: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(owners): add per-team test file census (#92559)
Raúl Negrón-Oteroeb37bb945810
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.pyindex a71377a8de6f..bd2194c87d49 100644--- a/.github/scripts/report_test_timings.py+++ b/.github/scripts/report_test_timings.py@@ -65,7 +65,7 @@ from opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom opentelemetry.sdk.trace.id_generator import IdGeneratorfrom opentelemetry.trace import Status, StatusCode-from posthog_owners import OwnersResolver+from posthog_owners import OwnersResolver, first_team_ownerlogger = logging.getLogger("report_test_timings")@@ -297,10 +297,14 @@ def normalize_jest_file(file: str, jest_root: str = "frontend") -> str:mangles the path or drops the file as un-normalizable, so the root follows theartifact's suite."""+ return _normalize_repo_file(file, jest_root)+++def _normalize_repo_file(file: str, root: str) -> str:if not file:return ""- normalized = posixpath.normpath(posixpath.join(jest_root, file.replace("\\", "/")))- if normalized == ".." or normalized.startswith("../") or normalized.startswith("/"):+ normalized = posixpath.normpath(posixpath.join(root, file.replace("\\", "/")))+ if normalized == ".." or normalized.startswith(("../", "/")):return ""return normalized@@ -321,12 +325,7 @@ def normalize_pytest_file(file: str) -> str:(``../../../opt/.../unittest/mock.py``). Such a path can never resolve an owner, so it isdiscarded here and the caller falls back to inferring the file from the JUnit classname."""- if not file:- return ""- normalized = posixpath.normpath(file.replace("\\", "/"))- if normalized == ".." or normalized.startswith(("../", "/")):- return ""- return normalized+ return _normalize_repo_file(file, ".")def infer_pytest_file(classname: str) -> str:@@ -824,9 +823,7 @@ def owner_team_lookup() -> Callable[[str], str]:except Exception:logger.exception("owners resolution failed for %s; emitting span without team attribution", file)return ""- # An `@handle` first owner is a person, not a team; stamping it would mint a- # one-person "team" in every per-team rollup.- return next((owner for owner in owners or [] if not owner.startswith("@")), "")+ return first_team_owner(owners)return lookupdiff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.pyindex 5c17265e3133..89429be8f69b 100644--- a/.github/scripts/test_report_test_timings.py+++ b/.github/scripts/test_report_test_timings.py@@ -124,8 +124,7 @@ def test_find_repo_root_walks_to_repository_markers(tmp_path: Path) -> None:"junit_file",["",- # pytest reports the decorator's own file for tests wrapped in mock.patch/freeze_time/- # parameterized; a path escaping the repo must fall back to classname inference.+ # a decorator's site-packages path (see normalize_pytest_file)"../../../../../opt/hostedtoolcache/Python/3.13.13/x64/lib/python3.13/unittest/mock.py",],)diff --git a/hogli.yaml b/hogli.yamlindex d4e4b347f823..588c26ab60d5 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1089,6 +1089,9 @@ owners:owners:who:click: posthog_owners.cli:cmd_whodescription: Show who owns a single path (owners, status, slack, source)+ owners:census:+ click: posthog_owners.cli:cmd_census+ description: Count test files per owning team (optional PREFIX; --json for machine output)owners:unowned:click: posthog_owners.cli:cmd_unowneddescription: List unowned tracked files, respecting owners:null exemptions (optional PREFIX)diff --git a/tools/owners/posthog_owners/__init__.py b/tools/owners/posthog_owners/__init__.pyindex 1b3c8fcaf392..87b89a4ce2e6 100644--- a/tools/owners/posthog_owners/__init__.py+++ b/tools/owners/posthog_owners/__init__.py@@ -1,11 +1,16 @@"""Distributed ownership: owners.yaml matcher, schema, resolver, and CLI."""+from .census import TeamTestCensus, census, first_team_owner, runner_for_pathfrom .matcher import compile_pattern, path_matches_patternfrom .resolver import OwnersResolver, Resolution__all__ = ["OwnersResolver","Resolution",+ "TeamTestCensus",+ "census","compile_pattern",+ "first_team_owner","path_matches_pattern",+ "runner_for_path",]diff --git a/tools/owners/posthog_owners/census.py b/tools/owners/posthog_owners/census.pynew file mode 100644index 000000000000..bb1c0fdc8085--- /dev/null+++ b/tools/owners/posthog_owners/census.py@@ -0,0 +1,71 @@+"""Per-team census of the repo's test files, resolved through the distributed owners.yaml+map. A static read of the tree, so it carries the denominator the signal-only CI spans cannot."""++import re+from collections.abc import Iterable+from dataclasses import dataclass+from pathlib import Path++from .resolver import OwnersResolver++UNOWNED_TEAM = "unowned"++_PYTEST_FILE = re.compile(r"(^|/)test_[^/]*\.py$|_test\.py$")+_JEST_FILE = re.compile(r"\.(test|spec)\.[jt]sx?$")+++def first_team_owner(owners: list[str] | None) -> str:+ """First owner that is a team slug; an ``@handle`` is a person, not a team."""+ return next((owner for owner in owners or [] if not owner.startswith("@")), "")+++def runner_for_path(path: str) -> str | None:+ if _PYTEST_FILE.search(path):+ return "pytest"+ if _JEST_FILE.search(path):+ return "jest"+ return None+++@dataclass(frozen=True, kw_only=True, slots=True)+class TeamTestCensus:+ owner_team: str+ pytest_file_count: int+ jest_file_count: int++ @property+ def test_file_count(self) -> int:+ return self.pytest_file_count + self.jest_file_count++ def as_payload(self) -> dict[str, int | str]:+ """The wire shape shared by ``owners:census --json`` and the census events."""+ return {+ "owner_team": self.owner_team,+ "pytest_file_count": self.pytest_file_count,+ "jest_file_count": self.jest_file_count,+ "test_file_count": self.test_file_count,+ }+++def census(paths: Iterable[str], repo_root: Path) -> list[TeamTestCensus]:+ """Count test files per owning team over repo-relative ``paths``, most tests first.+ Uncovered files and files owned only by ``@handles`` count under ``unowned``."""+ resolver = OwnersResolver(repo_root)+ counts: dict[str, dict[str, int]] = {}+ for path in paths:+ runner = runner_for_path(path)+ if runner is None:+ continue+ team = first_team_owner(resolver.resolve(path).owners) or UNOWNED_TEAM+ counts.setdefault(team, {"pytest": 0, "jest": 0})[runner] += 1+ return sorted(+ (+ TeamTestCensus(+ owner_team=team,+ pytest_file_count=by_runner["pytest"],+ jest_file_count=by_runner["jest"],+ )+ for team, by_runner in counts.items()+ ),+ key=lambda c: (-c.test_file_count, c.owner_team),+ )diff --git a/tools/owners/posthog_owners/cli.py b/tools/owners/posthog_owners/cli.pyindex df4d2c97d016..5b99ebfb5632 100644--- a/tools/owners/posthog_owners/cli.py+++ b/tools/owners/posthog_owners/cli.py@@ -10,6 +10,7 @@ from typing import castimport click+from .census import censusfrom .matcher import compile_pattern, normalize_pathfrom .resolver import OWNERS_FILENAME, PRODUCT_FILENAME, OwnersResolver, Purpose, read_stdin_paths, resolution_to_wirefrom .schema import is_simple_owners_file, normalize_product_owners@@ -61,6 +62,22 @@ def cmd_who(path: str) -> None:click.echo(f"source: {r.source or '(none)'}")[email protected](name="owners:census", help="Count test files per owning team")[email protected]("--json", "as_json", is_flag=True, help="Emit a JSON list of per-team counts")[email protected]("prefix", required=False)+def cmd_census(as_json: bool, prefix: str | None) -> None:+ resolver = OwnersResolver()+ rows = census(resolver.tracked_files(prefix), resolver.repo_root)+ if as_json:+ click.echo(json.dumps([row.as_payload() for row in rows], indent=2))+ return+ for row in rows:+ click.echo(+ f"{row.test_file_count:6d} {row.pytest_file_count:6d} py {row.jest_file_count:6d} js {row.owner_team}"+ )+ click.echo(f"\n{sum(r.test_file_count for r in rows)} test file(s) across {len(rows)} team(s)", err=True)++@click.command(name="owners:unowned", help="List unowned tracked files (respecting owners: null exemptions)")@click.argument("prefix", required=False)def cmd_unowned(prefix: str | None) -> None:@@ -317,6 +334,7 @@ def main() -> None:"""+main.add_command(cmd_census, name="census")main.add_command(cmd_resolve, name="resolve")main.add_command(cmd_who, name="who")main.add_command(cmd_unowned, name="unowned")diff --git a/tools/owners/tests/test_owners.py b/tools/owners/tests/test_owners.pyindex 0886ed5b418a..64ee5dc8dadd 100644--- a/tools/owners/tests/test_owners.py+++ b/tools/owners/tests/test_owners.py@@ -5,7 +5,11 @@ from pathlib import Pathimport pytest-from posthog_owners import fmt as fmt_module+from posthog_owners import (+ census,+ first_team_owner,+ fmt as fmt_module,+)from posthog_owners.cli import _consolidation_suggestions, _live_scope, _reserved_location_errorfrom posthog_owners.fmt import CanonicalPlacer, CanonicalPlanfrom posthog_owners.matcher import path_matches_pattern@@ -674,3 +678,30 @@ def test_live_scope_limits_validation_to_the_given_files(paths: tuple[str, ...],def test_live_scope_ignores_stale_owners_outside_the_diff() -> None:assert "team-bogus" not in _live_scope(_OWNERS_BY_FILE, ("owners.yaml",))+++def test_census_counts_test_files_per_team_and_folds_gaps_into_unowned(tmp_path: Path) -> None:+ _write(tmp_path, "owners.yaml", "version: 1\nowners: []\n")+ _write(tmp_path, "products/a/owners.yaml", "version: 1\nowners: [team-a]\n")+ _write(tmp_path, "products/p/owners.yaml", "version: 1\nowners: ['@someone']\n")+ paths = [+ "products/a/backend/test_api.py",+ "products/a/backend/queries_test.py",+ "products/a/frontend/thing.test.tsx",+ "products/a/frontend/thing.tsx",+ "products/p/backend/test_personal.py",+ "posthog/test_uncovered.py",+ ]++ result = census(paths, tmp_path)++ assert [(c.owner_team, c.pytest_file_count, c.jest_file_count) for c in result] == [+ ("team-a", 2, 1),+ ("unowned", 2, 0),+ ]+++def test_first_team_owner_skips_handles() -> None:+ assert first_team_owner(["@someone", "team-a"]) == "team-a"+ assert first_team_owner(["@someone"]) == ""+ assert first_team_owner(None) == ""