: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
fix(sdk-health): fix version comparison and stale data on Health page (#78634)
Steven Shults4c4e1037ffa4
diff --git a/frontend/src/scenes/onboarding/shared/sdkHealth/SdkHealthComponents.tsx b/frontend/src/scenes/onboarding/shared/sdkHealth/SdkHealthComponents.tsxindex 51c9d94347e9..b76c2384718b 100644--- a/frontend/src/scenes/onboarding/shared/sdkHealth/SdkHealthComponents.tsx+++ b/frontend/src/scenes/onboarding/shared/sdkHealth/SdkHealthComponents.tsx@@ -143,7 +143,7 @@ export function SdkSection({ sdkType }: { sdkType: SdkType }): JSX.Element {<Tooltiptitle={<>- Version number cached once a day.+ Version number refreshed hourly.<br />Click 'Releases ↗' to check for any since.</>diff --git a/frontend/src/scenes/onboarding/shared/sdkHealth/SdkHealthScene.tsx b/frontend/src/scenes/onboarding/shared/sdkHealth/SdkHealthScene.tsxindex 752aea3f5218..dd2768af8afc 100644--- a/frontend/src/scenes/onboarding/shared/sdkHealth/SdkHealthScene.tsx+++ b/frontend/src/scenes/onboarding/shared/sdkHealth/SdkHealthScene.tsx@@ -114,8 +114,8 @@ export function SdkHealthScene(): JSX.Element {<section className="mb-2"><h3>SDK health is good</h3><LemonBanner type="success" hideIcon={false}>- <p className="font-semibold">All caught up! Your SDKs are up to date.</p>- <p className="text-sm mt-1">You've got the latest. Nice work keeping everything current.</p>+ <p className="font-semibold">No SDK updates needed right now.</p>+ <p className="text-sm mt-1">Your SDKs are on the latest version or close behind it.</p></LemonBanner></section>) : (diff --git a/posthog/api/sdk_health.py b/posthog/api/sdk_health.pyindex bab9923b454e..75d124cd553f 100644--- a/posthog/api/sdk_health.py+++ b/posthog/api/sdk_health.py@@ -25,12 +25,8 @@ from products.growth.backend.constants import (from products.growth.backend.sdk_health import SdkHealthReport, compute_sdk_health# NOTE: products.growth.backend.team_sdk_versions is imported lazily inside get_team_data-# below. It transitively imports from posthog/dags which calls django.setup() — that-# causes a RuntimeError("populate() isn't reentrant") if we let it happen at module-# import time from posthog/api/__init__.py. SDK_TYPES used to trigger the same chain-# when it lived in products.growth.dags.github_sdk_versions; it now lives in-# products.growth.backend.constants (which has no Django side effects) and can be a-# top-level import.+# below. Importing it pulls posthog.hogql.query, the direct-SQL adapters, and+# ee.clickhouse.materialized_columns, none of which the rest of posthog/api needs.logger = structlog.get_logger(__name__)@@ -180,7 +176,8 @@ class SdkHealthViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):required=False,description=("When true, bypasses the Redis cache and re-queries ClickHouse for SDK usage. "- "Use sparingly — data is refreshed every 12 hours by a background job."+ "A background job refreshes this data once a day, so the cached answer is "+ "usually current. Use sparingly."),),],diff --git a/products/growth/backend/sdk_health.py b/products/growth/backend/sdk_health.pyindex d15fb3c7f6f3..50b839e7f2c0 100644--- a/products/growth/backend/sdk_health.py+++ b/products/growth/backend/sdk_health.py@@ -21,9 +21,12 @@ from typing import Any, Literal, NamedTuple, Optionalfrom urllib.parse import quoteimport humanize+import structlogfrom products.growth.backend.constants import LEGACY_JAVA_SDK, SdkVersionEntry+logger = structlog.get_logger(__name__)+# --- SDK classification --------------------MOBILE_SDKS: frozenset[str] = frozenset(@@ -596,7 +599,15 @@ def assess_release(is_outdated = False- if is_single_version and diff is not None and diff.kind != "patch" and days_since_release is not None:+ if (+ is_single_version+ and diff is not None+ and diff.diff > 0+ and diff.kind != "patch"+ and days_since_release is not None+ ):+ # diff.diff > 0 matters: a stale cached "latest" can be behind the version actually in+ # use, and a version newer than (or equal to) latest must never be flagged as outdatedis_outdated = days_since_release > SINGLE_VERSION_GRACE_PERIOD_DAYSelif is_recent_release:is_outdated = False@@ -659,7 +670,11 @@ def _build_reason(latest = _safe_version_display(latest_version)if not current_release.needs_updating and not outdated_traffic_alerts:- return f"{name} is on {current_version} which matches or exceeds latest {latest}."+ if current_release.is_current_or_newer:+ return f"{name} is on {current_version} which matches or exceeds latest {latest}."+ # Behind latest but within the grace rules (e.g. patch-level or a fresh release):+ # claiming it "matches latest" here would be wrong+ return f"{name} is on {current_version}, behind latest {latest}. Upgrading is not urgent yet."pieces: list[str] = []if current_release.is_outdated:@@ -673,11 +688,16 @@ def _build_reason(pieces.append(f"In-use version {current_version} is old ({current_release.days_since_release} days since release).")- else:+ elif current_release.is_current_or_newer:# 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}.")+ # as "outdated" while current and latest are the same. "or exceeds" covers the version+ # being ahead of a stale cached latest, where a bare "matches" would contradict itself.+ pieces.append(f"Latest in-use version {current_version} matches or exceeds latest {latest}.")+ else:+ # Behind latest but inside the patch/grace rules, so only the traffic alert drove this.+ # The alert sentence below carries the verdict, so don't editorialize about urgency here.+ pieces.append(f"Latest in-use version {current_version} is behind latest {latest}.")if outdated_traffic_alerts:versions = ", ".join(_safe_version_display(a.version) for a in outdated_traffic_alerts)@@ -744,6 +764,14 @@ def assess_sdk(try:latest = parse_version(latest_version_str)except ValueError:+ # A "latest" that doesn't parse means the GitHub fetcher's tag matching is broken for+ # this SDK. The SDK still has to be dropped (there is nothing to compare against), but+ # dropping it silently hides the pipeline breakage from everyone, so leave a trail.+ logger.warning(+ "sdk_health_unparseable_latest_version",+ sdk_type=sdk_type,+ latest_version=latest_version_str,+ )return Noneis_single_version = len(usage) == 1diff --git a/products/growth/backend/team_sdk_versions.py b/products/growth/backend/team_sdk_versions.pyindex 73704582bdf8..b99baf9fbf20 100644--- a/products/growth/backend/team_sdk_versions.py+++ b/products/growth/backend/team_sdk_versions.py@@ -15,9 +15,13 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team-from products.growth.backend.constants import TEAM_SDK_CACHE_EXPIRY, SdkVersionEntry, team_sdk_versions_v2_key+from products.growth.backend.constants import (+ SDK_TYPES,+ TEAM_SDK_CACHE_EXPIRY,+ SdkVersionEntry,+ team_sdk_versions_v2_key,+)from products.growth.backend.sdk_health import sort_sdk_version_entries-from products.growth.dags.github_sdk_versions import SDK_TYPESdefault_logger: BoundLogger = structlog.get_logger(__name__)diff --git a/products/growth/backend/tests/test_sdk_health.py b/products/growth/backend/tests/test_sdk_health.pyindex 59c5bede59b6..c29f94f50800 100644--- a/products/growth/backend/tests/test_sdk_health.py+++ b/products/growth/backend/tests/test_sdk_health.py@@ -247,7 +247,9 @@ class TestAssessReleaseCurrentOrNewer(SimpleTestCase):assert result.is_current_or_newer is Truedef test_ahead_of_cached_latest_not_outdated(self):- entry = _entry("1.6.0", 100)+ # The release date is past the single-version grace period on purpose: a version newer+ # than a stale cached "latest" must not fall into the single-version outdatedness rule+ entry = _entry("1.6.0", 100, days_ago=SINGLE_VERSION_GRACE_PERIOD_DAYS + 10)result = assess_release("posthog-node",entry,@@ -259,6 +261,59 @@ class TestAssessReleaseCurrentOrNewer(SimpleTestCase):assert result.is_current_or_newer is True+class TestAssessSdkReason(SimpleTestCase):+ # `reason` is the whole alert body forwarded to Slack/email/MCP, so these rows guard+ # against it asserting a match while the in-use version is behind latest, or ahead of a+ # stale cached latest. Patch-level and grace-period differences are never flagged, which+ # is what makes the false all-clear reachable in the first place.+ @parameterized.expand(+ [+ (+ "matches_latest",+ "posthog-node",+ "1.5.0",+ [_entry("1.5.0", 100)],+ "Node.js is on 1.5.0 which matches or exceeds latest 1.5.0.",+ ),+ (+ "behind_latest",+ "posthog-node",+ "1.5.9",+ [_entry("1.5.0", 100, days_ago=100)],+ "Node.js is on 1.5.0, behind latest 1.5.9. Upgrading is not urgent yet.",+ ),+ (+ "traffic_alert_while_matching_latest",+ "web",+ "1.298.1",+ [_entry("1.298.1", 60, days_ago=60), _entry("1.200.0", 40, days_ago=300)],+ "Latest in-use version 1.298.1 matches or exceeds latest 1.298.1. "+ "Outdated versions still handling >= 20% of traffic: 1.200.0.",+ ),+ (+ "traffic_alert_while_ahead_of_stale_latest",+ "web",+ "1.298.1",+ [_entry("1.299.0", 60, days_ago=60), _entry("1.200.0", 40, days_ago=300)],+ "Latest in-use version 1.299.0 matches or exceeds latest 1.298.1. "+ "Outdated versions still handling >= 20% of traffic: 1.200.0.",+ ),+ (+ "traffic_alert_while_behind_latest",+ "web",+ "1.298.1",+ [_entry("1.298.0", 60, days_ago=60), _entry("1.200.0", 40, days_ago=300)],+ "Latest in-use version 1.298.0 is behind latest 1.298.1. "+ "Outdated versions still handling >= 20% of traffic: 1.200.0.",+ ),+ ]+ )+ def test_reason(self, _name: str, sdk_type: str, latest_version: str, usage: list[UsageEntry], expected: str):+ sdk = assess_sdk(sdk_type, latest_version, usage, now=NOW)+ assert sdk is not None+ assert sdk.reason == expected++class TestAssessReleaseIsOld(SimpleTestCase):def test_desktop_old_flagged(self):# 17 weeks > 16-week desktop threshold, with 1 minor behinddiff --git a/products/growth/dags/github_sdk_versions.py b/products/growth/dags/github_sdk_versions.pyindex 9404ff77ec21..5c92b9dbaf45 100644--- a/products/growth/dags/github_sdk_versions.py+++ b/products/growth/dags/github_sdk_versions.py@@ -1,5 +1,6 @@import reimport json+import timefrom collections.abc import Callablefrom typing import Any, Optional, cast@@ -14,14 +15,13 @@ from posthog.egress.github.transport import github_requestfrom posthog.exceptions_capture import capture_exceptionfrom products.growth.backend.constants import SDK_CACHE_EXPIRY, SDK_TYPES, SdkTypes, github_sdk_versions_key+from products.growth.backend.sdk_health import SemanticVersion, try_parse_version# Re-exported for backward compatibility with callers that still import from here.__all__ = ["SDK_CACHE_EXPIRY", "SDK_TYPES", "SdkTypes", "github_sdk_versions_key"]logger = structlog.get_logger(__name__)-MAX_REQUEST_RETRIES = 3-INITIAL_RETRIES_BACKOFF = 1 # in secondsUNPREFIXED_SEMVER_TAG = re.compile(r"\d+\.\d+(?:\.\d+)*$")@@ -58,6 +58,12 @@ def prefixed_or_unprefixed_semver_tags(*prefixes: str) -> list[str | re.Pattern]return [*prefixes, UNPREFIXED_SEMVER_TAG]+# nosemgrep: tuple-return-prefer-dataclass -- opaque sort key, only ever compared whole+def _semver_order_key(version: SemanticVersion) -> tuple[int, int, int, bool]:+ # Stable releases sort above prereleases with the same core version+ return (version.major, version.minor or 0, version.patch or 0, version.extra is None)++def fetch_sdk_data_from_releases(repo: str, tag_prefixes: list[str | re.Pattern] | None = None) -> dict[str, Any]:"""Helper function to fetch SDK data from GitHub releases API."""@@ -70,6 +76,7 @@ def fetch_sdk_data_from_releases(repo: str, tag_prefixes: list[str | re.Pattern]return {}latest_version = None+ latest_parsed: Optional[SemanticVersion] = Nonerelease_dates = {}for release in releases:@@ -94,9 +101,16 @@ def fetch_sdk_data_from_releases(repo: str, tag_prefixes: list[str | re.Pattern]if not version:continue- # Latest version is always the first one we find because we go in order- if latest_version is None:+ # GitHub orders /releases by creation date, not by version, so the first match is+ # wrong whenever a hotfix ships on an older release line (or a release is backfilled).+ # Pick the highest version that parses instead; a non-parseable "latest" would make+ # the assessor drop the SDK from every report.+ parsed = try_parse_version(version)+ if parsed is not None and (+ latest_parsed is None or _semver_order_key(parsed) > _semver_order_key(latest_parsed)+ ):latest_version = version+ latest_parsed = parsed# Unintuitively we need to use `created_at` rather than `published_at`# because the former represents when the tag was created while the latter is when the release was created@@ -110,13 +124,21 @@ def fetch_sdk_data_from_releases(repo: str, tag_prefixes: list[str | re.Pattern]return {"latestVersion": latest_version, "releaseDates": release_dates}-# This is used to avoid hitting the GitHub API too often-# for requests coming from the same pod, this doesn't happen often but it's good to have it anyway-local_releases_cache: dict[str, list[Any]] = {}+# Dedupes fetches within a run for repos shared by several fetchers (PostHog/posthog-js serves+# web, node, and react-native). Entries must expire well before the next hourly run: this module+# lives in a long-running process, so an eternal cache would re-write Redis with the same+# snapshot every run and freeze "latest version" until a redeploy.+LOCAL_RELEASES_CACHE_TTL_SECONDS = 30 * 60+local_releases_cache: dict[str, tuple[float, list[Any]]] = {}def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:- """Fetch releases from a GitHub repository"""+ """Fetch releases from a GitHub repository.++ Returns [] when any page fails, so callers skip the Redis write and the last known-good+ data keeps serving. A partial page set must never be treated as the full release list:+ it can miss versions entirely and gets a stale "latest" cached for days.+ """global local_releases_cache# We don't wanna have to fight against the local cache when running tests@@ -125,9 +147,11 @@ def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:if settings.TEST:skip_cache = True- if repo in local_releases_cache and not skip_cache:- logger.info(f"[SDK Health] Returning cached releases for {repo}")- return local_releases_cache[repo]+ if not skip_cache:+ cached = local_releases_cache.get(repo)+ if cached is not None and time.monotonic() - cached[0] < LOCAL_RELEASES_CACHE_TTL_SECONDS:+ logger.info(f"[SDK Health] Returning cached releases for {repo}")+ return cached[1]releases = []page = 1@@ -142,16 +166,16 @@ def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:if not response.ok:logger.error(f"[SDK Health] Failed to fetch releases for {repo}", status_code=response.status_code)- break+ return []releases_json = response.json()if releases_json is None:logger.error(f"[SDK Health] Expected list of releases, got empty response", repo=repo)- break+ return []if not isinstance(releases_json, list):logger.error(f"[SDK Health] Expected list of releases, got {type(releases_json)}", repo=repo)- break+ return []if len(releases_json) == 0:break@@ -161,11 +185,11 @@ def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:except Exception as e:logger.exception(f"[SDK Health] Failed to fetch releases for {repo}", repo=repo)capture_exception(e, additional_properties={"repo": repo, "page": page, "url": url})- break+ return []- # Cache for later use and return- local_releases_cache[repo] = releases- return local_releases_cache[repo]+ # Only complete fetches are cached; a failed fetch must be retried, not served for 30 minutes+ local_releases_cache[repo] = (time.monotonic(), releases)+ return releasesdef fetch_web_sdk_data() -> dict[str, Any]:@@ -178,7 +202,12 @@ def fetch_web_sdk_data() -> dict[str, Any]:def fetch_python_sdk_data() -> dict[str, Any]:"""Fetch Python SDK data from GitHub releases API"""- return fetch_sdk_data_from_releases("PostHog/posthog-python", tag_prefixes=prefixed_or_unprefixed_semver_tags("v"))++ # The repo now tags monorepo-style (`posthog-v7.38.0`), with sibling packages like+ # `openfeature-provider-posthog-v*` that must not match; `v`-prefixed and bare tags are historical+ return fetch_sdk_data_from_releases(+ "PostHog/posthog-python", tag_prefixes=prefixed_or_unprefixed_semver_tags("posthog-v", "v")+ )def fetch_node_sdk_data() -> dict[str, Any]:@@ -193,12 +222,13 @@ def fetch_node_sdk_data() -> dict[str, Any]:if not posthog_js:return {}- # The latest date is always from `posthog-js` since this is the only active repo+ # The latest date is always from `posthog-js` since this is the only active repo,+ # so its dates win if a version somehow exists in both reposreturn {"latestVersion": posthog_js["latestVersion"],"releaseDates": {- **posthog_js["releaseDates"],**posthog_js_lite.get("releaseDates", {}),+ **posthog_js["releaseDates"],},}@@ -215,12 +245,13 @@ def fetch_react_native_sdk_data() -> dict[str, Any]:if not posthog_js:return {}- # The latest date is always from `posthog-js` since this is the only active repo+ # The latest date is always from `posthog-js` since this is the only active repo,+ # so its dates win if a version somehow exists in both reposreturn {"latestVersion": posthog_js["latestVersion"],"releaseDates": {- **posthog_js["releaseDates"],**posthog_js_lite.get("releaseDates", {}),+ **posthog_js["releaseDates"],},}@@ -238,7 +269,9 @@ def fetch_ios_sdk_data() -> dict[str, Any]:def fetch_kmp_sdk_data() -> dict[str, Any]:"""Fetch Kotlin Multiplatform SDK data from GitHub releases API"""- return fetch_sdk_data_from_releases("PostHog/posthog-kmp", tag_prefixes=["v"])++ # Early releases were tagged `v0.1.0`; the repo has since moved to bare tags like `0.2.2`+ return fetch_sdk_data_from_releases("PostHog/posthog-kmp", tag_prefixes=prefixed_or_unprefixed_semver_tags("v"))def fetch_android_sdk_data() -> dict[str, Any]:@@ -264,23 +297,34 @@ def fetch_go_sdk_data() -> dict[str, Any]:def fetch_php_sdk_data() -> dict[str, Any]:- """Fetch PHP SDK data from History.md with release dates"""+ """Fetch PHP SDK data from GitHub releases API"""return fetch_sdk_data_from_releases("PostHog/posthog-php")def fetch_ruby_sdk_data() -> dict[str, Any]:- """Fetch Ruby SDK data from CHANGELOG.md with release dates"""- return fetch_sdk_data_from_releases("PostHog/posthog-ruby")+ """Fetch Ruby SDK data from GitHub releases API"""++ # The repo now tags monorepo-style, releasing both `posthog-ruby-v*` and `posthog-rails-v*`;+ # only the former is this SDK. `v`-prefixed and bare tags are historical+ return fetch_sdk_data_from_releases(+ "PostHog/posthog-ruby", tag_prefixes=prefixed_or_unprefixed_semver_tags("posthog-ruby-v", "v")+ )def fetch_elixir_sdk_data() -> dict[str, Any]:- """Fetch Elixir SDK data from CHANGELOG.md with release dates"""+ """Fetch Elixir SDK data from GitHub releases API"""return fetch_sdk_data_from_releases("PostHog/posthog-elixir", tag_prefixes=prefixed_or_unprefixed_semver_tags("v"))def fetch_dotnet_sdk_data() -> dict[str, Any]:"""Fetch .NET SDK data from GitHub releases API"""- return fetch_sdk_data_from_releases("PostHog/posthog-dotnet", tag_prefixes=prefixed_or_unprefixed_semver_tags("v"))++ # The repo now tags monorepo-style (`PostHog-v2.13.0`), with sibling packages+ # `PostHog.AspNetCore-v*` and `PostHog.AI-v*` that must not match; `v`-prefixed and+ # bare tags are historical+ return fetch_sdk_data_from_releases(+ "PostHog/posthog-dotnet", tag_prefixes=prefixed_or_unprefixed_semver_tags("PostHog-v", "v")+ )# ---- Dagster defsdiff --git a/products/growth/dags/tests/test_github_sdk_versions.py b/products/growth/dags/tests/test_github_sdk_versions.pyindex 8da12ab4beab..d7bbcdb92472 100644--- a/products/growth/dags/tests/test_github_sdk_versions.py+++ b/products/growth/dags/tests/test_github_sdk_versions.py@@ -4,7 +4,10 @@ from pathlib import Pathimport pytestfrom unittest.mock import MagicMock, patch+from django.test import override_settings+from products.growth.dags.github_sdk_versions import (+ LOCAL_RELEASES_CACHE_TTL_SECONDS,fetch_android_sdk_data,fetch_dotnet_sdk_data,fetch_elixir_sdk_data,@@ -18,8 +21,10 @@ from products.growth.dags.github_sdk_versions import (fetch_php_sdk_data,fetch_python_sdk_data,fetch_react_native_sdk_data,+ fetch_releases_from_repo,fetch_ruby_sdk_data,fetch_web_sdk_data,+ local_releases_cache,)# NOTE: Fixtures are defined as they were in October 10, 2025@@ -370,6 +375,191 @@ class TestFetchDotnetSdkData(TestFetchSdkDataBase):assert mock_get.call_count == 2 # Assert that it attempted to paginate+def _release(tag_name: str, created_at: str) -> dict:+ return {"tag_name": tag_name, "created_at": created_at, "draft": False, "prerelease": False}+++class TestMonorepoPackageTagMatching(TestFetchSdkDataBase):+ @pytest.mark.parametrize(+ "fetch_fn,releases,expected_latest,expected_date_keys",+ [+ # posthog-python moved to `posthog-v*` tags; sibling package tags must not match+ (+ fetch_python_sdk_data,+ [+ _release("openfeature-provider-posthog-v0.1.39", "2026-08-01T00:00:00Z"),+ _release("posthog-v7.38.0", "2026-07-30T00:00:00Z"),+ _release("v7.12.0", "2025-08-30T00:00:00Z"),+ _release("7.5.0", "2025-05-30T00:00:00Z"),+ ],+ "7.38.0",+ {"7.38.0", "7.12.0", "7.5.0"},+ ),+ # posthog-ruby moved to `posthog-ruby-v*` tags; `posthog-rails-v*` is a different package+ (+ fetch_ruby_sdk_data,+ [+ _release("posthog-rails-v3.18.0", "2026-08-01T00:00:00Z"),+ _release("posthog-ruby-v3.23.0", "2026-07-30T00:00:00Z"),+ _release("v3.6.1", "2025-08-30T00:00:00Z"),+ _release("3.3.3", "2025-05-30T00:00:00Z"),+ ],+ "3.23.0",+ {"3.23.0", "3.6.1", "3.3.3"},+ ),+ # posthog-dotnet moved to `PostHog-v*` tags; AspNetCore/AI package tags must not match+ (+ fetch_dotnet_sdk_data,+ [+ _release("PostHog.AspNetCore-v2.8.2", "2026-08-01T00:00:00Z"),+ _release("PostHog.AI-v0.1.4", "2026-07-31T00:00:00Z"),+ _release("PostHog-v2.13.0", "2026-07-30T00:00:00Z"),+ _release("2.6.0", "2025-09-30T00:00:00Z"),+ _release("v2.4.1", "2025-08-30T00:00:00Z"),+ ],+ "2.13.0",+ {"2.13.0", "2.6.0", "2.4.1"},+ ),+ # posthog-kmp dropped its `v` prefix after 0.1.x+ (+ fetch_kmp_sdk_data,+ [+ _release("0.2.2", "2026-07-30T00:00:00Z"),+ _release("v0.1.0", "2026-05-30T00:00:00Z"),+ ],+ "0.2.2",+ {"0.2.2", "0.1.0"},+ ),+ ],+ )+ def test_current_and_historical_tag_schemes(self, fetch_fn, releases, expected_latest, expected_date_keys):+ with patch("posthog.egress.transport.transport.requests.request") as mock_get:+ self.setup_ok_json_mock(mock_get, releases)++ result = fetch_fn()++ assert result["latestVersion"] == expected_latest+ assert set(result["releaseDates"]) == expected_date_keys+++class TestLatestVersionSelection(TestFetchSdkDataBase):+ @patch("posthog.egress.transport.transport.requests.request")+ def test_backported_hotfix_listed_first_is_not_latest(self, mock_get):+ # GitHub orders /releases by creation date, so a hotfix on an older release line+ # appears before the actual newest version+ self.setup_ok_json_mock(+ mock_get,+ [+ _release("[email protected]", "2026-08-01T00:00:00Z"),+ _release("[email protected]", "2026-07-20T00:00:00Z"),+ ],+ )++ result = fetch_web_sdk_data()++ assert result["latestVersion"] == "1.298.1"++ @patch("posthog.egress.transport.transport.requests.request")+ def test_unparseable_tag_cannot_become_latest(self, mock_get):+ # posthog-ios matches every release tag; a stray non-version tag must not win+ self.setup_ok_json_mock(+ mock_get,+ [+ _release("list", "2026-08-01T00:00:00Z"),+ _release("3.69.2", "2026-07-20T00:00:00Z"),+ ],+ )++ result = fetch_ios_sdk_data()++ assert result["latestVersion"] == "3.69.2"+++class TestFetchReleasesFailureHandling(TestFetchSdkDataBase):+ @patch("posthog.egress.transport.transport.requests.request")+ def test_mid_pagination_failure_returns_no_data(self, mock_get):+ # A partial page set can miss versions and produce a wrong "latest"; the fetch must+ # fail closed so the previously cached Redis data keeps serving+ page1 = MagicMock()+ page1.ok = True+ page1.status_code = 200+ page1.json.return_value = [_release("[email protected]", "2026-07-20T00:00:00Z")] * 100++ page2 = MagicMock()+ page2.ok = False+ page2.status_code = 403++ mock_get.side_effect = [page1, page2]++ result = fetch_web_sdk_data()++ assert result == {}++ def test_failed_fetch_is_not_cached(self):+ repo = "PostHog/example-repo"+ local_releases_cache.pop(repo, None)++ fail = MagicMock()+ fail.ok = False+ fail.status_code = 403++ ok_page = MagicMock()+ ok_page.ok = True+ ok_page.status_code = 200+ ok_page.json.return_value = [_release("1.0.0", "2026-07-20T00:00:00Z")]++ empty_page = MagicMock()+ empty_page.ok = True+ empty_page.status_code = 200+ empty_page.json.return_value = []++ with (+ override_settings(TEST=False),+ patch("posthog.egress.transport.transport.requests.request") as mock_get,+ ):+ mock_get.side_effect = [fail, ok_page, empty_page]++ assert fetch_releases_from_repo(repo) == []+ # The failure must not be cached: the next call retries and succeeds+ releases = fetch_releases_from_repo(repo)++ local_releases_cache.pop(repo, None)+ assert len(releases) == 1++ def test_cached_releases_expire(self):+ repo = "PostHog/example-repo-ttl"+ local_releases_cache.pop(repo, None)++ def ok_pages():+ page = MagicMock()+ page.ok = True+ page.status_code = 200+ page.json.return_value = [_release("1.0.0", "2026-07-20T00:00:00Z")]+ empty = MagicMock()+ empty.ok = True+ empty.status_code = 200+ empty.json.return_value = []+ return [page, empty]++ with (+ override_settings(TEST=False),+ patch("posthog.egress.transport.transport.requests.request") as mock_get,+ patch("products.growth.dags.github_sdk_versions.time.monotonic") as mock_time,+ ):+ mock_get.side_effect = ok_pages() + ok_pages()++ mock_time.return_value = 0.0+ fetch_releases_from_repo(repo)+ fetch_releases_from_repo(repo)+ assert mock_get.call_count == 2 # Second call within the TTL is served from cache++ mock_time.return_value = LOCAL_RELEASES_CACHE_TTL_SECONDS + 1.0+ fetch_releases_from_repo(repo)+ assert mock_get.call_count == 4 # Past the TTL the releases are refetched++ local_releases_cache.pop(repo, None)++class TestSupportsUnprefixedReleaseTags(TestFetchSdkDataBase):@pytest.mark.parametrize("fetch_fn,latest_tag,previous_tag,previous_version,latest_created_at,previous_created_at",diff --git a/products/growth/frontend/generated/api.schemas.ts b/products/growth/frontend/generated/api.schemas.tsindex 128692e56756..a90ae8420ab8 100644--- a/products/growth/frontend/generated/api.schemas.ts+++ b/products/growth/frontend/generated/api.schemas.ts@@ -655,7 +655,7 @@ export const IdentityMatchingLinksListTier = {export type SdkHealthReportRetrieveParams = {/**- * When true, bypasses the Redis cache and re-queries ClickHouse for SDK usage. Use sparingly — data is refreshed every 12 hours by a background job.+ * When true, bypasses the Redis cache and re-queries ClickHouse for SDK usage. A background job refreshes this data once a day, so the cached answer is usually current. Use sparingly.*/force_refresh?: boolean}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d6612f6f6cd9..431153facaac 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -90553,7 +90553,7 @@ export namespace Schemas {export type SdkHealthReportRetrieveParams = {/**- * When true, bypasses the Redis cache and re-queries ClickHouse for SDK usage. Use sparingly — data is refreshed every 12 hours by a background job.+ * When true, bypasses the Redis cache and re-queries ClickHouse for SDK usage. A background job refreshes this data once a day, so the cached answer is usually current. Use sparingly.*/force_refresh?: boolean;};