: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
feat(health-checks): return lifecycle deltas from bulk_upsert/bulk_resolve (#59983)
Rafael Audibertd4ea2a3f0a82
diff --git a/posthog/models/health_issue.py b/posthog/models/health_issue.pyindex 93ed53fa47cc..3d2b20494e7c 100644--- a/posthog/models/health_issue.py+++ b/posthog/models/health_issue.py@@ -2,7 +2,7 @@ import jsonimport hashlibfrom typing import Any, Optional-from django.db import models, transaction+from django.db import connection, models, transactionfrom django.utils import timezonefrom posthog.models.utils import UUIDModel@@ -98,9 +98,19 @@ class HealthIssue(UUIDModel):cls,kind: str,issues: list[dict[str, Any]],- ) -> int:+ ) -> list["HealthIssue"]:+ """Upsert health issues; returns the rows that became active in this call.++ A row is "newly active" when it had no matching ACTIVE row before — this+ covers both brand-new issues and ones transitioning RESOLVED → ACTIVE+ (the partial unique constraint only covers ACTIVE rows, so a resolved+ row with the same hash does not block creation of a new active one).+ Rows that were already ACTIVE and just got their severity/payload+ refreshed are *not* returned — alert emission should fire on lifecycle+ transitions, not on every detection tick.+ """if not issues:- return 0+ return []now = timezone.now()@@ -109,7 +119,19 @@ class HealthIssue(UUIDModel):key = (issue["team_id"], issue["unique_hash"])incoming[key] = issue+ # Serialize concurrent upserts for the same (kind, team_id) — SELECT+ # FOR UPDATE can't lock a row that doesn't exist yet, and READ+ # COMMITTED doesn't lock gaps, so two callers would otherwise both+ # decide a hash is new and race into a duplicate bulk_create. Locks+ # acquired in sorted order to avoid deadlocks across overlapping+ # team_id sets.+ kind_lock_key = int.from_bytes(hashlib.sha256(kind.encode()).digest()[:4], "big", signed=True)+with transaction.atomic():+ with connection.cursor() as cursor:+ for team_id in sorted({tid for tid, _ in incoming}):+ cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [kind_lock_key, team_id])+existing_issues = {(issue.team_id, issue.unique_hash): issuefor issue in cls.objects.filter(@@ -150,7 +172,7 @@ class HealthIssue(UUIDModel):if to_update:HealthIssue.objects.bulk_update(to_update, fields=["severity", "payload", "updated_at"])- return len(to_create) + len(to_update)+ return to_create@classmethoddef bulk_resolve(@@ -158,43 +180,65 @@ class HealthIssue(UUIDModel):kind: str,team_ids: set[int],keep_hashes: dict[int, set[str]] | None = None,- ) -> int:+ ) -> list["HealthIssue"]:+ """Resolve stale active issues; returns the rows that transitioned ACTIVE -> RESOLVED.++ Each row is fetched before the update so callers can fire side effects+ (e.g. alert emission) on the exact set of transitioned rows. The+ in-memory copies are mutated to reflect post-update state.+ """if not team_ids:- return 0+ return []now = timezone.now()+ def _mark_resolved(rows: list[HealthIssue]) -> None:+ for row in rows:+ row.status = cls.Status.RESOLVED+ row.resolved_at = now+ row.updated_at = now++ resolved_rows: list[HealthIssue] = []+with transaction.atomic():if not keep_hashes:- return cls.objects.filter(+ qs = HealthIssue.objects.filter(kind=kind,status=cls.Status.ACTIVE,team_id__in=team_ids,- ).update(status=cls.Status.RESOLVED, resolved_at=now, updated_at=now)+ )+ resolved_rows = list(qs.select_for_update())+ qs.update(status=cls.Status.RESOLVED, resolved_at=now, updated_at=now)+ _mark_resolved(resolved_rows)+ return resolved_rowskeep_hashes_by_team = {team_id: hashes for team_id, hashes in keep_hashes.items() if team_id in team_ids}team_ids_without_keep_hashes = team_ids - set(keep_hashes_by_team.keys())- resolved = 0-if team_ids_without_keep_hashes:- resolved += cls.objects.filter(+ qs = HealthIssue.objects.filter(kind=kind,status=cls.Status.ACTIVE,team_id__in=team_ids_without_keep_hashes,- ).update(status=cls.Status.RESOLVED, resolved_at=now, updated_at=now)+ )+ batch = list(qs.select_for_update())+ qs.update(status=cls.Status.RESOLVED, resolved_at=now, updated_at=now)+ resolved_rows.extend(batch)for team_id, hashes in keep_hashes_by_team.items():- team_qs = cls.objects.filter(+ team_qs = HealthIssue.objects.filter(kind=kind,status=cls.Status.ACTIVE,team_id=team_id,)if hashes:team_qs = team_qs.exclude(unique_hash__in=hashes)- resolved += team_qs.update(status=cls.Status.RESOLVED, resolved_at=now, updated_at=now)+ batch = list(team_qs.select_for_update())+ team_qs.update(status=cls.Status.RESOLVED, resolved_at=now, updated_at=now)+ resolved_rows.extend(batch)- return resolved+ _mark_resolved(resolved_rows)+ return resolved_rowsdef resolve(self) -> None:if self.status != self.Status.ACTIVE:diff --git a/posthog/models/test/test_health_issue.py b/posthog/models/test/test_health_issue.pyindex 431108dd6d0f..ed63dbf19721 100644--- a/posthog/models/test/test_health_issue.py+++ b/posthog/models/test/test_health_issue.py@@ -142,3 +142,60 @@ class TestHealthIssue(BaseTest):issue.resolve()issue.refresh_from_db()self.assertIsNotNone(issue.resolved_at)++ def _bulk_payload(self, unique_hash: str, severity: str = "warning") -> dict:+ return {+ "team_id": self.team.id,+ "severity": severity,+ "payload": {"detail": unique_hash},+ "unique_hash": unique_hash,+ }++ def test_bulk_upsert_returns_newly_created_issues(self):+ created = HealthIssue.bulk_upsert("test_kind", [self._bulk_payload("a"), self._bulk_payload("b")])+ self.assertEqual({i.unique_hash for i in created}, {"a", "b"})+ self.assertTrue(all(i.status == HealthIssue.Status.ACTIVE for i in created))++ def test_bulk_upsert_does_not_return_already_active_issues(self):+ HealthIssue.bulk_upsert("test_kind", [self._bulk_payload("a", severity="warning")])+ second_pass = HealthIssue.bulk_upsert("test_kind", [self._bulk_payload("a", severity="critical")])+ self.assertEqual(second_pass, [])++ existing = HealthIssue.objects.get(team=self.team, kind="test_kind", unique_hash="a")+ self.assertEqual(existing.severity, "critical")++ def test_bulk_upsert_returns_reactivated_issue(self):+ first = HealthIssue.bulk_upsert("test_kind", [self._bulk_payload("a")])+ self.assertEqual(len(first), 1)+ first[0].resolve()++ reactivated = HealthIssue.bulk_upsert("test_kind", [self._bulk_payload("a")])+ self.assertEqual(len(reactivated), 1)+ self.assertEqual(reactivated[0].unique_hash, "a")+ self.assertEqual(reactivated[0].status, HealthIssue.Status.ACTIVE)+ self.assertNotEqual(reactivated[0].id, first[0].id)++ def test_bulk_upsert_empty_input_returns_empty_list(self):+ self.assertEqual(HealthIssue.bulk_upsert("test_kind", []), [])++ def test_bulk_resolve_returns_transitioned_rows(self):+ created = HealthIssue.bulk_upsert("test_kind", [self._bulk_payload("a"), self._bulk_payload("b")])+ self.assertEqual(len(created), 2)++ resolved = HealthIssue.bulk_resolve("test_kind", {self.team.id})+ self.assertEqual({i.unique_hash for i in resolved}, {"a", "b"})+ self.assertTrue(all(i.status == HealthIssue.Status.RESOLVED for i in resolved))+ self.assertTrue(all(i.resolved_at is not None for i in resolved))++ def test_bulk_resolve_with_keep_hashes_skips_active(self):+ HealthIssue.bulk_upsert("test_kind", [self._bulk_payload("a"), self._bulk_payload("b")])+ resolved = HealthIssue.bulk_resolve("test_kind", {self.team.id}, keep_hashes={self.team.id: {"a"}})+ self.assertEqual({i.unique_hash for i in resolved}, {"b"})+ self.assertTrue(HealthIssue.objects.filter(unique_hash="a", status=HealthIssue.Status.ACTIVE).exists())++ def test_bulk_resolve_empty_team_ids_returns_empty_list(self):+ self.assertEqual(HealthIssue.bulk_resolve("test_kind", set()), [])++ def test_bulk_resolve_no_active_issues_returns_empty_list(self):+ resolved = HealthIssue.bulk_resolve("test_kind", {self.team.id})+ self.assertEqual(resolved, [])diff --git a/posthog/temporal/health_checks/db.py b/posthog/temporal/health_checks/db.pyindex 279f6adedb83..13e06dfbae0e 100644--- a/posthog/temporal/health_checks/db.py+++ b/posthog/temporal/health_checks/db.py@@ -2,10 +2,16 @@ from posthog.models.health_issue import HealthIssuefrom posthog.temporal.health_checks.models import HealthCheckResult-def _upsert_issues(+def upsert_issues_with_deltas(kind: str,issues_by_team: dict[int, list[HealthCheckResult]],-) -> int:+) -> list[HealthIssue]:+ """Upsert health issues from a batch detection result.++ Returns the rows that became active in this call (newly created or+ transitioned from RESOLVED). These are the rows that should trigger+ a `firing` alert.+ """issues = [{"team_id": team_id,@@ -19,11 +25,16 @@ def _upsert_issues(return HealthIssue.bulk_upsert(kind, issues)-def _resolve_stale_issues(+def resolve_stale_issues_with_deltas(kind: str,issues_by_team: dict[int, list[HealthCheckResult]],healthy_team_ids: set[int],-) -> int:+) -> list[HealthIssue]:+ """Resolve issues for teams that no longer trip the check.++ Returns the rows that transitioned ACTIVE -> RESOLVED in this call.+ These are the rows that should trigger a `resolved` alert.+ """all_team_ids = healthy_team_ids | set(issues_by_team.keys())keep_hashes: dict[int, set[str]] = {}diff --git a/posthog/temporal/health_checks/processing.py b/posthog/temporal/health_checks/processing.pyindex c5bc46cb766f..d166d9ced5b4 100644--- a/posthog/temporal/health_checks/processing.py+++ b/posthog/temporal/health_checks/processing.py@@ -2,7 +2,7 @@ import timeimport structlog-from posthog.temporal.health_checks.db import _resolve_stale_issues, _upsert_issues+from posthog.temporal.health_checks.db import resolve_stale_issues_with_deltas, upsert_issues_with_deltasfrom posthog.temporal.health_checks.models import BatchDetectFn, BatchResultfrom posthog.temporal.health_checks.validation import _validate_batch_output@@ -40,13 +40,15 @@ def _process_batch_detection(return resultstart = time.monotonic()- result.issues_upserted = _upsert_issues(kind, issues_by_team)+ newly_active = upsert_issues_with_deltas(kind, issues_by_team)+ result.issues_upserted = len(newly_active)result.db_write_duration = time.monotonic() - starthealthy_team_ids = set(team_ids) - set(issues_by_team.keys())start = time.monotonic()- result.issues_resolved = _resolve_stale_issues(kind, issues_by_team, healthy_team_ids)+ newly_resolved = resolve_stale_issues_with_deltas(kind, issues_by_team, healthy_team_ids)+ result.issues_resolved = len(newly_resolved)result.resolve_duration = time.monotonic() - startreturn result