: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(devex): make auto-reviewer assignment resilient to stale team slugs (#60033)
Julian Bez013a7e5f4af9
diff --git a/.github/scripts/assign-reviewers.js b/.github/scripts/assign-reviewers.jsindex 0b0e08653133..25d706e35c2b 100644--- a/.github/scripts/assign-reviewers.js+++ b/.github/scripts/assign-reviewers.js@@ -272,18 +272,56 @@ async function assignReviewers(teams, users) {console.info('Assigning reviewers with payload:', JSON.stringify(payload, null, 2))- const response = await fetch(- `https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/requested_reviewers`,- {+ const post = (body) =>+ fetch(`https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/requested_reviewers`, {method: 'POST',headers: {Authorization: `token ${GITHUB_TOKEN}`,Accept: 'application/vnd.github.v3+json','Content-Type': 'application/json',},- body: JSON.stringify(payload),+ body: JSON.stringify(body),+ })++ const response = await post(payload)++ // GitHub returns 422 for the whole batch if *any* requested team isn't a+ // collaborator on the repo (teams get renamed, deleted, or never set up —+ // CODEOWNERS-soft and product.yaml drift). Salvage by retrying users ++ // each team independently so valid entries still land, and log the bad+ // slugs so they're visible in the action log as cleanup nudges.+ if (response.status === 422 && teams.length > 0) {+ const errorText = await response.text()+ console.warn(`⚠️ 422 on bulk request, retrying individually:\n${errorText}`)++ if (users.length > 0) {+ const r = await post({ reviewers: users })+ if (!r.ok) {+ throw new Error(`GitHub API error assigning users: ${r.status} ${r.statusText}\n${await r.text()}`)+ }}- )++ const dropped = []+ for (const team of teams) {+ const r = await post({ team_reviewers: [team] })+ if (r.status === 422) {+ dropped.push(team)+ } else if (!r.ok) {+ throw new Error(+ `GitHub API error assigning team '${team}': ${r.status} ${r.statusText}\n${await r.text()}`+ )+ }+ }++ if (dropped.length > 0) {+ console.warn(+ `⚠️ Dropped ${dropped.length} stale team(s): ${dropped.join(', ')}. ` ++ `Fix product.yaml / CODEOWNERS-soft so these get assigned next time.`+ )+ }+ console.info('✅ Reviewers assigned (with fallback)')+ return+ }if (!response.ok) {const errorText = await response.text()diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex b48425b5a9e5..e7ecc5ca6c22 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -75,6 +75,8 @@ jobs:tasks_temporal: ${{ steps.filter.outputs.tasks_temporal || 'true' }}openapi_types: ${{ steps.filter.outputs.openapi_types || 'true' }}legacy: ${{ steps.filter.outputs.legacy || 'true' }}+ product_yamls: ${{ steps.filter.outputs.product_yamls || 'false' }}+ product_yamls_files: ${{ steps.filter.outputs.product_yamls_files }}steps:# For pull requests it's not necessary to checkout the code, but we# also want this to run on master so we need to checkout@@ -197,6 +199,11 @@ jobs:- 'rust/bin/migrate-persons'tasks_temporal:- 'products/tasks/backend/temporal/**/*'+ product_yamls:+ # Validates owner team slugs against PostHog/posthog collaborator teams.+ # Costs one GitHub API call; gated here so we only pay it when ownership+ # actually changes. Drives the validate-product-yamls job below.+ - 'products/*/product.yaml'openapi_types:# Generated OpenAPI types - validate they match schema- 'frontend/src/generated/**/*'@@ -561,6 +568,66 @@ jobs:- name: Check product facade enforcement (import-linter)run: lint-imports+ # Validates product.yaml owners against PostHog/posthog collaborator teams.+ # Gated on the product_yamls paths filter so we only spend a GitHub API call+ # when ownership actually changes. The scoped form (positional product names)+ # means a PR can't trip on pre-existing stale ownership in unrelated yamls.+ # Skipped for fork PRs — app-token secrets aren't available there, and forks+ # can't introduce new product.yaml entries that ship to master without a+ # same-repo PR going through this check anyway.+ validate-product-yamls:+ needs: [changes]+ if: >+ needs.changes.outputs.product_yamls == 'true' &&+ github.event_name == 'pull_request' &&+ github.event.pull_request.head.repo.full_name == github.repository+ timeout-minutes: 5+ name: Validate product.yaml owners (ubuntu-latest)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2++ # Default GITHUB_TOKEN can't list /repos/{repo}/teams (needs org-level+ # `members: read`). Reuse the assign-reviewers app — same secret, same+ # use case. `owner: PostHog` scopes the issued token at the org so+ # org-level permissions actually flow through; otherwise the token is+ # repo-scoped and the org scope gets dropped.+ - name: Get app token+ id: app-token+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1+ with:+ client-id: ${{ secrets.GH_APP_POSTHOG_ASSIGN_REVIEWERS_APP_ID }}+ private-key: ${{ secrets.GH_APP_POSTHOG_ASSIGN_REVIEWERS_PRIVATE_KEY }}+ owner: ${{ github.repository_owner }}+ repositories: ${{ github.event.repository.name }}++ - name: Set up Python+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0+ with:+ python-version: 3.12.12++ - name: Install uv+ uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0+ with:+ version: '0.10.2'++ - name: Install Python dependencies+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev++ - name: Validate changed product.yaml owners+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ CHANGED_FILES: ${{ needs.changes.outputs.product_yamls_files }}+ run: |+ # CHANGED_FILES is space-separated (dorny list-files: escape).+ # Each entry is products/<name>/product.yaml — strip to <name>.+ names=$(echo "$CHANGED_FILES" | tr ' ' '\n' | sed -n 's|^products/\([^/]*\)/product.yaml$|\1|p' | xargs)+ if [ -z "$names" ]; then+ echo "No product.yaml files in diff after filtering"+ exit 0+ fi+ ./bin/hogli product:lint:owners $names+# Migration validation.# This job needs Docker + DB — it checks out master first to run baseline# migrations, then checks out the PR branch. OpenAPI type generation belongsdiff --git a/hogli.yaml b/hogli.yamlindex ae365b8472c3..b512f805d64b 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -784,6 +784,9 @@ tools:product:lint:click: hogli_commands.product.cli:cmd_lintdescription: Check product structure for misplaced files+ product:lint:owners:+ click: hogli_commands.product.cli:cmd_lint_owners+ description: Validate product.yaml owners against PostHog/posthog GitHub teamsproduct:maturity:click: hogli_commands.product.cli:cmd_maturitydescription: Score product maturity across isolation dimensionsdiff --git a/products/access_control/product.yaml b/products/access_control/product.yamlindex 1431939bfaa0..f3279a63cd58 100644--- a/products/access_control/product.yaml+++ b/products/access_control/product.yaml@@ -1,3 +1,3 @@name: Access controlowners:- - team-CHANGEME+ - team-platform-featuresdiff --git a/products/business_knowledge/product.yaml b/products/business_knowledge/product.yamlindex 15f862a02353..62c32b9cb827 100644--- a/products/business_knowledge/product.yaml+++ b/products/business_knowledge/product.yaml@@ -1,3 +1,3 @@name: Business knowledgeowners:- - team-conversations+ - conversationsdiff --git a/products/conversations/product.yaml b/products/conversations/product.yamlindex b25ac1795e16..57a279ad4650 100644--- a/products/conversations/product.yaml+++ b/products/conversations/product.yaml@@ -1,3 +1,3 @@name: Conversationsowners:- - team-conversations+ - conversationsdiff --git a/products/core_events/product.yaml b/products/core_events/product.yamlindex 8a26b110a36c..c33dc407ffa7 100644--- a/products/core_events/product.yaml+++ b/products/core_events/product.yaml@@ -1,3 +1,3 @@name: Core eventsowners:- - team-events+ - team-web-analyticsdiff --git a/products/customer_analytics/product.yaml b/products/customer_analytics/product.yamlindex 9dfc11b2a10b..fa08e7886736 100644--- a/products/customer_analytics/product.yaml+++ b/products/customer_analytics/product.yaml@@ -1,3 +1,3 @@name: Customer analyticsowners:- - team-customer-analytics+ - team-web-analyticsdiff --git a/products/revenue_analytics/product.yaml b/products/revenue_analytics/product.yamlindex dc5331fc9aaf..e492c8474c5f 100644--- a/products/revenue_analytics/product.yaml+++ b/products/revenue_analytics/product.yaml@@ -1,3 +1,3 @@name: Revenue analyticsowners:- - team-customer-analytics+ - team-growthdiff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex 595466a30fe3..0f6e16188cd8 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -757,7 +757,18 @@ class ProductYamlCheck(ProductCheck):class ProductYamlOwnersCheck(ProductCheck):- """Validates product.yaml owner slugs against GitHub org teams."""+ """Validates product.yaml owner slugs against GitHub team slugs in the PostHog org.++ Not part of the default CHECKS list — pays a GitHub API call per run, so it's+ only invoked via the dedicated ``product:lint:owners`` subcommand. CI gates+ that subcommand on a ``products/*/product.yaml`` paths filter, so the API+ call only fires when an ownership change is actually proposed.++ Validates "team exists in the org", not "team has access to this repo" — the+ repo-collaborator endpoint needs a permission the assign-reviewers GH App+ lacks. The "exists but lacks repo access" gap is covered by the script's+ 422 fallback (drops bad teams, keeps valid ones).+ """label = "product.yaml owners"@@ -779,10 +790,6 @@ class ProductYamlOwnersCheck(ProductCheck):gh_teams, fetch_err = get_team_slugs()if gh_teams is None:- import os-- if os.environ.get("GITHUB_ACTIONS") == "true":- return CheckResult(lines=[f"⚠ {fetch_err}, skipping in CI"])return CheckResult(lines=[f"✗ {fetch_err}"],issues=[fetch_err],@@ -792,9 +799,22 @@ class ProductYamlOwnersCheck(ProductCheck):result = CheckResult(file=f"products/{ctx.name}/product.yaml")for owner in owners:- if isinstance(owner, str) and owner not in gh_teams:+ if not isinstance(owner, str):+ continue+ # `@username` entries are individual reviewers, not teams — validating+ # them needs a different endpoint, and the assign-reviewers script+ # already routes them separately. Skip here.+ if owner.startswith("@"):+ continue+ if owner == "team-CHANGEME":+ result.issues.append(+ "owner is still the 'team-CHANGEME' scaffold placeholder — pick a real owning team"+ )+ continue+ if owner not in gh_teams:result.issues.append(- f"owner '{owner}' is not a GitHub team in PostHog org — check https://github.com/orgs/PostHog/teams"+ f"owner '{owner}' is not a GitHub team in the PostHog org. "+ f"See https://github.com/orgs/PostHog/teams")if result.issues:@@ -806,7 +826,6 @@ class ProductYamlOwnersCheck(ProductCheck):CHECKS: list[ProductCheck] = [ProductYamlCheck(),- ProductYamlOwnersCheck(),RequiredRootFilesCheck(),PackageJsonScriptsCheck(),MisplacedFilesCheck(),diff --git a/tools/hogli-commands/hogli_commands/product/cli.py b/tools/hogli-commands/hogli_commands/product/cli.pyindex 2b7194f17d13..296a32b84b8e 100644--- a/tools/hogli-commands/hogli_commands/product/cli.py+++ b/tools/hogli-commands/hogli_commands/product/cli.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport click-from .lint import lint_all_products, lint_product+from .lint import lint_all_products, lint_owners, lint_productfrom .maturity import generate_codegen_report, generate_detail, generate_report, score_all_products, score_productfrom .scaffold import bootstrap_product@@ -84,6 +84,17 @@ def cmd_lint(name: str | None, lint_all: bool) -> None:raise SystemExit(1)+ name="product:lint:owners",+ help="Validate product.yaml owners against PostHog/posthog collaborator teams. "+ "Pass product names to limit to those (CI passes the list derived from changed yamls); "+ "no args = sweep every product.",+)[email protected]("names", nargs=-1)+def cmd_lint_owners(names: tuple[str, ...]) -> None:+ lint_owners(list(names))++@click.command(name="product:maturity", help="Score product maturity across isolation dimensions")@click.argument("name", required=False)@click.option("--all", "score_all", is_flag=True, help="Score all products and generate ranked report")diff --git a/tools/hogli-commands/hogli_commands/product/gh.py b/tools/hogli-commands/hogli_commands/product/gh.pyindex 651821295911..5743c4fbaf7c 100644--- a/tools/hogli-commands/hogli_commands/product/gh.py+++ b/tools/hogli-commands/hogli_commands/product/gh.py@@ -2,16 +2,29 @@from __future__ import annotations+import shutil+import subprocess+_team_slugs: set[str] | None = None_fetch_err: str = ""_fetch_attempted: bool = False-def get_team_slugs(org: str = "PostHog") -> tuple[set[str] | None, str]:- """Fetch GitHub team slugs for an org. Cached after first call.+_ORG = "PostHog"+++def get_team_slugs() -> tuple[set[str] | None, str]:+ """Fetch GitHub team slugs visible in the PostHog org. Cached after the first call.- Returns (slugs, error_message). slugs is None when the fetch failed;- error_message explains why.+ Uses ``/orgs/{org}/teams`` (requires ``members: read``) rather than the+ repo-collaborator endpoint ``/repos/{repo}/teams``. The repo endpoint would+ be the tighter check semantically (the reviewer assignment API only accepts+ repo collaborator teams), but the assign-reviewers GitHub App doesn't have+ the scope for it. The "team exists in org but lacks repo access" gap is+ covered defensively by assign-reviewers.js's 422 fallback, which retries+ each team individually and logs the bad slugs.++ Returns ``(slugs, error_message)``. ``slugs`` is ``None`` when the fetch failed."""global _team_slugs, _fetch_err, _fetch_attempted@@ -20,16 +33,13 @@ def get_team_slugs(org: str = "PostHog") -> tuple[set[str] | None, str]:_fetch_attempted = True- import shutil- import subprocess-if not shutil.which("gh"):_fetch_err = "gh CLI not found — install it to validate owner team slugs"return None, _fetch_errtry:result = subprocess.run(- ["gh", "api", f"orgs/{org}/teams", "--paginate", "--jq", ".[].slug"],+ ["gh", "api", f"orgs/{_ORG}/teams", "--paginate", "--jq", ".[].slug"],capture_output=True,text=True,timeout=15,diff --git a/tools/hogli-commands/hogli_commands/product/lint.py b/tools/hogli-commands/hogli_commands/product/lint.pyindex 9044dfda28a8..aa6838725e8b 100644--- a/tools/hogli-commands/hogli_commands/product/lint.py+++ b/tools/hogli-commands/hogli_commands/product/lint.py@@ -3,10 +3,11 @@from __future__ import annotationsimport os+from pathlib import Pathimport click-from .checks import CHECKS, CheckContext, is_isolated_product, validate_tach_toml+from .checks import CHECKS, CheckContext, ProductYamlOwnersCheck, is_isolated_product, validate_tach_tomlfrom .paths import PRODUCTS_DIR, TACH_TOML, load_structure_IN_GH_ACTIONS = os.environ.get("GITHUB_ACTIONS") == "true"@@ -125,3 +126,70 @@ def lint_all_products() -> None:raise SystemExit(1)click.echo(f"✓ All {len(product_dirs)} products passed")+++def lint_owners(names: list[str] | None = None) -> None:+ """Validate product.yaml ``owners:`` against repo-collaborator GitHub teams.++ With ``names`` empty/None, sweeps every product (local convenience). In CI+ the call site passes the list of products whose product.yaml actually+ changed, so pre-existing rot elsewhere doesn't block unrelated PRs.++ Separated from ``lint_all_products`` because it makes a GitHub API call —+ wired into CI behind a paths filter so it only runs when a product.yaml+ changes.+ """+ if names:+ targets: list[Path] = []+ for name in names:+ d = PRODUCTS_DIR / name+ if not d.is_dir():+ click.echo(f"⚠ skipping '{name}': not a product directory")+ continue+ targets.append(d)+ # If the caller passed names but none resolved, treat it as an error —+ # otherwise an unexpected slug from CI's sed/xargs pipeline would slip+ # through as a silent green ("✓ All 0 product owners are valid").+ if not targets:+ click.echo("✗ None of the provided names matched a product directory — nothing validated")+ raise SystemExit(1)+ else:+ targets = sorted(+ d+ for d in PRODUCTS_DIR.iterdir()+ if d.is_dir() and not d.name.startswith((".", "_")) and (d / "__init__.py").exists()+ )++ check = ProductYamlOwnersCheck()+ structure = load_structure()+ failed: list[str] = []++ scope = "all products" if not names else f"{len(targets)} changed product(s)"+ click.echo(f"Validating product.yaml owners across {scope} against PostHog/posthog teams\n")++ for product_dir in targets:+ ctx = CheckContext(+ name=product_dir.name,+ product_dir=product_dir,+ backend_dir=product_dir / "backend",+ is_isolated=is_isolated_product(product_dir / "backend"),+ structure=structure,+ detailed=False,+ )+ result = check.run(ctx)+ if result.skip:+ continue+ if result.issues:+ failed.append(product_dir.name)+ click.echo(f"─ {product_dir.name}")+ for line in result.lines:+ click.echo(f" {line}")+ for issue in result.issues:+ _gh_annotation("error", product_dir.name, check.label, issue, file=result.file)++ click.echo("")+ if failed:+ click.echo(f"✗ {len(failed)} product(s) failed owner validation: {', '.join(failed)}")+ raise SystemExit(1)++ click.echo(f"✓ All {len(targets)} product owners are valid PostHog/posthog teams")diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex daeb07a4311c..8a3666dd1786 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -564,9 +564,8 @@ class TestProductYamlOwnersCheck:result = owners_check.run(ctx)assert not result.issues- def test_gh_unavailable_is_error_locally(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ def test_gh_unavailable_is_error(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n - team-foo\n")- monkeypatch.delenv("GITHUB_ACTIONS", raising=False)monkeypatch.setattr(gh_module, "_fetch_attempted", True)monkeypatch.setattr(gh_module, "_team_slugs", None)monkeypatch.setattr(gh_module, "_fetch_err", "gh CLI not found")@@ -574,15 +573,6 @@ class TestProductYamlOwnersCheck:assert result.issuesassert any("gh CLI" in i for i in result.issues)- def test_gh_unavailable_skips_in_ci(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n - team-foo\n")- monkeypatch.setenv("GITHUB_ACTIONS", "true")- monkeypatch.setattr(gh_module, "_fetch_attempted", True)- monkeypatch.setattr(gh_module, "_team_slugs", None)- monkeypatch.setattr(gh_module, "_fetch_err", "gh CLI not found")- result = owners_check.run(ctx)- assert not result.issues-# ---------------------------------------------------------------------------# FileFolderConflictsCheck — file vs package twin detection