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(stamphog): bind a large installation without a write per repository (#102059)

Julian Beza8c6e825bd52
diff --git a/products/stamphog/backend/facade/api.py b/products/stamphog/backend/facade/api.py
index 57c8a526cf47..79dda729e508 100644
--- a/products/stamphog/backend/facade/api.py
+++ b/products/stamphog/backend/facade/api.py
@@ -10,6 +10,7 @@ from __future__ import annotations
from collections.abc import Callable, Iterator, Sequence
from typing import Any, TypeVar, overload
+from uuid import UUID
from django.db import IntegrityError, router, transaction
from django.db.models import Q, QuerySet
@@ -192,6 +193,20 @@ def get_repo_config(team_id: int, repository: str) -> contracts.RepoConfigDTO |
return _repo_config_to_dto(obj) if obj is not None else None
+def get_repo_config_by_id(team_id: int, config_id: str) -> contracts.RepoConfigDTO | None:
+ """Resolve one config by its primary key, or None when the team has no such row.
+
+ An id that is not a UUID is a miss rather than an error, because the value comes straight off
+ the URL and Django raises on a malformed one before the query runs.
+ """
+ try:
+ parsed_id = UUID(config_id)
+ except ValueError:
+ return None
+ obj = StamphogRepoConfig.objects.for_team(team_id).filter(id=parsed_id).first()
+ return _repo_config_to_dto(obj) if obj is not None else None
+
+
def has_reviewable_repo_config(team_id: int) -> bool:
"""Whether the team has at least one enabled repo config that hosted reviews can run on.
diff --git a/products/stamphog/backend/facade/github.py b/products/stamphog/backend/facade/github.py
index ff1125852022..3ba0ef07d2bf 100644
--- a/products/stamphog/backend/facade/github.py
+++ b/products/stamphog/backend/facade/github.py
@@ -16,6 +16,7 @@ from django.db import IntegrityError, router, transaction
from django.utils import timezone
from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated
+from posthog.models.scoping.manager import resolve_effective_team_id
from products.stamphog.backend.activity_logging import (
log_repo_config_bulk_update,
@@ -42,6 +43,11 @@ __all__ = [
"user_can_access_installation",
]
+# How many repo-config rows go into one INSERT. An installation can expose thousands of
+# repositories, and every row in a statement adds its columns to that statement's bind-parameter
+# list, so the batch is chunked to stay clear of Postgres' per-statement parameter ceiling.
+_CREATE_BATCH_SIZE = 500
+
def _adopt_preexisting_config(team_id: int, repository: str, installation_id: str) -> StamphogRepoConfig | None:
"""Bind a manually-created (installation-less) config to a now-verified installation.
@@ -108,70 +114,117 @@ def sync_installation_repositories(
prove installation ownership is the right principal (the original installer may be long gone).
"""
repositories = list_user_accessible_repositories(installation_id, user_token)
- synced: list[StamphogRepoConfig] = []
+ # bulk_create below skips ProductTeamModel.save(), which is what normally rewrites team_id to the
+ # canonical id, so resolve it here instead and pass canonical=True from then on. for_team()
+ # resolves per call, so this also holds the whole sync to one Team lookup.
+ team_id = resolve_effective_team_id(team_id)
+ # Pin the reads and the writes to the model's routed DB (stamphog_db_writer when the product DB
+ # is configured, else default). A lagged reader would miss a row this sync just wrote and try to
+ # create it again.
+ write_db = router.db_for_write(StamphogRepoConfig)
+
+ # One read for the whole installation rather than one per repository. An organization that
+ # installs the App on all of its repositories can expose thousands of them, and a per-repository
+ # round trip made the request cost grow with that count until it ran past the gateway timeout.
+ # A re-sync now finds every row here and does no write work at all.
+ resolved: dict[str, StamphogRepoConfig] = {
+ config.repository: config
+ for config in StamphogRepoConfig.objects.for_team(team_id, canonical=True)
+ .using(write_db)
+ .filter(provider="github", installation_id=installation_id, repository__in=repositories)
+ }
+
created_rows: list[dict[str, Any]] = []
skipped: list[str] = []
- # Bind the per-row savepoint to the model's routed DB (stamphog_db_writer when the product DB is
- # configured, else default) — a bare atomic() opens on the default connection, so the get_or_create
- # would run outside any transaction on the product DB.
- write_db = router.db_for_write(StamphogRepoConfig)
- # One installation can expose thousands of repositories. Let the loop create the rows without a
- # per-row audit write and log the creates in one batch below; an adoption still logs its own diff.
- # The batch runs in a finally: a row that is already committed when the loop dies would otherwise
- # never be logged, and a retry sees it as pre-existing, so its creation is lost for good.
+ # Create the rows without a per-row audit write and log the creates in one batch below; an
+ # adoption still logs its own diff. The batch runs in a finally: a row that is already committed
+ # when the work dies would otherwise never be logged, and a retry sees it as pre-existing, so its
+ # creation is lost for good.
try:
with suppress_created_activity():
- for full_name in repositories:
- # Per-row savepoint: an IntegrityError only rolls back that row, leaving the rest of the
- # batch (and the outer autocommit context) intact.
- try:
- with transaction.atomic(using=write_db):
- config, was_created = StamphogRepoConfig.objects.for_team(team_id).get_or_create(
- provider="github",
- installation_id=installation_id,
- repository=full_name,
- # for_team() scopes the read but not row creation, so team_id is explicit
- # here. Bind disabled: an installation can surface hundreds of repos, so
- # connect them but don't start reviewing until a human toggles each on.
- # enabled only seeds new rows; an existing row's toggle is never flipped.
- # The connecting user is seeded here too, so a new row does not need the
- # restamp below and its activity log shows one "connected" entry instead of
- # a create plus a connector change.
- defaults={
- "team_id": team_id,
- "enabled": False,
- "connected_by_user_id": connected_by_user_id,
- },
- )
- except IntegrityError:
- # The unique (team, repository) constraint tripped: a same-team row for this repo
- # already exists under a different installation_id — the manually-created config
- # (blank installation) finally being bound. Adopt it instead of skipping; only a
- # real conflict (already bound to another installation) stays skipped.
- adopted = _adopt_preexisting_config(team_id, full_name, installation_id)
+ candidates = [
+ StamphogRepoConfig(
+ # for_team() scopes a read but not row creation, so team_id is explicit here.
+ team_id=team_id,
+ provider="github",
+ installation_id=installation_id,
+ repository=full_name,
+ # Bind disabled: an installation can surface hundreds of repos, so connect them
+ # but don't start reviewing until a human toggles each one on.
+ enabled=False,
+ # The connecting user is seeded here, so a new row does not need the restamp
+ # below and its activity log shows one "connected" entry instead of a create
+ # plus a connector change.
+ connected_by_user_id=connected_by_user_id,
+ )
+ for full_name in repositories
+ if full_name not in resolved
+ ]
+ if candidates:
+ # The rows and the record of which ones this call inserted have to commit together.
+ # An unwrapped bulk_create commits on its own, so a failure of the read-back would
+ # leave the rows in place with created_rows empty, and the retry would then see them
+ # as pre-existing and never write their audit entries.
+ with transaction.atomic(using=write_db):
+ # ON CONFLICT DO NOTHING, so both unique constraints still decide which rows land
+ # and a concurrent sync of the same installation cannot make this raise.
+ # bulk_create also sends no per-row save signal, which is the audit outcome the
+ # suppression above gives the rest of this block.
+ StamphogRepoConfig.objects.for_team(team_id, canonical=True).using(write_db).bulk_create(
+ candidates, ignore_conflicts=True, batch_size=_CREATE_BATCH_SIZE
+ )
+ # The primary keys are generated in Python, so reading them back says exactly
+ # which candidates this call inserted. ignore_conflicts reports nothing itself,
+ # and a row that lost to a conflict needs the per-row resolution below.
+ inserted_ids = set(
+ StamphogRepoConfig.objects.for_team(team_id, canonical=True)
+ .using(write_db)
+ .filter(id__in=[candidate.id for candidate in candidates])
+ .values_list("id", flat=True)
+ )
+ # Recorded before the resolution below, so a failure in it still logs every row that
+ # landed.
+ created_rows.extend(
+ {"id": candidate.id, "repository": candidate.repository}
+ for candidate in candidates
+ if candidate.id in inserted_ids
+ )
+ for candidate in candidates:
+ if candidate.id in inserted_ids:
+ resolved[candidate.repository] = candidate
+ continue
+ # A unique constraint holds this repository. Either the same team already has it
+ # under a different installation_id, which is the manually-created config (blank
+ # installation) finally being bound, so adopt it; or another team owns the triple,
+ # which stays skipped.
+ adopted = _adopt_preexisting_config(team_id, candidate.repository, installation_id)
if adopted is None:
- skipped.append(full_name)
+ skipped.append(candidate.repository)
else:
- synced.append(adopted)
- continue
- synced.append(config)
- if was_created:
- created_rows.append({"id": config.id, "repository": config.repository})
+ resolved[candidate.repository] = adopted
finally:
log_repo_configs_created(
team_id, created_rows, user=get_current_user(), was_impersonated=get_was_impersonated()
)
- if synced:
+ # Answer in the order GitHub listed the repositories, which is the order the connect screen renders.
+ synced = [resolved[full_name] for full_name in repositories if full_name in resolved]
+ # A row this call inserted already carries the caller as its connector, so only a pre-existing row
+ # can need a restamp. Leaving the new ones out also keeps a first-time sync of a large installation
+ # from locking every row it just created.
+ created_ids = {row["id"] for row in created_rows}
+ restamp_ids = [config.id for config in synced if config.id not in created_ids]
+
+ if restamp_ids:
with transaction.atomic(using=write_db):
# Lock the rows and re-read the connector rather than trusting the objects above: two
# syncs of the same installation running at once both hold the same stale value, so a
# real A -> B handover would be logged twice, as C -> A and C -> B.
locked = (
- StamphogRepoConfig.objects.for_team(team_id)
+ StamphogRepoConfig.objects.for_team(team_id, canonical=True)
.using(write_db)
.select_for_update()
- .filter(id__in=[c.id for c in synced])
+ .filter(id__in=restamp_ids)
.values_list("id", "repository", "connected_by_user_id")
)
restamped: list[dict[str, Any]] = [
@@ -181,9 +234,9 @@ def sync_installation_repositories(
]
if restamped:
# .update() bypasses auto_now, so updated_at is set by hand.
- StamphogRepoConfig.objects.for_team(team_id).filter(id__in=[row["id"] for row in restamped]).update(
- connected_by_user_id=connected_by_user_id, updated_at=timezone.now()
- )
+ StamphogRepoConfig.objects.for_team(team_id, canonical=True).filter(
+ id__in=[row["id"] for row in restamped]
+ ).update(connected_by_user_id=connected_by_user_id, updated_at=timezone.now())
# update() bypasses the model signal, so the change is logged here.
log_repo_config_bulk_update(
team_id,
diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.py
index f8a8dfaeb2cf..d1f238d46609 100644
--- a/products/stamphog/backend/presentation/views.py
+++ b/products/stamphog/backend/presentation/views.py
@@ -187,10 +187,11 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
serializer_class = StamphogRepoConfigSerializer
def _get_or_404(self, pk: str | None) -> contracts.RepoConfigDTO:
- for config in facade_api.list_repo_configs(self.canonical_team_id):
- if str(config.id) == str(pk):
- return config
- raise NotFound()
+ # A keyed lookup, not a scan: an installation can surface hundreds of repositories.
+ config = facade_api.get_repo_config_by_id(self.canonical_team_id, str(pk))
+ if config is None:
+ raise NotFound()
+ return config
def _require_review_gate_manager(self, request: Request) -> None:
"""Refuse a review-gating write below the manager level on the stamphog resource.
diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.py
index 0de393606da7..76eecb5a61a9 100644
--- a/products/stamphog/backend/tests/test_api.py
+++ b/products/stamphog/backend/tests/test_api.py
@@ -374,6 +374,11 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):
response = self.client.get(f"{self.url}{theirs.id}/")
assert response.status_code == status.HTTP_404_NOT_FOUND
+ def test_malformed_config_id_is_a_404(self) -> None:
+ # An id that is not a UUID has to read as a miss, or a bad URL becomes a 500.
+ response = self.client.get(f"{self.url}not-a-uuid/")
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
def test_cannot_delete_other_teams_config(self) -> None:
other_team = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user)
theirs = StamphogRepoConfig.objects.unscoped().create(
@@ -662,6 +667,54 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
connected_names.add(log.detail["name"])
assert connected_names == {"PostHog/other", "PostHog/posthog"}
+ @patch(
+ f"{_GITHUB_FACADE}.list_user_accessible_repositories",
+ return_value=["PostHog/mine", "PostHog/theirs"],
+ )
+ @patch(f"{_VIEWS}.user_can_access_installation", return_value=True)
+ @patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")
+ def test_sync_skips_a_repo_another_team_already_owns(self, mock_exchange, mock_verify, mock_list) -> None:
+ # Without the read-back that says which rows landed, a repo another team holds under this
+ # installation answers as synced and its webhooks resolve to the wrong team.
+ other_team = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user)
+ theirs = StamphogRepoConfig.objects.unscoped().create(
+ team_id=other_team.id, repository="PostHog/theirs", installation_id="42"
+ )
+
+ response = self.client.post(
+ self.url, {"installation_id": "42", "code": "oauth-code", "state": self.state}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert [row["repository"] for row in body["synced"]] == ["PostHog/mine"]
+ assert body["skipped"] == ["PostHog/theirs"]
+ theirs.refresh_from_db()
+ assert theirs.team_id == other_team.id
+ assert not (
+ StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id, repository="PostHog/theirs").exists()
+ )
+
+ @patch(
+ f"{_GITHUB_FACADE}.list_user_accessible_repositories",
+ return_value=["PostHog/posthog", "PostHog/other"],
+ )
+ @patch(f"{_VIEWS}.user_can_access_installation", return_value=True)
+ @patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")
+ def test_resyncing_an_installation_creates_nothing_new(self, mock_exchange, mock_verify, mock_list) -> None:
+ # A regression here duplicates the connected audit entries and makes each re-sync cost grow.
+ payload = {"installation_id": "42", "code": "oauth-code", "state": self.state}
+ assert self.client.post(self.url, payload, format="json").status_code == status.HTTP_200_OK
+
+ response = self.client.post(self.url, payload, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert sorted(row["repository"] for row in body["synced"]) == ["PostHog/other", "PostHog/posthog"]
+ assert body["skipped"] == []
+ assert StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id).count() == 2
+ assert ActivityLog.objects.filter(scope="StamphogRepoConfig", activity="created").count() == 2
+
@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories", return_value=["PostHog/posthog"])
@patch(f"{_VIEWS}.user_can_access_installation", return_value=True)
@patch(f"{_VIEWS}.exchange_oauth_code_for_user_token", return_value="user-token")