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.

feat(health-checks): emit alert events on issue lifecycle transitions (#59984)

Rafael Audibert0f3cd8632109
diff --git a/posthog/temporal/health_checks/alerts.py b/posthog/temporal/health_checks/alerts.py
new file mode 100644
index 000000000000..6257faaa2b7b
--- /dev/null
+++ b/posthog/temporal/health_checks/alerts.py
@@ -0,0 +1,81 @@
+from typing import Literal
+
+import structlog
+
+from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event
+from posthog.exceptions_capture import capture_exception
+from posthog.models.health_issue import HealthIssue
+from posthog.temporal.health_checks.framework import AlertContent, HealthCheck
+from posthog.temporal.health_checks.registry import _DETECT_FNS, ensure_registry_loaded
+
+logger = structlog.get_logger(__name__)
+
+
+EVENT_FIRING = "$health_check_issue_firing"
+EVENT_RESOLVED = "$health_check_issue_resolved"
+
+
+# FUTURE: this module is the seam where a Signals-style inbox can plug in.
+# Health-check transitions already carry a uniform envelope (kind / severity /
+# title / summary / link / payload); a Signals integration can read from the
+# same event stream — keep that envelope stable as new fields are added.
+
+
+def _check_class_for_kind(kind: str) -> type[HealthCheck] | None:
+ # The registry only stores instance-bound detect callables, but every
+ # HealthCheck subclass binds `cls()` so the underlying class is reachable
+ # via the bound method's `__self__`. Ensure the registry is loaded so this
+ # works when called outside the orchestrator's primary code path.
+ ensure_registry_loaded()
+ fn = _DETECT_FNS.get(kind)
+ if fn is None:
+ return None
+ instance = getattr(fn, "__self__", None)
+ if instance is None:
+ return None
+ return type(instance)
+
+
+def _render(issue: HealthIssue) -> AlertContent:
+ check_cls = _check_class_for_kind(issue.kind)
+ if check_cls is None:
+ return AlertContent(title=issue.kind, summary=f"{issue.kind} ({issue.severity})", link="/health")
+ return check_cls.render_alert(issue)
+
+
+def emit_health_check_alert(issue: HealthIssue, *, status: Literal["firing", "resolved"]) -> bool:
+ """Emit one $health_check_issue_{firing,resolved} event for a transition.
+
+ Returns True if the event was produced. Failures (render or Kafka) are
+ swallowed and reported to error tracking so a single bad issue cannot
+ break the orchestrator batch.
+ """
+ try:
+ content = _render(issue)
+ produce_internal_event(
+ team_id=issue.team_id,
+ event=InternalEventEvent(
+ event=EVENT_FIRING if status == "firing" else EVENT_RESOLVED,
+ distinct_id=f"team_{issue.team_id}",
+ properties={
+ "kind": issue.kind,
+ "severity": issue.severity,
+ "issue_id": str(issue.id),
+ "title": content.title,
+ "summary": content.summary,
+ "link": content.link,
+ "payload": issue.payload,
+ },
+ ),
+ )
+ return True
+ except Exception as e:
+ logger.exception(
+ "Failed to emit health-check alert",
+ kind=issue.kind,
+ issue_id=str(issue.id),
+ status=status,
+ error=str(e),
+ )
+ capture_exception(e, additional_properties={"kind": issue.kind, "issue_id": str(issue.id), "status": status})
+ return False
diff --git a/posthog/temporal/health_checks/framework.py b/posthog/temporal/health_checks/framework.py
index 1ec86d524302..9c2466626a4d 100644
--- a/posthog/temporal/health_checks/framework.py
+++ b/posthog/temporal/health_checks/framework.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass
+from typing import TYPE_CHECKING
from posthog.clickhouse.query_tagging import Product
from posthog.dags.common.owners import JobOwners
@@ -8,6 +9,26 @@ from posthog.temporal.health_checks.detectors import DEFAULT_EXECUTION_POLICY, H
from posthog.temporal.health_checks.models import DEFAULT_ACTIVE_SINCE_DAYS, HealthCheckResult
from posthog.temporal.health_checks.registry import _DETECT_FNS, HEALTH_CHECKS
+if TYPE_CHECKING:
+ from posthog.models.health_issue import HealthIssue
+
+
+@dataclass(frozen=True)
+class AlertContent:
+ """User-facing description of a fired health-check alert.
+
+ Health checks override `HealthCheck.render_alert` to produce one of
+ these. The fields are embedded into `$health_check_issue_firing` and
+ `$health_check_issue_resolved` event properties, where HogFunction
+ templates pick them up as `event.properties.title`, etc.
+ """
+
+ title: str
+ summary: str
+ # Relative path inside the PostHog app (e.g. "/health/sdk-doctor").
+ # HogFunction templates concatenate this onto {project.url}.
+ link: str
+
@dataclass(frozen=True)
class HealthCheckRegistration:
@@ -67,3 +88,17 @@ class HealthCheck:
def detect(self, team_ids: list[int]) -> dict[int, list[HealthCheckResult]]:
raise NotImplementedError
+
+ @classmethod
+ def render_alert(cls, issue: HealthIssue) -> AlertContent:
+ """Build the alert content surfaced to HogFunction destinations.
+
+ The default produces a generic title/summary keyed off `kind` and
+ `severity` with a link to /health. Concrete checks override this to
+ produce a human-readable message that names the affected resource.
+ """
+ return AlertContent(
+ title=cls.name,
+ summary=f"{cls.kind} ({issue.severity})",
+ link="/health",
+ )
diff --git a/posthog/temporal/health_checks/processing.py b/posthog/temporal/health_checks/processing.py
index d166d9ced5b4..e38e2d6dc758 100644
--- a/posthog/temporal/health_checks/processing.py
+++ b/posthog/temporal/health_checks/processing.py
@@ -2,6 +2,7 @@ import time
import structlog
+from posthog.temporal.health_checks.alerts import emit_health_check_alert
from posthog.temporal.health_checks.db import resolve_stale_issues_with_deltas, upsert_issues_with_deltas
from posthog.temporal.health_checks.models import BatchDetectFn, BatchResult
from posthog.temporal.health_checks.validation import _validate_batch_output
@@ -51,4 +52,9 @@ def _process_batch_detection(
result.issues_resolved = len(newly_resolved)
result.resolve_duration = time.monotonic() - start
+ for issue in newly_active:
+ emit_health_check_alert(issue, status="firing")
+ for issue in newly_resolved:
+ emit_health_check_alert(issue, status="resolved")
+
return result
diff --git a/posthog/temporal/health_checks/tests/test_alert_emission.py b/posthog/temporal/health_checks/tests/test_alert_emission.py
new file mode 100644
index 000000000000..69dfa51fdef2
--- /dev/null
+++ b/posthog/temporal/health_checks/tests/test_alert_emission.py
@@ -0,0 +1,91 @@
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models.health_issue import HealthIssue
+from posthog.temporal.health_checks.alerts import EVENT_FIRING, EVENT_RESOLVED, emit_health_check_alert
+from posthog.temporal.health_checks.framework import AlertContent, HealthCheck
+
+
+class _StubCheck(HealthCheck):
+ # No name/kind class attributes -> __init_subclass__ skips auto-registration.
+ @classmethod
+ def render_alert(cls, issue: HealthIssue) -> AlertContent:
+ return AlertContent(title="stub title", summary=f"stub for {issue.kind}", link="/health/stub")
+
+
+class _BadCheck(HealthCheck):
+ @classmethod
+ def render_alert(cls, issue: HealthIssue) -> AlertContent:
+ raise ValueError("boom")
+
+
+def _make_issue(kind: str = "stub_check", severity: str = "warning") -> HealthIssue:
+ return HealthIssue(team_id=42, kind=kind, severity=severity, payload={"detail": "x"}, unique_hash="h")
+
+
+class TestEmitHealthCheckAlert(SimpleTestCase):
+ @patch("posthog.temporal.health_checks.alerts._check_class_for_kind", return_value=_StubCheck)
+ @patch("posthog.temporal.health_checks.alerts.produce_internal_event")
+ def test_firing_emits_event_with_envelope(self, produce, _lookup):
+ issue = _make_issue()
+ fired = emit_health_check_alert(issue, status="firing")
+ self.assertTrue(fired)
+ produce.assert_called_once()
+ kwargs = produce.call_args.kwargs
+ self.assertEqual(kwargs["team_id"], 42)
+ event = kwargs["event"]
+ self.assertEqual(event.event, EVENT_FIRING)
+ self.assertEqual(event.distinct_id, "team_42")
+ self.assertEqual(event.properties["kind"], "stub_check")
+ self.assertEqual(event.properties["severity"], "warning")
+ self.assertEqual(event.properties["title"], "stub title")
+ self.assertEqual(event.properties["summary"], "stub for stub_check")
+ self.assertEqual(event.properties["link"], "/health/stub")
+ self.assertEqual(event.properties["payload"], {"detail": "x"})
+
+ @patch("posthog.temporal.health_checks.alerts._check_class_for_kind", return_value=_StubCheck)
+ @patch("posthog.temporal.health_checks.alerts.produce_internal_event")
+ def test_resolved_emits_resolved_event(self, produce, _lookup):
+ emit_health_check_alert(_make_issue(), status="resolved")
+ self.assertEqual(produce.call_args.kwargs["event"].event, EVENT_RESOLVED)
+
+ @patch("posthog.temporal.health_checks.alerts._check_class_for_kind", return_value=None)
+ @patch("posthog.temporal.health_checks.alerts.produce_internal_event")
+ def test_unregistered_kind_falls_back_to_generic_content(self, produce, _lookup):
+ emit_health_check_alert(_make_issue(kind="not_in_registry"), status="firing")
+ props = produce.call_args.kwargs["event"].properties
+ # Generic fallback: title == kind, link defaults to /health
+ self.assertEqual(props["title"], "not_in_registry")
+ self.assertEqual(props["link"], "/health")
+
+ @parameterized.expand(
+ [
+ ("produce_fails", _StubCheck, RuntimeError("kafka down"), True),
+ ("render_fails", _BadCheck, None, False),
+ ]
+ )
+ def test_failure_is_swallowed_and_captured(
+ self,
+ _name: str,
+ check_cls: type[HealthCheck],
+ produce_side_effect: Exception | None,
+ expects_produce_call: bool,
+ ) -> None:
+ with (
+ patch("posthog.temporal.health_checks.alerts._check_class_for_kind", return_value=check_cls),
+ patch(
+ "posthog.temporal.health_checks.alerts.produce_internal_event",
+ side_effect=produce_side_effect,
+ ) as produce,
+ patch("posthog.temporal.health_checks.alerts.capture_exception") as capture,
+ ):
+ fired = emit_health_check_alert(_make_issue(), status="firing")
+ self.assertFalse(fired)
+ if expects_produce_call:
+ produce.assert_called_once()
+ else:
+ produce.assert_not_called()
+ capture.assert_called_once()
diff --git a/products/growth/backend/temporal/health_checks/sdk_outdated.py b/products/growth/backend/temporal/health_checks/sdk_outdated.py
index 0c1186e34e26..54a60b4d7899 100644
--- a/products/growth/backend/temporal/health_checks/sdk_outdated.py
+++ b/products/growth/backend/temporal/health_checks/sdk_outdated.py
@@ -7,7 +7,7 @@ from posthog.dags.common.owners import JobOwners
from posthog.models.health_issue import HealthIssue
from posthog.redis import get_client
from posthog.temporal.health_checks.detectors import HealthExecutionPolicy
-from posthog.temporal.health_checks.framework import HealthCheck
+from posthog.temporal.health_checks.framework import AlertContent, HealthCheck
from posthog.temporal.health_checks.models import HealthCheckResult
from posthog.temporal.health_checks.query import execute_clickhouse_health_team_query
@@ -18,6 +18,7 @@ from products.growth.backend.constants import (
github_sdk_versions_key,
team_sdk_versions_key,
)
+from products.growth.backend.sdk_health import _is_safe_for_interpolation
logger = structlog.get_logger(__name__)
@@ -86,6 +87,24 @@ class SdkOutdatedCheck(HealthCheck):
schedule = "0 8 * * *"
active_since_days = 30
+ @classmethod
+ def render_alert(cls, issue: HealthIssue) -> AlertContent:
+ sdk_name = issue.payload.get("sdk_name", "an SDK")
+ latest = issue.payload.get("latest_version") or "the latest version"
+ usage = issue.payload.get("usage") or []
+ # `lib_version` originates from the $lib_version event property — attacker
+ # controllable via project token. Gate it through the same allowlist used
+ # by SDK Doctor before interpolating into a string we forward to alert
+ # destinations (Slack, email, webhooks).
+ raw_current = usage[0].get("lib_version") if usage else None
+ current = raw_current if raw_current and _is_safe_for_interpolation(raw_current) else None
+ summary = f"{sdk_name} is on {current}, latest is {latest}" if current else f"{sdk_name} is behind {latest}"
+ return AlertContent(
+ title=f"{sdk_name} SDK is outdated",
+ summary=summary,
+ link="/health/sdk-doctor",
+ )
+
def detect(self, team_ids: list[int]) -> dict[int, list[HealthCheckResult]]:
github_data = _load_github_sdk_data()
if not github_data:
diff --git a/products/growth/backend/temporal/health_checks/tests/test_sdk_outdated.py b/products/growth/backend/temporal/health_checks/tests/test_sdk_outdated.py
index c4df1d23c272..e59d834d6c62 100644
--- a/products/growth/backend/temporal/health_checks/tests/test_sdk_outdated.py
+++ b/products/growth/backend/temporal/health_checks/tests/test_sdk_outdated.py
@@ -2,7 +2,9 @@ import json
from unittest.mock import MagicMock, patch
-from django.test import TestCase
+from django.test import SimpleTestCase, TestCase
+
+from parameterized import parameterized
from posthog.models.health_issue import HealthIssue
@@ -189,3 +191,29 @@ class TestSdkOutdatedCheck(TestCase):
mock_pipe.setex.assert_called_once()
_key, ttl, _payload = mock_pipe.setex.call_args[0]
assert ttl == TEAM_SDK_CACHE_EXPIRY
+
+
+class TestSdkOutdatedRenderAlert(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("safe_version", "1.198.0", "web is on 1.198.0, latest is 1.200.0"),
+ ("space_injection", "1.198.0 <https://evil.example|click>", "web is behind 1.200.0"),
+ ("newline_injection", "1.198.0\n@channel", "web is behind 1.200.0"),
+ ("markdown_injection", "**1.198.0**", "web is behind 1.200.0"),
+ ("empty_string", "", "web is behind 1.200.0"),
+ ]
+ )
+ def test_render_alert_rejects_unsafe_lib_version(self, _name: str, raw_version: str, expected_summary: str) -> None:
+ issue = HealthIssue(
+ team_id=1,
+ kind="sdk_outdated",
+ severity=HealthIssue.Severity.WARNING,
+ payload={
+ "sdk_name": "web",
+ "latest_version": "1.200.0",
+ "usage": [{"lib_version": raw_version, "count": 100, "max_timestamp": "2026-03-20"}],
+ },
+ unique_hash="h",
+ )
+ content = SdkOutdatedCheck.render_alert(issue)
+ assert content.summary == expected_summary