: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
chore(deps): pin PostHog SDKs to their current majors (#108085)
Eli Reisman0fa4f99d0d95
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex e49492b15f21..049c2374f151 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -417,6 +417,7 @@ jobs:schema: ${{ steps.filter.outputs.schema || 'true' }}product_yamls: ${{ steps.filter.outputs.product_yamls || 'false' }}repo_invariants: ${{ steps.filter.outputs.repo_invariants || 'false' }}+ sdk_manifests: ${{ steps.filter.outputs.sdk_manifests || 'true' }}product_yamls_files: ${{ steps.filter.outputs.product_yamls_files }}steps:# For pull requests it's not necessary to checkout the code, but we@@ -681,6 +682,34 @@ jobs:- '.github/workflows/ci-python.yml'- 'products/ruff.toml'- '.github/scripts/**'+ sdk_manifests:+ # Everything the SDK major-version guard reads. Lockfiles are listed+ # because a floor-only or `*` spec can move to a new major through+ # its lock alone.+ - '**/package.json'+ - 'pnpm-workspace.yaml'+ - 'pnpm-lock.yaml'+ - 'products/desktop/pnpm-workspace.yaml'+ - 'products/desktop/pnpm-lock.yaml'+ - 'pyproject.toml'+ - 'uv.lock'+ - 'services/llm-gateway/pyproject.toml'+ - 'services/llm-gateway/uv.lock'+ - 'common/ingestion/acceptance_tests/requirements.txt'+ - 'tools/infra-scripts/clitools/requirements.txt'+ - 'tools/infra-scripts/clitools/constraints.txt'+ - 'rust/Cargo.toml'+ - 'rust/Cargo.lock'+ - 'cli/Cargo.toml'+ - 'cli/Cargo.lock'+ - 'bin/hobby-installer/go.mod'+ - 'bin/hobby-installer/go.sum'+ - '.github/scripts/check_sdk_majors.py'+ # The guard scans every package.json for an SDK declaration.+ - '**/package.json'+ - 'rust/Cargo.toml'+ - 'cli/Cargo.toml'+ - 'bin/hobby-installer/go.mod'product_yamls:- 'products/*/product.yaml'- '**/owners.yaml'@@ -1616,6 +1645,20 @@ jobs:# Lightweight repo-wide checks that only need Python + uv (no Docker/DB).# Consolidates checks that previously each spun up their own runner.+ # Every PostHog SDK this repo installs must stay on its pinned major; the release+ # bots rewrite manifests across majors, so this is the block. Stdlib only, no venv.+ sdk-major-guard:+ needs: [changes]+ if: needs.changes.outputs.sdk_manifests == 'true' && github.event_name != 'push'+ timeout-minutes: 5+ permissions: {}+ name: SDK major-version guard (depot-ubuntu-24.04)+ runs-on: depot-ubuntu-24.04+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ - name: Check every SDK stays on its pinned major+ run: python3 .github/scripts/check_sdk_majors.py+repo-checks:needs: [changes]# product_yamls: ownership-only PRs still need the owners.yaml lint below.@@ -4199,6 +4242,7 @@ jobs:detect-snapshot-mode,handle-snapshots,repo-checks,+ sdk-major-guard,]name: Django Tests Pass on Depotruns-on: depot-ubuntu-24.04@@ -4229,6 +4273,7 @@ jobs:echo "| check-migrations | ${{ needs.check-migrations.result }} |"echo "| check-openapi-types | ${{ needs.check-openapi-types.result }} |"echo "| repo-checks | ${{ needs.repo-checks.result }} |"+ echo "| sdk-major-guard | ${{ needs.sdk-major-guard.result }} |"echo "| turbo-discover | ${{ needs.turbo-discover.result }} |"echo "| build-product-test-matrix | ${{ needs.build-product-test-matrix.result }} |"echo "| turbo-tests | ${{ needs.turbo-tests.result }} |"@@ -4362,6 +4407,7 @@ jobs:check_required_result "OpenAPI type checks" "${{ needs.check-openapi-types.result }}"check_required_result "Hand-off wait" "${{ needs.wait-for-handoff.result }}"check_required_result "Repo checks" "${{ needs.repo-checks.result }}"+ check_required_result "SDK major guard" "${{ needs.sdk-major-guard.result }}"check_required_result "Turbo discover" "${{ needs.turbo-discover.result }}"check_required_result "Product test matrix build" "${{ needs.build-product-test-matrix.result }}"check_required_result "Product/Turbo tests" "${{ needs.turbo-tests.result }}"diff --git a/.github/scripts/check_sdk_majors.py b/.github/scripts/check_sdk_majors.pynew file mode 100644index 000000000000..30e5b78a4ae2--- /dev/null+++ b/.github/scripts/check_sdk_majors.py@@ -0,0 +1,388 @@+#!/usr/bin/env python3+# ruff: noqa: T201 allow print statements+"""+CI check: every PostHog SDK this repo installs stays on the major it was migrated to.++A new SDK major removes legacy capture and changes the capture API, so taking one is a+reviewed migration, never a routine bump. The SDK release bots rewrite these manifests+on every release, so the declared spec alone cannot hold the line: this checks every+manifest that names an SDK, the resolved lockfile versions, and the SDK range each+wrapper package accepts.++To take a major on purpose, raise its entry in EXPECTED_MAJORS in the PR that moves the+call sites.++Usage:+ python3 .github/scripts/check_sdk_majors.py++Exit codes:+ 0 - every SDK is on its expected major+ 1 - a manifest, lockfile or wrapper peer range reaches another major+"""++from __future__ import annotations++import re+import sys+import json+import tomllib+from pathlib import Path+from typing import NamedTuple++REPO_ROOT = Path(__file__).resolve().parent.parent.parent+SKIPPED_DIRS = {"node_modules", ".git", "dist", ".venv", "target", ".flox", "build"}++# posthog-python is published under two names: `posthoganalytics` for this repo (its+# Django package is also called posthog) and `posthog` everywhere else.+EXPECTED_MAJORS = {+ "posthoganalytics": 7,+ "posthog": 7,+ "posthog-node": 5,+ "posthog-js": 1,+ "@posthog/react": 1,+ "posthog-js-lite": 4,+ "posthog-react-native": 4,+ "posthog-rs": 0,+ "posthog-go": 1,+}+NPM_SDKS = ("posthog-node", "posthog-js", "@posthog/react", "posthog-js-lite", "posthog-react-native")+NPM_SECTIONS = ("dependencies", "devDependencies", "optionalDependencies", "peerDependencies")++# pnpm workspaces: (manifest path prefix, workspace file, lockfile). The first match wins.+NPM_WORKSPACES = (+ ("products/desktop/", "products/desktop/pnpm-workspace.yaml", "products/desktop/pnpm-lock.yaml"),+ ("", "pnpm-workspace.yaml", "pnpm-lock.yaml"),+)++# Wrapper packages that depend on an SDK. A routine wrapper release can raise its peer+# range to the next SDK major, which is the same breaking change through a side door.+NODE_WRAPPER_PEERS = (+ ("pnpm-lock.yaml", "@posthog/react", "posthog-js"),+ ("pnpm-lock.yaml", "@posthog/mcp", "posthog-node"),+)++# (manifest, package, lockfile or None)+PYTHON_PINS = (+ ("pyproject.toml", "posthoganalytics", "uv.lock"),+ ("services/llm-gateway/pyproject.toml", "posthoganalytics", "services/llm-gateway/uv.lock"),+ ("common/ingestion/acceptance_tests/requirements.txt", "posthoganalytics", None),+ ("tools/infra-scripts/clitools/requirements.txt", "posthog", None),+)++# (manifest, TOML path to the dependency table, lockfile). posthog-rs is 0.x, so Cargo+# already treats every minor as breaking and the bot bumps those routinely; the guard+# holds only the major, which keeps 1.0 out until its migration.+RUST_PINS = (+ ("rust/Cargo.toml", ("workspace", "dependencies"), "rust/Cargo.lock"),+ ("cli/Cargo.toml", ("dependencies",), "cli/Cargo.lock"),+)++GO_MODULE = "github.com/posthog/posthog-go"+GO_MANIFEST = "bin/hobby-installer/go.mod"+GO_SUM = "bin/hobby-installer/go.sum"++MIGRATION_HINT = "A new SDK major needs a migration PR; raise EXPECTED_MAJORS there."+++class MajorRange(NamedTuple):+ low: int+ high: int | None # inclusive; None means no upper bound+++def _major(version: str) -> int:+ match = re.match(r"v?(\d+)", version)+ if not match:+ raise ValueError(f"cannot read a major from {version!r}")+ return int(match.group(1))+++def _is_next_major_boundary(version: str, major: int) -> bool:+ """True for a version that is exactly the first release of major + 1, such as 8, 8.0 or 8.0.0."""+ return re.fullmatch(rf"v?{major + 1}(\.0)*(-0)?", version) is not None+++def _named(package: str) -> re.Pattern[str]:+ """Match `package` followed by an operator, an extra, or the end, never a longer name."""+ return re.compile(rf"^{re.escape(package)}(\[|[^A-Za-z0-9_.-]|$)")+++def npm_ranges(spec: str) -> list[MajorRange]:+ """The majors an npm range admits, one MajorRange per `||` alternative."""+ ranges = []+ for alternative in spec.split("||"):+ alternative = alternative.strip()+ if alternative in ("", "*", "latest", "x") or alternative.startswith(("workspace:", "catalog:", "npm:")):+ ranges.append(MajorRange(0, None))+ continue+ low, high = 0, None+ for token in alternative.split():+ if token.startswith(("^", "~", "=")):+ major = _major(token.lstrip("^~="))+ low, high = max(low, major), major if high is None else min(high, major)+ elif token.startswith(">="):+ low = max(low, _major(token[2:]))+ elif token.startswith(">"):+ # A bare `>5` excludes every 5.x; `>5.1` means `>=5.2.0` and still admits major 5.+ bound = token[1:]+ low = max(low, _major(bound) + 1 if re.fullmatch(r"v?\d+", bound) else _major(bound))+ elif token.startswith("<="):+ high = _major(token[2:]) if high is None else min(high, _major(token[2:]))+ elif token.startswith("<"):+ bound = token[1:]+ cap = _major(bound) - 1 if _is_next_major_boundary(bound, _major(bound) - 1) else _major(bound)+ high = cap if high is None else min(high, cap)+ else:+ major = _major(token.replace("x", "0"))+ low, high = max(low, major), major if high is None else min(high, major)+ ranges.append(MajorRange(low, high))+ return ranges+++def npm_pinned_to(spec: str, expected: int) -> bool:+ return all(r.low == expected and r.high == expected for r in npm_ranges(spec))+++def npm_admits(spec: str, expected: int) -> bool:+ return any(r.low <= expected and (r.high is None or expected <= r.high) for r in npm_ranges(spec))+++def pnpm_catalog(workspace_file: Path) -> dict[str, str]:+ catalog: dict[str, str] = {}+ in_catalog = False+ for line in workspace_file.read_text(encoding="utf-8").splitlines():+ if line.startswith("catalog:"):+ in_catalog = True+ continue+ if in_catalog and line and not line.startswith(" "):+ break+ match = re.match(r"^\s+'?([^':\s]+)'?:\s*'?([^'#]+?)'?\s*(#.*)?$", line) if in_catalog else None+ if match:+ catalog[match.group(1)] = match.group(2)+ return catalog+++def pnpm_lock_majors(lock_text: str, package: str) -> set[int]:+ pattern = re.compile(rf"^ '?{re.escape(package)}@(\d+)\.", re.MULTILINE)+ return {int(m.group(1)) for m in pattern.finditer(lock_text)}+++def pnpm_lock_peer_ranges(lock_text: str, package: str, peer: str) -> dict[str, str]:+ """Every version of `package` in the lock's packages section, with the range it declares on `peer`."""+ ranges = {}+ for entry in re.finditer(rf"^ '{re.escape(package)}@([^(']+)':\n((?: .*\n)+)", lock_text, re.MULTILINE):+ peer_line = re.search(rf"^ '?{re.escape(peer)}'?:\s*'?([^'\n]+?)'?$", entry.group(2), re.MULTILINE)+ ranges[entry.group(1)] = peer_line.group(1) if peer_line else ""+ return ranges+++def npm_workspace_for(manifest: str) -> tuple[str, str]:+ for prefix, workspace_file, lock in NPM_WORKSPACES:+ if manifest.startswith(prefix):+ return workspace_file, lock+ raise AssertionError("unreachable: the root workspace matches every path")+++def npm_manifests(root: Path) -> list[tuple[str, str, str, str]]:+ """Every (manifest, section, package, spec) under root that names an npm SDK."""+ found = []+ for path in sorted(root.rglob("package.json")):+ if SKIPPED_DIRS.intersection(path.parts):+ continue+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, UnicodeDecodeError):+ continue+ manifest = path.relative_to(root).as_posix()+ for section in NPM_SECTIONS:+ deps = data.get(section)+ if not isinstance(deps, dict):+ continue+ for package in NPM_SDKS:+ if package in deps:+ found.append((manifest, section, package, deps[package]))+ return found+++def pep440_clauses(spec: str) -> list[tuple[str, str]]:+ body = re.sub(r"^[A-Za-z0-9_.-]+(\[[^\]]*\])?", "", spec.strip())+ return [(m.group(1), m.group(2)) for m in re.finditer(r"(===|==|~=|!=|<=|>=|<|>)\s*([0-9][0-9A-Za-z.*+!-]*)", body)]+++def python_floor_major(spec: str) -> int:+ floors = [_major(v) for op, v in pep440_clauses(spec) if op in ("==", "===", "~=", ">=", ">")]+ if not floors:+ raise ValueError(f"{spec!r} has no lower bound")+ return max(floors)+++def python_capped_at(major: int, *specs: str) -> bool:+ """True when the specs together exclude every version of major + 1."""+ for spec in specs:+ for op, version in pep440_clauses(spec):+ if op in ("==", "===", "~="):+ return True+ if op == "<" and (_major(version) <= major or _is_next_major_boundary(version, major)):+ return True+ if op == "<=" and _major(version) <= major:+ return True+ return False+++def requirements_lines(text: str) -> list[str]:+ return [line.strip() for line in text.splitlines() if line.strip() and not line.startswith("#")]+++def cargo_requirement_major(requirement: str) -> int:+ """Cargo treats a bare version as a caret, so `0.27.0` admits only 0.27.x."""+ if re.search(r"[*<>,]", requirement) or not requirement.strip():+ raise ValueError(f"{requirement!r} is not a caret, tilde or exact requirement, so it can float across majors")+ return _major(requirement.lstrip("^~="))+++def _lock_package_major(lock_path: Path, package: str) -> int:+ packages = tomllib.loads(lock_path.read_text(encoding="utf-8"))["package"]+ return _major(next(p["version"] for p in packages if p["name"] == package))+++def check_node(root: Path) -> list[str]:+ problems = []+ for manifest, section, package, spec in npm_manifests(root):+ workspace_file, _lock = npm_workspace_for(manifest)+ expected = EXPECTED_MAJORS[package]+ if spec == "catalog:":+ spec = pnpm_catalog(root / workspace_file).get(package, "")+ if not npm_pinned_to(spec, expected):+ problems.append(+ f"{manifest} [{section}]: {package} declares {spec!r}, which is not pinned to major {expected}. {MIGRATION_HINT}"+ )+ for _prefix, workspace_file, lock in NPM_WORKSPACES:+ catalog = pnpm_catalog(root / workspace_file)+ for package in NPM_SDKS:+ if package in catalog and not npm_pinned_to(catalog[package], EXPECTED_MAJORS[package]):+ problems.append(+ f"{workspace_file} catalog: {package} is {catalog[package]!r}, expected major {EXPECTED_MAJORS[package]}"+ )+ lock_text = (root / lock).read_text(encoding="utf-8")+ for package in NPM_SDKS:+ resolved = pnpm_lock_majors(lock_text, package)+ if resolved and resolved != {EXPECTED_MAJORS[package]}:+ problems.append(+ f"{lock} resolves {package} to majors {sorted(resolved)}, expected {{{EXPECTED_MAJORS[package]}}}"+ )+ for lock, package, peer in NODE_WRAPPER_PEERS:+ lock_text = (root / lock).read_text(encoding="utf-8")+ ranges = pnpm_lock_peer_ranges(lock_text, package, peer)+ if not ranges:+ problems.append(f"{lock} has no packages entry for {package}")+ for version, peer_range in ranges.items():+ if not peer_range:+ problems.append(f"{lock}: {package}@{version} declares no peer dependency on {peer}")+ elif not npm_admits(peer_range, EXPECTED_MAJORS[peer]):+ problems.append(+ f"{package}@{version} requires {peer} {peer_range!r}, which excludes major {EXPECTED_MAJORS[peer]}. {MIGRATION_HINT}"+ )+ return problems+++def check_python(root: Path) -> list[str]:+ problems = []+ for manifest, package, lock in PYTHON_PINS:+ text = (root / manifest).read_text(encoding="utf-8")+ expected = EXPECTED_MAJORS[package]+ if manifest.endswith("pyproject.toml"):+ data = tomllib.loads(text)+ spec = next((d for d in data["project"]["dependencies"] if _named(package).match(d)), None)+ extra = [+ c+ for c in data.get("tool", {}).get("uv", {}).get("constraint-dependencies", [])+ if _named(package).match(c)+ ]+ cap_home = "[tool.uv] constraint-dependencies"+ else:+ lines = requirements_lines(text)+ spec = next((line for line in lines if _named(package).match(line)), None)+ extra = []+ for line in lines:+ if line.startswith("-c "):+ constraints = (root / manifest).parent / line.split(None, 1)[1]+ extra += [+ c+ for c in requirements_lines(constraints.read_text(encoding="utf-8"))+ if _named(package).match(c)+ ]+ cap_home = "a constraints file"+ if spec is None:+ problems.append(f"{manifest} no longer declares {package}")+ continue+ if python_floor_major(spec) != expected:+ problems.append(f"{manifest}: {package} declares {spec!r}, expected major {expected}. {MIGRATION_HINT}")+ if not python_capped_at(expected, spec, *extra):+ problems.append(+ f"{manifest}: {package} {spec!r} can reach major {expected + 1}; the upper bound belongs in {cap_home}"+ )+ if lock and _lock_package_major(root / lock, package) != expected:+ problems.append(f"{lock} resolves {package} outside major {expected}")+ return problems+++def check_rust(root: Path) -> list[str]:+ problems = []+ expected = EXPECTED_MAJORS["posthog-rs"]+ for manifest, table, lock in RUST_PINS:+ data = tomllib.loads((root / manifest).read_text(encoding="utf-8"))+ for key in table:+ data = data[key]+ dependency = data["posthog-rs"]+ requirement = dependency if isinstance(dependency, str) else dependency["version"]+ try:+ major = cargo_requirement_major(requirement)+ except ValueError as err:+ problems.append(f"{manifest}: {err}")+ continue+ if major != expected:+ problems.append(f"{manifest}: posthog-rs = {requirement!r}, expected major {expected}. {MIGRATION_HINT}")+ if _lock_package_major(root / lock, "posthog-rs") != expected:+ problems.append(f"{lock} resolves posthog-rs outside major {expected}")+ return problems+++def check_go(root: Path) -> list[str]:+ problems = []+ expected = EXPECTED_MAJORS["posthog-go"]+ # A Go major is a new module path: v1 has no suffix, every later major carries /vN.+ expected_suffix = "" if expected == 1 else f"/v{expected}"+ requires = re.findall(+ rf"^\s*{re.escape(GO_MODULE)}(/v\d+)?\s+(v\d+)", (root / GO_MANIFEST).read_text(encoding="utf-8"), re.MULTILINE+ )+ if not requires:+ problems.append(f"{GO_MANIFEST} no longer requires posthog-go")+ for suffix, version in requires:+ if suffix != expected_suffix or _major(version) != expected:+ problems.append(+ f"{GO_MANIFEST} requires {GO_MODULE}{suffix} {version}, expected {GO_MODULE}{expected_suffix} v{expected}. {MIGRATION_HINT}"+ )+ sums = re.findall(+ rf"^{re.escape(GO_MODULE)}(/v\d+)? (v\d+)", (root / GO_SUM).read_text(encoding="utf-8"), re.MULTILINE+ )+ if not sums or any(suffix != expected_suffix or _major(version) != expected for suffix, version in sums):+ problems.append(f"{GO_SUM} records posthog-go outside {GO_MODULE}{expected_suffix} v{expected}")+ return problems+++def check_all(root: Path) -> list[str]:+ return check_node(root) + check_python(root) + check_rust(root) + check_go(root)+++def main() -> int:+ problems = check_all(REPO_ROOT)+ for problem in problems:+ print(f"::error::{problem}")+ if problems:+ print(f"\n{len(problems)} SDK major-version problem(s). {MIGRATION_HINT}")+ return 1+ print("Every PostHog SDK is on its expected major.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/scripts/test_check_sdk_majors.py b/.github/scripts/test_check_sdk_majors.pynew file mode 100644index 000000000000..2797bf1763e4--- /dev/null+++ b/.github/scripts/test_check_sdk_majors.py@@ -0,0 +1,121 @@+import json+import importlib.util+from pathlib import Path++import pytest++SCRIPT = Path(__file__).with_name("check_sdk_majors.py")+spec = importlib.util.spec_from_file_location("check_sdk_majors", SCRIPT)+guard = importlib.util.module_from_spec(spec)+assert spec.loader is not None+spec.loader.exec_module(guard)+++ "spec,expected,pinned,admits",+ [+ ("5.54.1", 5, True, True),+ ("^5.54.1", 5, True, True),+ ("~5.54.1", 5, True, True),+ ("^0.18.1", 0, True, True),+ (">=5.0.0 <6.0.0", 5, True, True),+ (">=5.0.0 <6.0.0-0", 5, True, True),+ (">=5.0.0 <6.1.0", 5, False, True),+ (">=5.0.0", 5, False, True),+ (">=1.257.2", 1, False, True),+ ("^5.0.0 || ^6.0.0", 5, False, True),+ ("^6.0.0", 5, False, False),+ ("*", 5, False, True),+ ("latest", 5, False, True),+ ("<5", 5, False, False),+ ("<5.0.0-0", 5, False, False),+ (">5", 5, False, False),+ (">5.0.0", 5, False, True),+ (">5.1", 5, False, True),+ (">4 <6", 5, True, True),+ ],+)+def test_npm_range_semantics(spec: str, expected: int, pinned: bool, admits: bool) -> None:+ assert guard.npm_pinned_to(spec, expected) is pinned+ assert guard.npm_admits(spec, expected) is admits+++ "specs,expected,capped",+ [+ (("posthoganalytics==7.60.1",), 7, True),+ (("posthoganalytics~=7.60",), 7, True),+ (("posthoganalytics>=7.60.1",), 7, False),+ (("posthoganalytics>=7.60.1,<8",), 7, True),+ (("posthoganalytics>=7.60.1,<8.0.0",), 7, True),+ (("posthoganalytics>=7.60.1,<8.1",), 7, False),+ (("posthoganalytics>=7.60.1", "posthoganalytics<8"), 7, True),+ (("posthoganalytics>=7.60.1", "posthoganalytics<9"), 7, False),+ (("posthog>=7.60.1", "posthog<=7.99"), 7, True),+ (("posthog>=7.60.1", "posthog<=8"), 7, False),+ ],+)+def test_python_cap_semantics(specs: tuple[str, ...], expected: int, capped: bool) -> None:+ assert guard.python_floor_major(specs[0]) == expected+ assert guard.python_capped_at(expected, *specs) is capped+++ "package,candidate,matches",+ [+ ("posthog", "posthog<8", True),+ ("posthog", "posthog[extra]>=7", True),+ ("posthog", "posthoganalytics<8", False),+ ("posthoganalytics", "posthoganalytics>=7.60.1", True),+ ],+)+def test_python_constraint_names_match_exactly(package: str, candidate: str, matches: bool) -> None:+ assert bool(guard._named(package).match(candidate)) is matches++[email protected]("requirement,major", [("0.27.0", 0), ("^0.27", 0), ("=1.2.3", 1), ("~0.24.0", 0)])+def test_cargo_requirement_major(requirement: str, major: int) -> None:+ assert guard.cargo_requirement_major(requirement) == major++[email protected]("requirement", ["*", ">=0.27", "0.27, <2", ""])+def test_cargo_requirement_rejects_floating_ranges(requirement: str) -> None:+ with pytest.raises(ValueError):+ guard.cargo_requirement_major(requirement)+++def test_npm_manifests_finds_every_sdk_declaration_and_picks_the_workspace(tmp_path: Path) -> None:+ (tmp_path / "products" / "desktop" / "apps" / "code").mkdir(parents=True)+ (tmp_path / "node_modules" / "x").mkdir(parents=True)+ (tmp_path / "package.json").write_text(+ json.dumps({"dependencies": {"posthog-js": "catalog:"}, "peerDependencies": {"@posthog/react": "*"}})+ )+ (tmp_path / "products" / "desktop" / "apps" / "code" / "package.json").write_text(+ json.dumps({"dependencies": {"posthog-node": "^5.54.1"}})+ )+ (tmp_path / "node_modules" / "x" / "package.json").write_text(json.dumps({"dependencies": {"posthog-node": "*"}}))++ found = guard.npm_manifests(tmp_path)++ assert found == [+ ("package.json", "dependencies", "posthog-js", "catalog:"),+ ("package.json", "peerDependencies", "@posthog/react", "*"),+ ("products/desktop/apps/code/package.json", "dependencies", "posthog-node", "^5.54.1"),+ ]+ assert guard.npm_workspace_for("products/desktop/apps/code/package.json") == (+ "products/desktop/pnpm-workspace.yaml",+ "products/desktop/pnpm-lock.yaml",+ )+ assert guard.npm_workspace_for("package.json") == ("pnpm-workspace.yaml", "pnpm-lock.yaml")+++def test_pnpm_lock_peer_ranges_returns_every_version() -> None:+ lock = (+ "packages:\n\n"+ " '@posthog/[email protected]':\n resolution: {integrity: x}\n peerDependencies:\n posthog-js: '>=1.257.2'\n\n"+ " '@posthog/[email protected]':\n resolution: {integrity: y}\n peerDependencies:\n posthog-js: ^2.0.0\n\n"+ )+ assert guard.pnpm_lock_peer_ranges(lock, "@posthog/react", "posthog-js") == {+ "1.9.0": ">=1.257.2",+ "1.11.2": "^2.0.0",+ }diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 8093cfaa7da8..4c8796d3e8ad 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -179,6 +179,7 @@ jobs:schema: ${{ steps.filter.outputs.schema || 'true' }}product_yamls: ${{ steps.filter.outputs.product_yamls || 'false' }}repo_invariants: ${{ steps.filter.outputs.repo_invariants || 'false' }}+ sdk_manifests: ${{ steps.filter.outputs.sdk_manifests || 'true' }}product_yamls_files: ${{ steps.filter.outputs.product_yamls_files }}timing_scripts: ${{ steps.filter.outputs.timing_scripts }}# Which engine runs this event's backend tests. Depot CI never decides on its@@ -450,6 +451,34 @@ jobs:- '.github/workflows/ci-python.yml'- 'products/ruff.toml'- '.github/scripts/**'+ sdk_manifests:+ # Everything the SDK major-version guard reads. Lockfiles are listed+ # because a floor-only or `*` spec can move to a new major through+ # its lock alone.+ - '**/package.json'+ - 'pnpm-workspace.yaml'+ - 'pnpm-lock.yaml'+ - 'products/desktop/pnpm-workspace.yaml'+ - 'products/desktop/pnpm-lock.yaml'+ - 'pyproject.toml'+ - 'uv.lock'+ - 'services/llm-gateway/pyproject.toml'+ - 'services/llm-gateway/uv.lock'+ - 'common/ingestion/acceptance_tests/requirements.txt'+ - 'tools/infra-scripts/clitools/requirements.txt'+ - 'tools/infra-scripts/clitools/constraints.txt'+ - 'rust/Cargo.toml'+ - 'rust/Cargo.lock'+ - 'cli/Cargo.toml'+ - 'cli/Cargo.lock'+ - 'bin/hobby-installer/go.mod'+ - 'bin/hobby-installer/go.sum'+ - '.github/scripts/check_sdk_majors.py'+ # The guard scans every package.json for an SDK declaration.+ - '**/package.json'+ - 'rust/Cargo.toml'+ - 'cli/Cargo.toml'+ - 'bin/hobby-installer/go.mod'product_yamls:# Validates owner team slugs against PostHog/posthog collaborator teams,# and lints the distributed owners.yaml files (schema, conflicts, dead@@ -1409,6 +1438,20 @@ jobs:# Lightweight repo-wide checks that only need Python + uv (no Docker/DB).# Consolidates checks that previously each spun up their own runner.+ # Every PostHog SDK this repo installs must stay on its pinned major; the release+ # bots rewrite manifests across majors, so this is the block. Stdlib only, no venv.+ sdk-major-guard:+ needs: [changes]+ if: needs.changes.outputs.sdk_manifests == 'true' && github.event_name != 'schedule' && needs.changes.outputs.engine != 'depot'+ timeout-minutes: 5+ permissions: {}+ name: SDK major-version guard+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ - name: Check every SDK stays on its pinned major+ run: python3 .github/scripts/check_sdk_majors.py+repo-checks:needs: [changes]# product_yamls: ownership-only PRs still need the owners.yaml lint below.@@ -4225,6 +4268,7 @@ jobs:detect-snapshot-mode,handle-snapshots,repo-checks,+ sdk-major-guard,]name: Django Tests Passruns-on: ubuntu-24.04@@ -4280,6 +4324,7 @@ jobs:echo "| Dependency | Result |"echo "| --- | --- |"echo "| repo-checks | ${{ needs.repo-checks.result }} |"+ echo "| sdk-major-guard | ${{ needs.sdk-major-guard.result }} |"echo "| check-openapi-types | ${{ needs.check-openapi-types.result }} |"echo "| changes | ${{ needs.changes.result }} |"echo "| get_clickhouse_versions | ${{ needs.get_clickhouse_versions.result }} |"@@ -4409,6 +4454,7 @@ jobs:}check_required_result "Repo checks" "${{ needs.repo-checks.result }}"+ check_required_result "SDK major guard" "${{ needs.sdk-major-guard.result }}"check_required_result "OpenAPI type checks" "${{ needs.check-openapi-types.result }}"# Upstream jobs whose failure would otherwise only cascade into django# being *skipped*, which this gate reads as success — a green gate withdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 824e6f2437d0..827b2839198a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4824,8 +4824,8 @@ importers:specifier: 'catalog:''@posthog/react':- specifier: '*'- version: 1.9.0(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ specifier: 'catalog:'+ version: 1.11.2(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected])'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])@@ -5140,8 +5140,8 @@ importers:specifier: 'catalog:''@posthog/react':- specifier: '*'- version: 1.9.0(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ specifier: 'catalog:'+ version: 1.11.2(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected])'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])@@ -10827,16 +10827,6 @@ packages:'@types/react':optional: true- '@posthog/[email protected]':- resolution: {integrity: sha512-lVdTsWT5+PtHBu44gSQ7QohbLjAYqHkFAIGAQ+HV8Eh9yj+OcnQ7mXCmyhaMlTBD3z7D0H1eWMp4vQaFnsIyWQ==}- peerDependencies:- '@types/react': 18.3.27- posthog-js: '>=1.257.2'- react: 18.3.1- peerDependenciesMeta:- '@types/react':- optional: true-'@posthog/[email protected]':resolution: {integrity: sha512-JUFk57H89fOnHpF62FDyFGw4uXeHAX20OPfkLL8/iqg/xrVp5Q21LvJUDijmS5wt0avgUwXF2bxYgaZ5iWRmAg==}@@ -30434,13 +30424,6 @@ snapshots:optionalDependencies:'@types/react': 18.3.27- '@posthog/[email protected](@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected])':- dependencies:- posthog-js: 1.435.5(@types/[email protected])([email protected])- react: 18.3.1- optionalDependencies:- '@types/react': 18.3.27-'@posthog/[email protected]': {}'@posthog/[email protected]': {}diff --git a/products/stamphog/package.json b/products/stamphog/package.jsonindex 1267b7ecf24f..7d48564ca7c9 100644--- a/products/stamphog/package.json+++ b/products/stamphog/package.json@@ -16,7 +16,7 @@"peerDependencies": {"@posthog/brand": "catalog:","@posthog/icons": "catalog:",- "@posthog/react": "*",+ "@posthog/react": "catalog:","@storybook/react": "catalog:","@testing-library/dom": "*","@testing-library/user-event": "*",diff --git a/products/visual_review/package.json b/products/visual_review/package.jsonindex 0622be82d0dc..554b64bd65b8 100644--- a/products/visual_review/package.json+++ b/products/visual_review/package.json@@ -19,7 +19,7 @@"peerDependencies": {"@posthog/brand": "catalog:","@posthog/icons": "catalog:",- "@posthog/react": "*",+ "@posthog/react": "catalog:","@storybook/react": "catalog:","@testing-library/dom": "*","@testing-library/user-event": "*",diff --git a/pyproject.toml b/pyproject.tomlindex 63aa534a65a1..e16b2569fb2c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -312,6 +312,10 @@ required-version = ">=0.10.2"add-bounds = "major"exclude-newer = "7 days"exclude-newer-package = { hogql-parser = false, hogql-parser-rs = false, deltalite = false, posthoganalytics = false, pixelhog = false, django = false, modal = false, posthog-hogland = false, google-ads = false }+# posthoganalytics 8 removes legacy capture. The SDK release bot rewrites the+# dependency spec on every release, so this constraint is what stops a new major from+# landing by accident. Lift it in the migration PR that moves the call sites.+constraint-dependencies = ["posthoganalytics<8"][tool.uv.workspace]members = ["tools/hogli", "packages/owners-yaml", "packages/personhog-proto"]diff --git a/services/llm-gateway/pyproject.toml b/services/llm-gateway/pyproject.tomlindex 3636e33ac55a..e1a52a2c1a7d 100644--- a/services/llm-gateway/pyproject.toml+++ b/services/llm-gateway/pyproject.toml@@ -113,3 +113,6 @@ warn_unused_ignores = truemanaged = trueexclude-newer = "7 days"exclude-newer-package = { posthoganalytics = false }+# The SDK release bot resets the posthoganalytics spec to a floor on every release, so+# this constraint is what keeps a new major out until its migration PR.+constraint-dependencies = ["posthoganalytics<8"]diff --git a/services/llm-gateway/uv.lock b/services/llm-gateway/uv.lockindex 98ba7592c57c..c46351aba9cc 100644--- a/services/llm-gateway/uv.lock+++ b/services/llm-gateway/uv.lock@@ -9,6 +9,9 @@ exclude-newer-span = "P7D"[options.exclude-newer-package]posthoganalytics = false+[manifest]+constraints = [{ name = "posthoganalytics", specifier = "<8" }]+[[package]]name = "aiohappyeyeballs"version = "2.6.1"diff --git a/tools/infra-scripts/clitools/constraints.txt b/tools/infra-scripts/clitools/constraints.txtnew file mode 100644index 000000000000..14d06877b187--- /dev/null+++ b/tools/infra-scripts/clitools/constraints.txt@@ -0,0 +1,3 @@+# No lockfile here, so this cap is what keeps a fresh install on the current SDK major.+# posthog 8 removes legacy capture; lift the cap in the migration PR.+posthog<8diff --git a/tools/infra-scripts/clitools/requirements.txt b/tools/infra-scripts/clitools/requirements.txtindex 0bff203784ee..44b5d0ea958b 100644--- a/tools/infra-scripts/clitools/requirements.txt+++ b/tools/infra-scripts/clitools/requirements.txt@@ -1,4 +1,5 @@# PostHog Python SDK — used by toolbox/telemetry.py to capture usage events.# https://posthog.com/docs/libraries/python# >=3 required: the `Posthog` client class doesn't exist in older 1.x/2.x releases.+-c constraints.txtposthog>=7.60.1diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.tsindex fd0e7132ff86..f6c1e42575a1 100644--- a/tools/workflow-plan/tests/workflows.test.ts+++ b/tools/workflow-plan/tests/workflows.test.ts@@ -147,6 +147,7 @@ const frontendOnlyFilters: Stubs = {tasks_temporal: false,openapi_types: false,product_yamls: false,+ sdk_manifests: false,}),},}@@ -160,6 +161,7 @@ const EXPECTATIONS: Expectation[] = ['turbo-discover','django','repo-checks',+ 'sdk-major-guard','check-migrations','check-openapi-types','django_tests',@@ -208,6 +210,7 @@ const EXPECTATIONS: Expectation[] = ['detect-snapshot-mode','turbo-discover','repo-checks',+ 'sdk-major-guard','validate-product-yamls','check-migrations','check-openapi-types',@@ -291,7 +294,7 @@ const EXPECTATIONS: Expectation[] = [{ name: 'draft PR labeled no-ci', github: pullRequest({ draft: true, labels: ['no-ci'] }) },{runs: ['django_tests'],- skipped: ['changes', 'django', 'turbo-tests', 'repo-checks', 'check-migrations', 'dynamic-ci-filter'],+ skipped: ['changes', 'django', 'turbo-tests', 'repo-checks', 'sdk-major-guard', 'check-migrations', 'dynamic-ci-filter'],}),backend(@@ -318,13 +321,14 @@ const EXPECTATIONS: Expectation[] = ['django','get_clickhouse_versions','build_django_matrix',+ 'sdk-major-guard',],}),backend({ name: 'master push', github: push() },{- runs: ['changes', 'repo-checks', 'check-migrations', 'mirror-schema-cache', 'django_tests'],+ runs: ['changes', 'repo-checks', 'sdk-major-guard', 'check-migrations', 'mirror-schema-cache', 'django_tests'],skipped: ['dynamic-ci-filter','detect-snapshot-mode',@@ -341,7 +345,7 @@ const EXPECTATIONS: Expectation[] = [{ name: 'hourly schedule', github: schedule() },{runs: ['changes', 'turbo-tests', 'django', 'django_tests'],- skipped: ['repo-checks', 'check-migrations', 'check-openapi-types', 'mirror-schema-cache'],+ skipped: ['repo-checks', 'sdk-major-guard', 'check-migrations', 'check-openapi-types', 'mirror-schema-cache'],}),backend(diff --git a/uv.lock b/uv.lockindex 970208ec4069..b8933adae2e9 100644--- a/uv.lock+++ b/uv.lock@@ -32,6 +32,7 @@ members = ["personhog-proto","posthog",]+constraints = [{ name = "posthoganalytics", specifier = "<8" }][[manifest.dependency-metadata]]name = "xgboost"