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(health-checks): drop deleted teams in HealthIssue.bulk_upsert (#60552)

posthog[bot]00795df20400
diff --git a/posthog/models/health_issue.py b/posthog/models/health_issue.py
index 3d2b20494e7c..9157f6a0dd5f 100644
--- a/posthog/models/health_issue.py
+++ b/posthog/models/health_issue.py
@@ -5,8 +5,39 @@ from typing import Any, Optional
from django.db import connection, models, transaction
from django.utils import timezone
+import structlog
+
from posthog.models.utils import UUIDModel
+logger = structlog.get_logger(__name__)
+
+
+def _filter_existing_team_ids(team_ids: set[int]) -> set[int]:
+ """Return the subset of team_ids that still exist in posthog_team.
+
+ Health checks snapshot team IDs at workflow start and dispatch them to
+ activities that may run minutes later — teams can be deleted in the
+ meantime. Callers use this to drop orphaned team_ids before writes so a
+ missing FK does not roll back the whole batch.
+ """
+ if not team_ids:
+ return set()
+
+ # Inline import — posthog.models.__init__ imports HealthIssue before Team,
+ # so a module-level `from posthog.models.team import Team` here would
+ # invert the load order and risk a partial-init failure.
+ from posthog.models.team import Team
+
+ existing = set(Team.objects.filter(id__in=team_ids).values_list("id", flat=True))
+ missing = team_ids - existing
+ if missing:
+ logger.warning(
+ "health_issue_dropping_deleted_teams",
+ dropped_count=len(missing),
+ dropped_team_ids=sorted(missing),
+ )
+ return existing
+
class HealthIssue(UUIDModel):
class Severity(models.TextChoices):
@@ -128,8 +159,22 @@ class HealthIssue(UUIDModel):
kind_lock_key = int.from_bytes(hashlib.sha256(kind.encode()).digest()[:4], "big", signed=True)
with transaction.atomic():
+ # Teams can be deleted between the workflow's team-ID snapshot and
+ # this upsert. A missing team would trigger a deferred FK violation
+ # at COMMIT and roll back every row in the batch, not just the
+ # orphan — so drop incoming rows for teams that no longer exist.
+ #
+ # Filter before acquiring advisory locks so we don't hold per-team
+ # locks for IDs we're about to drop.
+ team_ids = _filter_existing_team_ids({tid for tid, _ in incoming})
+ if not team_ids:
+ return []
+
+ # Drop incoming rows for teams that no longer exist
+ incoming = {key: value for key, value in incoming.items() if key[0] in team_ids}
+
with connection.cursor() as cursor:
- for team_id in sorted({tid for tid, _ in incoming}):
+ for team_id in sorted(team_ids):
cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [kind_lock_key, team_id])
existing_issues = {
@@ -137,7 +182,7 @@ class HealthIssue(UUIDModel):
for issue in cls.objects.filter(
kind=kind,
status=cls.Status.ACTIVE,
- team_id__in={tid for tid, _ in incoming},
+ team_id__in=team_ids,
unique_hash__in={h for _, h in incoming},
)
}
diff --git a/posthog/models/test/test_health_issue.py b/posthog/models/test/test_health_issue.py
index ed63dbf19721..18214b8ae3ed 100644
--- a/posthog/models/test/test_health_issue.py
+++ b/posthog/models/test/test_health_issue.py
@@ -199,3 +199,40 @@ class TestHealthIssue(BaseTest):
def test_bulk_resolve_no_active_issues_returns_empty_list(self):
resolved = HealthIssue.bulk_resolve("test_kind", {self.team.id})
self.assertEqual(resolved, [])
+
+ def test_bulk_upsert_skips_deleted_team_and_persists_remaining(self):
+ # Reproduces the FK violation that previously rolled back the entire
+ # batch when a team_id snapshotted at workflow start was deleted before
+ # bulk_upsert ran.
+ missing_team_id = self.team.id + 999_999
+ result = HealthIssue.bulk_upsert(
+ "test_kind",
+ [
+ self._bulk_payload("good"),
+ {
+ "team_id": missing_team_id,
+ "severity": "warning",
+ "payload": {"detail": "orphan"},
+ "unique_hash": "orphan",
+ },
+ ],
+ )
+ self.assertEqual({i.unique_hash for i in result}, {"good"})
+ self.assertTrue(HealthIssue.objects.filter(team=self.team, kind="test_kind", unique_hash="good").exists())
+ self.assertFalse(HealthIssue.objects.filter(unique_hash="orphan").exists())
+
+ def test_bulk_upsert_all_teams_missing_returns_empty(self):
+ missing_team_id = self.team.id + 999_999
+ result = HealthIssue.bulk_upsert(
+ "test_kind",
+ [
+ {
+ "team_id": missing_team_id,
+ "severity": "warning",
+ "payload": {"detail": "orphan"},
+ "unique_hash": "orphan",
+ }
+ ],
+ )
+ self.assertEqual(result, [])
+ self.assertFalse(HealthIssue.objects.filter(unique_hash="orphan").exists())
diff --git a/posthog/temporal/health_checks/db.py b/posthog/temporal/health_checks/db.py
index 13e06dfbae0e..50764a4e962b 100644
--- a/posthog/temporal/health_checks/db.py
+++ b/posthog/temporal/health_checks/db.py
@@ -1,4 +1,4 @@
-from posthog.models.health_issue import HealthIssue
+from posthog.models.health_issue import HealthIssue, _filter_existing_team_ids
from posthog.temporal.health_checks.models import HealthCheckResult
@@ -36,9 +36,15 @@ def resolve_stale_issues_with_deltas(
These are the rows that should trigger a `resolved` alert.
"""
all_team_ids = healthy_team_ids | set(issues_by_team.keys())
+ # Mirror the bulk_upsert filter — a team deleted mid-workflow already had
+ # its issues cascaded away, so resolving on its ID is wasted work and
+ # produces misleading `resolved` alerts if the IDs were ever reused.
+ all_team_ids = _filter_existing_team_ids(all_team_ids)
keep_hashes: dict[int, set[str]] = {}
for team_id, results in issues_by_team.items():
+ if team_id not in all_team_ids:
+ continue
keep_hashes[team_id] = {HealthIssue.compute_unique_hash(kind, r.payload, r.hash_keys) for r in results}
return HealthIssue.bulk_resolve(kind, all_team_ids, keep_hashes or None)
diff --git a/posthog/temporal/health_checks/tests/test_db.py b/posthog/temporal/health_checks/tests/test_db.py
new file mode 100644
index 000000000000..e48ce53e401d
--- /dev/null
+++ b/posthog/temporal/health_checks/tests/test_db.py
@@ -0,0 +1,55 @@
+from posthog.test.base import BaseTest
+
+from posthog.models.health_issue import HealthIssue
+from posthog.temporal.health_checks.db import resolve_stale_issues_with_deltas, upsert_issues_with_deltas
+from posthog.temporal.health_checks.models import HealthCheckResult
+
+
+class TestResolveStaleIssuesWithDeltas(BaseTest):
+ def _seed_active_issue(self, kind: str, unique_hash: str) -> HealthIssue:
+ return HealthIssue.objects.create(
+ team=self.team,
+ kind=kind,
+ severity=HealthIssue.Severity.WARNING,
+ payload={},
+ unique_hash=unique_hash,
+ status=HealthIssue.Status.ACTIVE,
+ )
+
+ def test_resolves_issues_for_existing_teams(self):
+ self._seed_active_issue("test_kind", "h1")
+ resolved = resolve_stale_issues_with_deltas("test_kind", {}, healthy_team_ids={self.team.id})
+ self.assertEqual({i.unique_hash for i in resolved}, {"h1"})
+
+ def test_skips_deleted_team_id_in_healthy_set(self):
+ missing_team_id = self.team.id + 999_999
+ self._seed_active_issue("test_kind", "h1")
+ resolved = resolve_stale_issues_with_deltas(
+ "test_kind",
+ {},
+ healthy_team_ids={self.team.id, missing_team_id},
+ )
+ self.assertEqual({i.unique_hash for i in resolved}, {"h1"})
+
+ def test_upsert_skips_deleted_team_without_aborting_batch(self):
+ # Reproduces the production failure: a team_id snapshotted at workflow
+ # start is deleted before the upsert runs. The deferred FK check used
+ # to fire at COMMIT and roll back the live team's issue along with the
+ # orphan. After the fix the orphan is filtered out and the live team's
+ # issue persists.
+ missing_team_id = self.team.id + 999_999
+ issues_by_team = {
+ self.team.id: [
+ HealthCheckResult(severity=HealthIssue.Severity.WARNING, payload={"detail": "x"}, hash_keys=[])
+ ],
+ missing_team_id: [
+ HealthCheckResult(severity=HealthIssue.Severity.WARNING, payload={"detail": "y"}, hash_keys=[])
+ ],
+ }
+
+ created = upsert_issues_with_deltas("test_kind", issues_by_team)
+ self.assertEqual({i.team_id for i in created}, {self.team.id})
+ self.assertTrue(
+ HealthIssue.objects.filter(team=self.team, kind="test_kind", status=HealthIssue.Status.ACTIVE).exists()
+ )
+ self.assertFalse(HealthIssue.objects.filter(team_id=missing_team_id).exists())