: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(growth): compute sdk outdated alerts from real heuristics (#60563)
Rafael Audibertbf646d47ebf6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f6c708838a4c..7e5e9c226cf4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4883,9 +4883,9 @@ snapshots:scenes-app-health-tables--pipeline-empty--light:hash: v1.k794b7964.ec1a0c63234885fd64e3f15987d197f5e61ac21ba61c361fdf20f83106e19507.uH1VQA7HYxgCOJDUbkbAMwselmpdht-EQkv3psoMnhkscenes-app-health-tables--sdk-outdated-default--dark:- hash: v1.k794b7964.e344806c26ccc68f19d8597a6d7d0be2fd89157df30846cfad4fdcffbc08dc11.IVXYUX-acvQ6EZoP7Ew8y_TihseHmFnivD_JGwKnX38+ hash: v1.k794b7964.ab9ab6cbaa1e7d8fdfbb188a9b0a8491837df0e22a58bd54b617ece4abf0a43b.Bbll2XYBtMUl_ALsNRDvOItQvugleRkMnv2-8HINpywscenes-app-health-tables--sdk-outdated-default--light:- hash: v1.k794b7964.161c288ace9b18064492e3bc808933df5a517bdf7b43a1e30c41d05719bf7fb6.ozDmY7tz3h081KV7F8mdQ8PaG7Df49Nes54WDm0Gtms+ hash: v1.k794b7964.45c25f801bc1fbc052079379dba03267fc2f0f80d39816f201576118cceb3b82.uGSSujU_XkiaTmQnAmBa88Qdcec89qAIp0CKeloUHyQscenes-app-health-tables--sdk-outdated-empty--dark:hash: v1.k794b7964.203934be2d5f83fe3faa72101ad0396838076b862f2fc5759e6cc31689a8040d.Bwi0yxffqQ6k3FM-9vDFCa66Cw-DIy1ubxHZ39gR-ZAscenes-app-health-tables--sdk-outdated-empty--light:diff --git a/frontend/src/scenes/health/components/HealthTables.stories.tsx b/frontend/src/scenes/health/components/HealthTables.stories.tsxindex e69382b2c176..9ddc8e393b4e 100644--- a/frontend/src/scenes/health/components/HealthTables.stories.tsx+++ b/frontend/src/scenes/health/components/HealthTables.stories.tsx@@ -193,6 +193,10 @@ const SDK_OUTDATED_ISSUE: HealthIssue = createMockIssue('sdk-1', {payload: {sdk_name: 'web',latest_version: '1.142.0',+ current_version: '1.142.0',+ // The latest in-use version already matches latest, but an older version is still+ // serving a significant share of traffic — the reason explains both.+ reason: 'Latest in-use version 1.142.0 matches latest 1.142.0. Outdated versions still handling >= 20% of traffic: 1.130.0.',usage: [{lib_version: '1.142.0',@@ -200,6 +204,8 @@ const SDK_OUTDATED_ISSUE: HealthIssue = createMockIssue('sdk-1', {max_timestamp: '2025-01-15T09:30:00Z',release_date: '2025-01-10T00:00:00Z',is_latest: true,+ is_outdated: false,+ status_reason: 'You have the latest available.',},{lib_version: '1.138.4',@@ -207,13 +213,17 @@ const SDK_OUTDATED_ISSUE: HealthIssue = createMockIssue('sdk-1', {max_timestamp: '2025-01-14T22:15:00Z',release_date: '2024-12-18T00:00:00Z',is_latest: false,+ is_outdated: false,+ status_reason: "Released 4 weeks ago. Upgrading is a good idea, but it's not urgent yet.",},{lib_version: '1.130.0',- count: 312,+ count: 31200,max_timestamp: '2025-01-12T06:00:00Z',release_date: '2024-10-02T00:00:00Z',is_latest: false,+ is_outdated: true,+ status_reason: 'Released 3 months ago. Upgrade recommended.',},],},diff --git a/frontend/src/scenes/health/renderers/SdkOutdatedRenderer.tsx b/frontend/src/scenes/health/renderers/SdkOutdatedRenderer.tsxindex ecb95a45c50b..7b7b8cb97422 100644--- a/frontend/src/scenes/health/renderers/SdkOutdatedRenderer.tsx+++ b/frontend/src/scenes/health/renderers/SdkOutdatedRenderer.tsx@@ -1,4 +1,4 @@-import { LemonTag, Link } from '@posthog/lemon-ui'+import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { SDK_DOCS_LINKS, SDK_TYPE_READABLE_NAME } from 'scenes/onboarding/sdks/sdkConstants'@@ -12,11 +12,31 @@ interface UsageEntry {max_timestamp: stringrelease_date: string | nullis_latest: boolean+ is_outdated?: boolean+ status_reason?: string+}++const statusTag = (entry: UsageEntry): JSX.Element => {+ const tag = entry.is_latest ? (+ <LemonTag type="success" size="small">+ Current+ </LemonTag>+ ) : entry.is_outdated ? (+ <LemonTag type="danger" size="small">+ Outdated+ </LemonTag>+ ) : (+ <LemonTag type="warning" size="small">+ Behind+ </LemonTag>+ )+ return entry.status_reason ? <Tooltip title={entry.status_reason}>{tag}</Tooltip> : tag}export const SdkOutdatedRenderer = ({ issue }: { issue: HealthIssue }): JSX.Element => {const sdkName = issue.payload.sdk_name as SdkType | undefinedconst latestVersion = issue.payload.latest_version as string | undefined+ const reason = issue.payload.reason as string | undefinedconst usage = issue.payload.usage as UsageEntry[] | undefinedif (!sdkName) {@@ -43,6 +63,7 @@ export const SdkOutdatedRenderer = ({ issue }: { issue: HealthIssue }): JSX.Elem</div>)}</div>+ {reason && <div className="text-muted mb-2">{reason}</div>}{usage && usage.length > 0 && (<table className="w-full text-xs border-collapse"><thead>@@ -63,17 +84,7 @@ export const SdkOutdatedRenderer = ({ issue }: { issue: HealthIssue }): JSX.Elem<td className="py-1 pr-2"><TZLabel time={entry.max_timestamp} /></td>- <td className="py-1">- {entry.is_latest ? (- <LemonTag type="success" size="small">- Current- </LemonTag>- ) : (- <LemonTag type="warning" size="small">- Outdated- </LemonTag>- )}- </td>+ <td className="py-1">{statusTag(entry)}</td></tr>))}</tbody>diff --git a/posthog/api/sdk_doctor.py b/posthog/api/sdk_doctor.pyindex c6cf1728aea3..92b0d9e11ab9 100644--- a/posthog/api/sdk_doctor.py+++ b/posthog/api/sdk_doctor.py@@ -64,9 +64,8 @@ class SdkReleaseAssessmentSerializer(serializers.Serializer):help_text=("Per-version badge tooltip text matching the SDK Doctor UI exactly. Quote verbatim when ""reporting to users. Varies by state: 'Released X ago. Upgrade recommended.' for outdated "- "versions, 'You have the latest available. Click Releases above to check for any since.' "- "for current versions, or 'Released X ago. Upgrading is a good idea, but it's not urgent "- "yet.' for recent-but-behind versions."+ "versions, 'You have the latest available.' for current versions, or 'Released X ago. "+ "Upgrading is a good idea, but it's not urgent yet.' for recent-but-behind versions."),)sql_query = serializers.CharField(diff --git a/products/growth/backend/sdk_health.py b/products/growth/backend/sdk_health.pyindex 5e563396f4ec..44021abb417d 100644--- a/products/growth/backend/sdk_health.py+++ b/products/growth/backend/sdk_health.py@@ -1,12 +1,12 @@"""SDK Doctor health assessment.-Ports the outdatedness detection logic from frontend/src/scenes/onboarding/sdks/sdkDoctorLogic.tsx-so the backend can return a pre-digested health report for MCP / agent consumption.+The single source of truth for SDK outdatedness detection. Consumed by:+ - the `sdk_outdated` Temporal health check (alerts / HealthIssue rows),+ - the SDK Doctor report endpoint (posthog/api/sdk_doctor.py), which the SDK Doctor UI and the+ SDK Doctor MCP tool both read.-Keep constants and thresholds in sync with the frontend's DEVICE_CONTEXT_CONFIG,-SIGNIFICANT_TRAFFIC_THRESHOLD_*, GRACE_PERIOD_DAYS, SINGLE_VERSION_GRACE_PERIOD_DAYS,-and SDK_FRESHNESS_GRACE_PERIOD_DAYS.+The frontend renders these pre-computed values."""from dataclasses import dataclass, field@@ -31,7 +31,7 @@ from posthog.redis import get_clientfrom products.growth.backend.constants import SDK_TYPES, github_sdk_versions_key-# --- SDK classification ----------------------------------------------------+# --- SDK classification --------------------MOBILE_SDKS: frozenset[str] = frozenset({@@ -71,7 +71,7 @@ SDK_READABLE_NAME: dict[str, str] = {"posthog-elixir": "Elixir",}-# --- Thresholds (mirrored from sdkDoctorLogic.tsx) -------------------------+# --- Thresholds ----------------------------# Age-based outdatedness thresholds in weeks (desktop=4mo, mobile=6mo)AGE_THRESHOLD_DESKTOP_WEEKS = 16@@ -93,7 +93,7 @@ SIGNIFICANT_TRAFFIC_THRESHOLD_DEFAULT = 0.1MINOR_VERSIONS_BEHIND_THRESHOLD = 3MINOR_AGE_THRESHOLD_DAYS = 180-# --- Types ------------------------------------------------------------------+# --- Types ----------------------------------Severity = Literal["none", "warning", "danger"]OverallHealth = Literal["healthy", "needs_attention"]@@ -243,7 +243,7 @@ def diff_versions(a: SemanticVersion, b: SemanticVersion) -> Optional[SemanticVereturn None-# --- Age / device helpers --------------------------------------------------+# --- Age / device helpers ------------------def _calculate_version_age_days(release_date_iso: str, now: Optional[datetime] = None) -> int:@@ -330,26 +330,26 @@ def _released_ago(release_date_iso: Optional[str], now: Optional[datetime] = Nonreturn humanize.naturaltime(current - release)-# --- UI-parity string/URL builders -----------------------------------------+# --- UI-facing string/URL builders ---------#-# These mirror the copy and link construction in-# frontend/src/scenes/onboarding/sdks/SdkDoctorComponents.tsx and-# frontend/src/scenes/onboarding/sdks/SdkDoctorScene.tsx.-# Keep these in sync when UI copy or the Activity/SQL URL shape changes.+# The SDK Doctor UI (frontend/src/scenes/onboarding/sdks/) renders these strings/URLs verbatim+# from the report endpoint, so this is the single place the copy and Activity/SQL links are built.def _build_status_reason(is_outdated: bool, is_current_or_newer: bool, released_ago: Optional[str]) -> str:"""- Per-version tooltip text mirroring the three badge states in SdkDoctorComponents.tsx:149-196.+ Per-version status text for the three badge states (Outdated / Current / Recent).- Outdated (danger): "Released {ago}. Upgrade recommended." or "Upgrade recommended"- - Current (success): "You have the latest available. Click 'Releases ↗' above to check for any since."+ - Current (success): "You have the latest available."- Recent (warning): "Released {ago}. Upgrading is a good idea, but it's not urgent yet." (or without prefix)++ This value is persisted into HealthIssue payloads and forwarded to alert destinations / MCP."""if is_outdated:return f"Released {released_ago}. Upgrade recommended." if released_ago else "Upgrade recommended"if is_current_or_newer:- return "You have the latest available. Click 'Releases ↗' above to check for any since."+ return "You have the latest available."if released_ago:return f"Released {released_ago}. Upgrading is a good idea, but it's not urgent yet."return "Upgrading is a good idea, but it's not urgent yet"@@ -368,7 +368,7 @@ def _is_safe_for_interpolation(value: str) -> bool:def _build_sql_query(sdk_type: str, version: str) -> str:"""- Matches queryForSdkVersion() in SdkDoctorComponents.tsx.+ SQL drill-in for an SDK version, rendered as-is by the SDK Doctor UI and MCP tool.Returns an empty string when either `sdk_type` or `version` fails validation —the skill instructs agents to surface the unexpected empty value rather than retry@@ -390,7 +390,7 @@ def _build_sql_query(sdk_type: str, version: str) -> str:def _build_activity_page_url(project_id: Optional[int], sdk_type: str, version: str) -> str:"""- Matches activityPageUrlForSdkVersion() in SdkDoctorComponents.tsx.+ Activity > Explore drill-in URL for an SDK version, rendered as-is by the SDK Doctor UI and MCP tool.Returns a relative path (no host) including /project/<id>/ prefix so MCP agentscan combine it with the user's known PostHog host (e.g. us.posthog.com).@@ -493,7 +493,7 @@ def _build_banner(sdk_type: str, alert: OutdatedTrafficAlert) -> str:)-# --- Core assessment -------------------------------------------------------+# --- Core assessment -----------------------def assess_release(@@ -639,12 +639,20 @@ def _build_reason(latest_version: str,outdated_traffic_alerts: list[OutdatedTrafficAlert],) -> str:- """Short human-readable explanation for agents / UI."""+ """Short human-readable explanation for agents / UI / alerts.++ The single source of truth for "why is this flagged?": it always names the current+ in-use version and, when older versions still taking significant traffic are what drove+ the alert, the specific versions that triggered it. This keeps the string self-contained+ for every consumer (SDK Doctor UI, MCP agents, alert destinations) — including the case+ where the latest in-use version already matches latest but an older one is still served.+ """+ name = SDK_READABLE_NAME.get(sdk_type, sdk_type)current_version = _safe_version_display(current_release.version)latest = _safe_version_display(latest_version)if not current_release.needs_updating and not outdated_traffic_alerts:- return f"{sdk_type} is on {current_version} which matches or exceeds latest {latest}."+ return f"{name} is on {current_version} which matches or exceeds latest {latest}."pieces: list[str] = []if current_release.is_outdated:@@ -658,13 +666,18 @@ def _build_reason(pieces.append(f"In-use version {current_version} is old ({current_release.days_since_release} days since release).")+ else:+ # The latest in-use version is fine; the alert is driven entirely by older versions+ # still taking traffic. State it so the reason stands on its own rather than reading+ # as "outdated" while current and latest are the same.+ pieces.append(f"Latest in-use version {current_version} matches latest {latest}.")if outdated_traffic_alerts:versions = ", ".join(_safe_version_display(a.version) for a in outdated_traffic_alerts)threshold = outdated_traffic_alerts[0].threshold_percent- pieces.append(f"Outdated versions handling >= {threshold:.0f}% of traffic: {versions}.")+ pieces.append(f"Outdated versions still handling >= {threshold:.0f}% of traffic: {versions}.")- return " ".join(pieces) if pieces else f"{sdk_type} may need attention."+ return " ".join(pieces) if pieces else f"{name} may need attention."def assess_sdk(diff --git a/products/growth/backend/temporal/health_checks/sdk_outdated.py b/products/growth/backend/temporal/health_checks/sdk_outdated.pyindex 54a60b4d7899..b2388fe7cd74 100644--- a/products/growth/backend/temporal/health_checks/sdk_outdated.py+++ b/products/growth/backend/temporal/health_checks/sdk_outdated.py@@ -1,5 +1,6 @@import jsonfrom collections import defaultdict+from typing import Anyimport structlog@@ -18,7 +19,14 @@ 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+from products.growth.backend.sdk_health import SdkAssessment, _is_safe_for_interpolation, compute_sdk_health++# Issue severity follows the SDK Doctor assessment severity: a single outdated SDK is a warning,+# but when the bulk of a team's SDKs are outdated the assessment escalates to "danger".+_SEVERITY_BY_ASSESSMENT: dict[str, HealthIssue.Severity] = {+ "danger": HealthIssue.Severity.CRITICAL,+ "warning": HealthIssue.Severity.WARNING,+}logger = structlog.get_logger(__name__)@@ -90,15 +98,21 @@ class SdkOutdatedCheck(HealthCheck):@classmethoddef 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}"+ # `reason` is the assessment's single source of truth (compute_sdk_health → _build_reason).+ # It already names the current in-use version and the specific older versions driving the+ # alert, and routes every version through SDK Doctor's allowlist before interpolation — so+ # it's both complete and safe to forward to alert destinations (Slack, email, webhooks).+ summary = issue.payload.get("reason")+ if not summary:+ # Fallback for issues persisted before `reason` was added to the payload. `current_version`+ # originates from the $lib_version event property — attacker controllable via project token —+ # so gate it through the same allowlist before interpolating.+ #+ # Can be removed after 2026-06-08.+ latest = issue.payload.get("latest_version") or "the latest version"+ raw_current = issue.payload.get("current_version")+ 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,@@ -134,35 +148,75 @@ class SdkOutdatedCheck(HealthCheck):issues: defaultdict[int, list[HealthCheckResult]] = defaultdict(list)for team_id, sdk_data in team_sdk_data.items():- for lib_name, entries in sdk_data.items():- if lib_name not in github_data or not entries:- continue- sdk_github_data = github_data[lib_name]- latest_version = sdk_github_data["latestVersion"]- release_dates = sdk_github_data.get("releaseDates", {})-- current_version = entries[0].get("lib_version")-- if current_version and current_version != latest_version:- issues[team_id].append(- HealthCheckResult(- severity=HealthIssue.Severity.WARNING,- payload={- "sdk_name": lib_name,- "latest_version": latest_version,- "usage": [- {- "lib_version": entry["lib_version"],- "count": entry.get("count", 0),- "max_timestamp": entry["max_timestamp"],- "release_date": release_dates.get(entry["lib_version"]),- "is_latest": entry["lib_version"] == latest_version,- }- for entry in entries- ],- },- hash_keys=["sdk_name"],- )- )+ combined = _build_combined_data(sdk_data, github_data)+ if not combined:+ continue+ report = compute_sdk_health(combined, project_id=team_id)+ for assessment in report.sdks:+ if assessment.needs_updating:+ issues[team_id].append(_build_health_result(assessment))return issues+++def _build_combined_data(+ sdk_data: dict[str, list[SdkVersionEntry]],+ github_data: dict[str, dict],+) -> dict[str, dict[str, Any]]:+ """Shape per-team SDK usage into the structure compute_sdk_health expects."""+ combined: dict[str, dict[str, Any]] = {}+ for lib_name, entries in sdk_data.items():+ if lib_name not in github_data or not entries:+ continue+ sdk_github_data = github_data[lib_name]+ latest_version = sdk_github_data["latestVersion"]+ release_dates = sdk_github_data.get("releaseDates", {})+ combined[lib_name] = {+ "latest_version": latest_version,+ "usage": [+ {+ "lib_version": entry["lib_version"],+ "count": entry.get("count", 0),+ "max_timestamp": entry["max_timestamp"],+ "release_date": release_dates.get(entry["lib_version"]),+ "is_latest": entry["lib_version"] == latest_version,+ }+ for entry in entries+ ],+ }+ return combined+++def _build_health_result(assessment: SdkAssessment) -> HealthCheckResult:+ """Build a HealthCheckResult from a computed SDK assessment.++ The payload carries everything both the alert (render_alert) and the unified Health scene's+ per-version table (SdkOutdatedRenderer) need, so neither has to recompute or re-query.+ """+ severity = _SEVERITY_BY_ASSESSMENT.get(assessment.severity, HealthIssue.Severity.WARNING)+ primary = assessment.releases[0] if assessment.releases else None+ return HealthCheckResult(+ severity=severity,+ payload={+ "sdk_name": assessment.lib,+ "latest_version": assessment.latest_version,+ "current_version": primary.version if primary else None,+ "reason": assessment.reason,+ "banners": assessment.banners,+ "is_outdated": assessment.is_outdated,+ "is_old": assessment.is_old,+ "usage": [+ {+ "lib_version": release.version,+ "count": release.count,+ "max_timestamp": release.max_timestamp,+ "release_date": release.release_date,+ "is_latest": release.version == assessment.latest_version,+ "is_outdated": release.is_outdated,+ "status_reason": release.status_reason,+ }+ for release in assessment.releases+ ],+ },+ hash_keys=["sdk_name"],+ )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.pyindex e59d834d6c62..11d52afe0a02 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@@ -1,22 +1,17 @@-import json-from unittest.mock import MagicMock, patch-from django.test import SimpleTestCase, TestCase+from django.test import SimpleTestCasefrom parameterized import parameterizedfrom posthog.models.health_issue import HealthIssue-from products.growth.backend.constants import SDK_TYPES, TEAM_SDK_CACHE_EXPIRY+from products.growth.backend.constants import TEAM_SDK_CACHE_EXPIRYfrom products.growth.backend.temporal.health_checks.sdk_outdated import SdkOutdatedCheck, _cache_team_sdk_data--def _make_github_data(latest_version: str, release_dates: dict | None = None) -> dict:- return {- "latestVersion": latest_version,- "releaseDates": release_dates or {},- }+# A release date far enough in the past that any version behind latest is unambiguously outdated,+# independent of the wall clock when the test runs.+OLD_RELEASE = "2020-01-01T00:00:00Z"def _make_ch_row(@@ -29,156 +24,163 @@ def _make_ch_row(return (team_id, lib, lib_version, max_timestamp, event_count)-class TestSdkOutdatedCheck(TestCase):+def _patch_check(github: dict | None, rows: list[tuple]):+ """Patch the three external boundaries the check touches: GitHub version data, ClickHouse, Redis cache."""+ return (+ patch(+ "products.growth.backend.temporal.health_checks.sdk_outdated._load_github_sdk_data",+ return_value=github or {},+ ),+ patch(+ "products.growth.backend.temporal.health_checks.sdk_outdated.execute_clickhouse_health_team_query",+ return_value=rows,+ ),+ patch("products.growth.backend.temporal.health_checks.sdk_outdated._cache_team_sdk_data"),+ )+++class TestSdkOutdatedCheck(SimpleTestCase):def setUp(self):self.check = SdkOutdatedCheck()- @patch("products.growth.backend.temporal.health_checks.sdk_outdated._cache_team_sdk_data")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.execute_clickhouse_health_team_query")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.get_client")- def test_detects_outdated_sdk_with_enriched_payload(- self, mock_get_client: MagicMock, mock_ch_query: MagicMock, mock_cache: MagicMock- ):- mock_redis = MagicMock()- mock_get_client.return_value = mock_redis- mock_redis.mget.return_value = [- json.dumps(_make_github_data("1.200.0", {"1.198.0": "2026-03-01T00:00:00Z"})).encode()+ def _run(self, github: dict | None, rows: list[tuple], team_ids: list[int]) -> dict:+ p_github, p_ch, p_cache = _patch_check(github, rows)+ with p_github, p_ch, p_cache as mock_cache:+ self._mock_cache = mock_cache+ return self.check.detect(team_ids)++ def test_detects_outdated_sdk_with_enriched_payload(self):+ github = {+ "web": {"latestVersion": "2.0.0", "releaseDates": {}},+ "posthog-node": {"latestVersion": "3.0.0", "releaseDates": {}},+ "posthog-python": {"latestVersion": "5.0.0", "releaseDates": {"4.0.0": OLD_RELEASE}},+ }+ rows = [+ _make_ch_row(1, "web", "2.0.0"),+ _make_ch_row(1, "posthog-node", "3.0.0"),+ _make_ch_row(1, "posthog-python", "4.0.0", event_count=900),]- mock_ch_query.return_value = [- _make_ch_row(1, "web", "1.198.0", "2026-03-20 12:00:00", 5000),- _make_ch_row(1, "web", "1.195.0", "2026-03-18 08:00:00", 1000),- ]-- results = self.check.detect([1])+ results = self._run(github, rows, [1])+ # Two SDKs are current, one is a major version behind — only the outdated one raises an issue.assert 1 in resultsassert len(results[1]) == 1issue = results[1][0]+ # 1 of 3 outdated is below the escalation threshold (ceil(3/2)=2), so this stays a warning.assert issue.severity == HealthIssue.Severity.WARNING- assert issue.payload["sdk_name"] == "web"- assert issue.payload["latest_version"] == "1.200.0"- assert len(issue.payload["usage"]) == 2- assert issue.payload["usage"][0]["lib_version"] == "1.198.0"- assert issue.payload["usage"][0]["count"] == 5000+ assert issue.payload["sdk_name"] == "posthog-python"+ assert issue.payload["latest_version"] == "5.0.0"+ assert issue.payload["current_version"] == "4.0.0"+ assert issue.payload["is_outdated"] is True+ assert "reason" in issue.payload+ assert isinstance(issue.payload["banners"], list)+ assert len(issue.payload["usage"]) == 1+ assert issue.payload["usage"][0]["lib_version"] == "4.0.0"+ assert issue.payload["usage"][0]["is_outdated"] is Trueassert issue.payload["usage"][0]["is_latest"] is False- assert issue.payload["usage"][0]["release_date"] == "2026-03-01T00:00:00Z"- assert issue.payload["usage"][1]["lib_version"] == "1.195.0"- assert issue.payload["usage"][1]["release_date"] is None+ assert "status_reason" in issue.payload["usage"][0]assert issue.hash_keys == ["sdk_name"]- @patch("products.growth.backend.temporal.health_checks.sdk_outdated._cache_team_sdk_data")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.execute_clickhouse_health_team_query")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.get_client")- def test_skips_team_on_latest_version(- self, mock_get_client: MagicMock, mock_ch_query: MagicMock, mock_cache: MagicMock- ):- mock_redis = MagicMock()- mock_get_client.return_value = mock_redis- mock_redis.mget.return_value = [json.dumps(_make_github_data("1.200.0")).encode()]-- mock_ch_query.return_value = [- _make_ch_row(1, "web", "1.200.0", "2026-03-20 12:00:00", 5000),+ def test_alert_reason_explains_significant_outdated_traffic(self):+ # The most-used version already matches latest, but an older version still serves a+ # significant share of traffic. The SDK is flagged, and the alert must explain *that*+ # rather than the contradictory "on 1.142.0, latest is 1.142.0".+ github = {"web": {"latestVersion": "1.142.0", "releaseDates": {"1.130.0": OLD_RELEASE}}}+ rows = [+ _make_ch_row(1, "web", "1.142.0", event_count=700), # primary: latest, healthy+ _make_ch_row(1, "web", "1.130.0", event_count=300), # 30% traffic, behind, old]- results = self.check.detect([1])+ results = self._run(github, rows, [1])- assert results == {}+ issue = results[1][0]+ assert issue.payload["current_version"] == "1.142.0"+ assert issue.payload["latest_version"] == "1.142.0"+ assert issue.payload["is_outdated"] is True- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.execute_clickhouse_health_team_query")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.get_client")- def test_returns_empty_when_no_github_data(self, mock_get_client: MagicMock, mock_ch_query: MagicMock):- mock_redis = MagicMock()- mock_get_client.return_value = mock_redis- mock_redis.mget.return_value = [None] * len(SDK_TYPES)+ # The reason names both the healthy current version and the older version driving the alert.+ reason = issue.payload["reason"]+ assert "1.142.0" in reason+ assert "1.130.0" in reason- results = self.check.detect([1])+ # render_alert forwards the reason verbatim, so the alert is no longer self-contradictory.+ content = SdkOutdatedCheck.render_alert(issue)+ assert content.summary == reason+ assert "1.130.0" in content.summary- assert results == {}- mock_ch_query.assert_not_called()+ def test_escalates_to_critical_when_majority_outdated(self):+ github = {"posthog-python": {"latestVersion": "5.0.0", "releaseDates": {"4.0.0": OLD_RELEASE}}}+ rows = [_make_ch_row(1, "posthog-python", "4.0.0")]- @patch("products.growth.backend.temporal.health_checks.sdk_outdated._cache_team_sdk_data")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.execute_clickhouse_health_team_query")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.get_client")- def test_skips_team_with_no_clickhouse_data(- self, mock_get_client: MagicMock, mock_ch_query: MagicMock, mock_cache: MagicMock- ):- mock_redis = MagicMock()- mock_get_client.return_value = mock_redis- mock_redis.mget.return_value = [json.dumps(_make_github_data("1.200.0")).encode()]+ results = self._run(github, rows, [1])- mock_ch_query.return_value = []+ # The team's only SDK is outdated (1 of 1 >= ceil(1/2)), so severity escalates to critical.+ assert results[1][0].severity == HealthIssue.Severity.CRITICAL- results = self.check.detect([1])+ def test_skips_team_on_latest_version(self):+ github = {"web": {"latestVersion": "1.200.0", "releaseDates": {}}}+ rows = [_make_ch_row(1, "web", "1.200.0")]- assert results == {}+ assert self._run(github, rows, [1]) == {}- @patch("products.growth.backend.temporal.health_checks.sdk_outdated._cache_team_sdk_data")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.execute_clickhouse_health_team_query")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.get_client")- def test_multiple_teams_in_batch(self, mock_get_client: MagicMock, mock_ch_query: MagicMock, mock_cache: MagicMock):- mock_redis = MagicMock()- mock_get_client.return_value = mock_redis- mock_redis.mget.return_value = [json.dumps(_make_github_data("2.0.0")).encode()]+ def test_patch_behind_is_not_flagged(self):+ # Proves the heuristics run: a crude current!=latest rule would flag this, but a patch+ # difference is never outdated.+ github = {"web": {"latestVersion": "2.0.5", "releaseDates": {}}}+ rows = [_make_ch_row(1, "web", "2.0.3")]++ assert self._run(github, rows, [1]) == {}- mock_ch_query.return_value = [- _make_ch_row(1, "web", "1.5.0", "2026-03-20 12:00:00", 3000),- _make_ch_row(2, "web", "2.0.0", "2026-03-20 12:00:00", 1000),- _make_ch_row(3, "web", "1.0.0", "2026-03-19 08:00:00", 500),+ def test_returns_empty_when_no_github_data(self):+ p_github, p_ch, p_cache = _patch_check({}, [])+ with p_github, p_ch as mock_ch, p_cache:+ results = self.check.detect([1])+ assert results == {}+ mock_ch.assert_not_called()++ def test_skips_team_with_no_clickhouse_data(self):+ github = {"web": {"latestVersion": "2.0.0", "releaseDates": {}}}+ assert self._run(github, [], [1]) == {}++ def test_multiple_teams_in_batch(self):+ github = {"web": {"latestVersion": "2.0.0", "releaseDates": {}}}+ rows = [+ _make_ch_row(1, "web", "1.0.0"), # major behind -> outdated+ _make_ch_row(2, "web", "2.0.0"), # latest -> healthy+ _make_ch_row(3, "web", "1.0.0"), # major behind -> outdated]- results = self.check.detect([1, 2, 3])+ results = self._run(github, rows, [1, 2, 3])- # Team 1 and 3 are outdated, team 2 is on latestassert 1 in resultsassert 2 not in resultsassert 3 in results+ # One result per outdated SDK assessment — guards against regressing to one-per-release.assert len(results[1]) == 1assert len(results[3]) == 1assert results[1][0].payload["sdk_name"] == "web"assert results[3][0].payload["sdk_name"] == "web"- @patch("products.growth.backend.temporal.health_checks.sdk_outdated._cache_team_sdk_data")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.execute_clickhouse_health_team_query")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.get_client")- def test_caches_team_data_in_redis(- self, mock_get_client: MagicMock, mock_ch_query: MagicMock, mock_cache: MagicMock- ):- mock_redis = MagicMock()- mock_get_client.return_value = mock_redis- mock_redis.mget.return_value = [json.dumps(_make_github_data("2.0.0")).encode()]+ def test_ignores_unknown_sdk_types(self):+ github = {"web": {"latestVersion": "2.0.0", "releaseDates": {}}}+ rows = [_make_ch_row(1, "unknown-sdk", "1.0.0", event_count=100)]- mock_ch_query.return_value = [- _make_ch_row(1, "web", "1.5.0", "2026-03-20 12:00:00", 3000),- ]+ assert self._run(github, rows, [1]) == {}++ def test_caches_team_data_in_redis(self):+ github = {"web": {"latestVersion": "2.0.0", "releaseDates": {}}}+ rows = [_make_ch_row(1, "web", "1.5.0")]- self.check.detect([1])+ self._run(github, rows, [1])- mock_cache.assert_called_once()- cached_data = mock_cache.call_args[0][0]+ self._mock_cache.assert_called_once()+ cached_data = self._mock_cache.call_args[0][0]assert 1 in cached_dataassert "web" in cached_data[1]assert cached_data[1]["web"][0]["lib_version"] == "1.5.0"- @patch("products.growth.backend.temporal.health_checks.sdk_outdated._cache_team_sdk_data")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.execute_clickhouse_health_team_query")- @patch("products.growth.backend.temporal.health_checks.sdk_outdated.get_client")- def test_ignores_unknown_sdk_types(- self, mock_get_client: MagicMock, mock_ch_query: MagicMock, mock_cache: MagicMock- ):- mock_redis = MagicMock()- mock_get_client.return_value = mock_redis- mock_redis.mget.return_value = [json.dumps(_make_github_data("2.0.0")).encode()]-- mock_ch_query.return_value = [- _make_ch_row(1, "unknown-sdk", "1.0.0", "2026-03-20 12:00:00", 100),- ]-- results = self.check.detect([1])-- assert results == {}-@patch("products.growth.backend.temporal.health_checks.sdk_outdated.get_client")def test_cache_team_sdk_data_uses_team_sdk_cache_expiry(self, mock_get_client: MagicMock):mock_redis = MagicMock()@@ -194,6 +196,26 @@ class TestSdkOutdatedCheck(TestCase):class TestSdkOutdatedRenderAlert(SimpleTestCase):+ def test_render_alert_prefers_reason_when_present(self) -> None:+ reason = (+ "Latest in-use version 1.200.0 matches latest 1.200.0. "+ "Outdated versions still handling >= 20% of traffic: 1.150.0."+ )+ issue = HealthIssue(+ team_id=1,+ kind="sdk_outdated",+ severity=HealthIssue.Severity.WARNING,+ payload={+ "sdk_name": "web",+ "latest_version": "1.200.0",+ "current_version": "1.200.0",+ "reason": reason,+ },+ unique_hash="h",+ )+ content = SdkOutdatedCheck.render_alert(issue)+ assert content.summary == reason+@parameterized.expand([("safe_version", "1.198.0", "web is on 1.198.0, latest is 1.200.0"),@@ -203,7 +225,9 @@ class TestSdkOutdatedRenderAlert(SimpleTestCase):("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:+ def test_render_alert_rejects_unsafe_current_version(+ self, _name: str, raw_version: str, expected_summary: str+ ) -> None:issue = HealthIssue(team_id=1,kind="sdk_outdated",@@ -211,7 +235,7 @@ class TestSdkOutdatedRenderAlert(SimpleTestCase):payload={"sdk_name": "web","latest_version": "1.200.0",- "usage": [{"lib_version": raw_version, "count": 100, "max_timestamp": "2026-03-20"}],+ "current_version": raw_version,},unique_hash="h",)diff --git a/products/growth/backend/tests/test_sdk_health.py b/products/growth/backend/tests/test_sdk_health.pyindex 2f5c6ea05daf..a6a832999e11 100644--- a/products/growth/backend/tests/test_sdk_health.py+++ b/products/growth/backend/tests/test_sdk_health.py@@ -462,7 +462,7 @@ class TestUiParityStrings(SimpleTestCase):False,True,"a day ago",- "You have the latest available. Click 'Releases ↗' above to check for any since.",+ "You have the latest available.",),("recent_with_age",diff --git a/products/growth/skills/diagnosing-sdk-health/SKILL.md b/products/growth/skills/diagnosing-sdk-health/SKILL.mdindex 41a29d330c2b..d0a4fb78f513 100644--- a/products/growth/skills/diagnosing-sdk-health/SKILL.md+++ b/products/growth/skills/diagnosing-sdk-health/SKILL.md@@ -79,10 +79,8 @@ Group by severity (`danger` first, then `warning`, then `none`). Skip SDKs withEach SDK's `releases` array has per-version rows. Each row includes UI-matching copy andready-to-use links:-- `status_reason` — badge tooltip text that **closely** matches the UI (e.g. `"Released-5 months ago. Upgrade recommended."`, `"You have the latest available. Click 'Releases ↗'-above to check for any since."`, or `"Released 2 months ago. Upgrading is a good idea,-but it's not urgent yet."`). Quote directly. **Caveat**: the relative-age segment+- `status_reason` — badge tooltip text that **closely** matches the UI. Quote directly.+ **Caveat**: the relative-age segment("5 months ago" etc.) is computed with Python's `humanize.naturaltime` on the backendand JavaScript's `dayjs().fromNow()` in the browser, and the two libraries havedifferent thresholds at some boundaries (e.g. humanize says `"30 days ago"` where dayjsdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4b43dc493b3f..f5aa744f5b9f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36731,7 +36731,7 @@ export namespace Schemas {needs_updating: boolean;/** True when this version equals or exceeds the latest known published version. */is_current_or_newer: boolean;- /** Per-version badge tooltip text matching the SDK Doctor UI exactly. Quote verbatim when reporting to users. Varies by state: 'Released X ago. Upgrade recommended.' for outdated versions, 'You have the latest available. Click Releases above to check for any since.' for current versions, or 'Released X ago. Upgrading is a good idea, but it's not urgent yet.' for recent-but-behind versions. */+ /** Per-version badge tooltip text matching the SDK Doctor UI exactly. Quote verbatim when reporting to users. Varies by state: 'Released X ago. Upgrade recommended.' for outdated versions, 'You have the latest available.' for current versions, or 'Released X ago. Upgrading is a good idea, but it's not urgent yet.' for recent-but-behind versions. */status_reason: string;/** SQL SELECT statement for drilling into events for this SDK version over the last 7 days. Suitable to pass to the execute-sql tool or to display as a copy-paste snippet. */sql_query: string;