: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(devex): attribute trunk flaky tests through the owners.yaml map (#101204)
Georges-Antoine Assi5d48c3364bfc
diff --git a/.agents/skills/establishing-code-ownership/SKILL.md b/.agents/skills/establishing-code-ownership/SKILL.mdindex 1e7fc4e413e2..73627e74ebf1 100644--- a/.agents/skills/establishing-code-ownership/SKILL.md+++ b/.agents/skills/establishing-code-ownership/SKILL.md@@ -30,6 +30,7 @@ For a path, it walks from the repo root down to the path collecting ownership fi1. **`owners.yaml` — the canonical, distributed source.** Each directory can carry one. Fields (`owners`, `status`, `inherit`, per-path `rules`) fall through to the nearest ancestor unless overridden. `inherit: false` cuts the walk (Gerrit's `set noparent`) — nothing above it contributes. Within a file, `rules:` are last-match-wins. `owners: null` means **unowned by design** (exempt from the coverage check), distinct from a directory with no file at all (genuinely unowned).2. **`products/<name>/product.yaml` — an accepted alias.** When a product dir has no `owners.yaml`, its `product.yaml` `owners:` list is read as the ownership for `products/<name>/**` (every other `product.yaml` field is ignored). A dir with both files is a lint error; `owners.yaml` wins.3. **`.github/CODEOWNERS` — blocking approvals, never part of the walk.** It keeps GitHub-native semantics, stays hand-maintained (mostly infra, e.g. `team-security`), and is enforced by GitHub itself. The resolver does **not** read it — when you need to know whether a blocking approval is additionally required, consult the file directly. It never changes the resolved `owners`, and nothing here writes to it.+ A tool that can only read CODEOWNERS gets a generated projection of the map instead, from `hogli owners:codeowners` (see [tools/owners/README.md](../../../tools/owners/README.md)); that projection covers test files and is never `.github/CODEOWNERS`.Owners are a mixed list of **team slugs** (`team-devex`, `conversations`, `logs` — the GitHub team handle minus `@PostHog/`) and **`@handles`** for individuals; the first entry is the primary owner.diff --git a/.agents/skills/fixing-flaky-tests/SKILL.md b/.agents/skills/fixing-flaky-tests/SKILL.mdindex 215f5a9386c9..a0b0033f91e8 100644--- a/.agents/skills/fixing-flaky-tests/SKILL.md+++ b/.agents/skills/fixing-flaky-tests/SKILL.md@@ -83,6 +83,14 @@ The `trunk` MCP server in `.mcp.json` queries it (tools are marked experimentalAuthenticate once via `/mcp` → `trunk` (browser OAuth); headless environments instead add an `Authorization: Bearer` header with a `TRUNK_API_TOKEN` org token to the server entry.+Two limits worth knowing before you start here.+AI investigations are not enabled for this repo, so `fix-flaky-test` returns history or nothing, never a root cause.+And lookup only goes name to ID: a bare dashboard link identifies a test you cannot name, so ask for the test name rather than guessing at the ID.++Trunk attributes each test to a team through CODEOWNERS, which cannot express the `owners.yaml` map.+`.github/scripts/trunk-codeowners.sh` projects the map into a generated CODEOWNERS before each upload (`hogli owners:codeowners` builds the same file locally), so a test's owner in Trunk should match `hogli owners:who`.+Where it does not, the projection dropped a spelling two teams would both claim.+Like `ci:insights`, this is corroboration and history, not the classification authority — flaky-vs-deterministic and the rate still come from the run data above.## 2. Extract the failure from CIdiff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex eec7ed8fd16f..ef424f8439d5 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -43,7 +43,9 @@# no-ops here and there is nothing to mirror. Canonical's turbo-tests gate now calls# ./.github/actions/trunk-quarantine-gate to retry once. The shadow has no gate, so it# does not need a mirrored action. Canonical pins Trunk CLI 0.15.4 for JUnit retry-# elements; the shadow has no uploader CLI to pin)+# elements; the shadow has no uploader CLI to pin. Canonical also builds a CODEOWNERS+# projection of the owners.yaml map before each upload, so Trunk can attribute a test to+# a team; with no upload here, that step has nothing to mirror either)# - Per-test failure rollup: canonical's django_tests gate uploads product JUnit and, when a# test job fails, downloads that shard's JUnit to list the actual failing tests. The shadow# strips artifact uploads (above), so it has nothing to download and keeps the plaindiff --git a/.github/actions/trunk-quarantine-gate/action.yml b/.github/actions/trunk-quarantine-gate/action.ymlindex cbe1d4da0d44..2afa2219c449 100644--- a/.github/actions/trunk-quarantine-gate/action.yml+++ b/.github/actions/trunk-quarantine-gate/action.yml@@ -19,6 +19,19 @@ inputs:runs:using: 'composite'steps:+ # Exports TRUNK_CODEOWNERS_PATH for the uploader steps below, so Trunk attributes each test+ # to the team that owns its file. Exports nothing when it cannot, which leaves the uploader+ # on .github/CODEOWNERS as before, and the script reads the reports to skip the work for a+ # suite whose reporter writes no file attribute. The existence guard covers a checkout that+ # predates the script, the way an unrebased branch does.+ - name: Build the Trunk ownership map+ shell: bash+ env:+ JUNIT_PATHS: ${{ inputs.junit-paths }}+ run: |+ script="${{ github.action_path }}/../../scripts/trunk-codeowners.sh"+ if [ -x "$script" ]; then "$script" "$RUNNER_TEMP/trunk-codeowners" "$JUNIT_PATHS"; fi+- name: Upload to Trunkid: uploadcontinue-on-error: truediff --git a/.github/scripts/trunk-codeowners.sh b/.github/scripts/trunk-codeowners.shnew file mode 100755index 000000000000..d16d0d0c3b77--- /dev/null+++ b/.github/scripts/trunk-codeowners.sh@@ -0,0 +1,80 @@+#!/usr/bin/env bash+# Write the owners.yaml map into a CODEOWNERS file Trunk can read, and point the uploader at it+# through GITHUB_ENV. Trunk attributes a flaky test to a team by matching the JUnit file attribute+# against a CODEOWNERS file, and .github/CODEOWNERS covers only the paths that need a blocking+# approval, so without this almost every test reaches Trunk unowned.+#+# Best effort by design. Every uploading job runs this, and not all of them have a Python+# environment. On any failure the uploader falls back to .github/CODEOWNERS, which is what it read+# before this existed, so a failed generation costs attribution and never a red check.+set -uo pipefail++output_dir="${1:-}"+junit_paths="${2:-}"+if [ -z "$output_dir" ]; then+ echo "usage: $0 OUTPUT_DIR [JUNIT_PATHS]" >&2+ exit 0+fi++repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+# The file has to carry this name: the uploader takes a directory and looks for CODEOWNERS in it.+target="$output_dir/CODEOWNERS"++# Trunk reads the owner off the file attribute, so a report without one cannot be attributed however+# good the map is. cargo-nextest, playwright and vitest all write the path as `classname` instead,+# which Trunk does not read. Those suites skip the work rather than pay for a map nothing consults.+reports_carry_a_file_attribute() {+ [ -n "$junit_paths" ] || return 0+ local patterns report+ IFS=',' read -r -a patterns <<<"$junit_paths"+ for pattern in "${patterns[@]}"; do+ for report in $pattern; do+ [ -f "$report" ] || continue+ if grep -qE '<test(case|suite)[^>]*[[:space:]]file(path)?="' "$report"; then+ return 0+ fi+ done+ done+ return 1+}++generate() {+ # uv first, because CI images carry uv more often than a python with pyyaml, and --no-project+ # keeps it off this repo's own dependency sync. The entrypoint needs stdlib plus pyyaml only.+ if command -v uv >/dev/null 2>&1; then+ uv run --no-project --with pyyaml python -m posthog_owners --codeowners "$target" && return 0+ fi+ if command -v python3 >/dev/null 2>&1; then+ python3 -m posthog_owners --codeowners "$target" && return 0+ fi+ return 1+}++fall_back() {+ echo "::notice::$1; Trunk falls back to .github/CODEOWNERS for test ownership"+ exit 0+}++if ! reports_carry_a_file_attribute; then+ echo "No JUnit report carries a file attribute, so Trunk cannot attribute these tests; skipping the ownership map"+ exit 0+fi++mkdir -p "$output_dir" || fall_back "Could not create $output_dir"++if ! PYTHONPATH="$repo_root/tools/owners" generate >/dev/null 2>&1; then+ fall_back "Could not generate the Trunk ownership map"+fi++rule_count="$(grep -cvE '^#|^$' "$target" 2>/dev/null || true)"+if [ "${rule_count:-0}" -lt 1 ]; then+ fall_back "The generated Trunk ownership map has no rules"+fi++{+ echo "TRUNK_CODEOWNERS_PATH=$output_dir"+ # Without this the uploader tries the GitLab parser first and only falls back to GitHub's.+ echo "TRUNK_CODEOWNERS_TYPE=github"+} >>"${GITHUB_ENV:-/dev/null}"++echo "Trunk ownership map: $rule_count rule(s) from the owners.yaml tree"diff --git a/.github/scripts/trunk-codeowners.test.sh b/.github/scripts/trunk-codeowners.test.shnew file mode 100755index 000000000000..3b8b81754199--- /dev/null+++ b/.github/scripts/trunk-codeowners.test.sh@@ -0,0 +1,91 @@+#!/usr/bin/env bash+set -euo pipefail++script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/trunk-codeowners.sh"+workdir="$(mktemp -d)"+trap 'rm -rf "$workdir"' EXIT++# The generator itself is covered by tools/owners/tests/test_owners.py. These cases stub the+# interpreter so the script's own contract is deterministic on a runner with no Python.+stub_interpreter() {+ local name="$1" exit_code="$2" body="$3"+ cat >"$stub_dir/$name" <<EOF+#!/usr/bin/env bash+target=""+while [ \$# -gt 0 ]; do+ if [ "\$1" = "--codeowners" ]; then target="\$2"; fi+ shift+done+if [ -n "\$target" ] && [ -n "$body" ]; then printf '%s\n' "$body" >"\$target"; fi+exit $exit_code+EOF+ chmod +x "$stub_dir/$name"+}++# A report whose testcases carry the file attribute, which is what Trunk matches against.+# Two cases, because the attribute's position varies by reporter: pytest writes it after classname+# and name, and a reporter that writes it first must match too.+attributable_report='<testsuite><testcase name="t" file="a/b.test.ts" /><testcase file="c/d.test.ts" name="u" /></testsuite>'+# What cargo-nextest, playwright and vitest write: the path lands in classname, which Trunk ignores.+unattributable_report='<testsuite><testcase name="t" classname="a/b.test.ts" profile="x" /></testsuite>'++run_case() {+ local name="$1" uv_exit="$2" uv_body="$3" python_exit="$4" python_body="$5" expect_env="$6" report="${7:-$attributable_report}"+ stub_dir="$workdir/$name-bin"+ mkdir -p "$stub_dir"+ stub_interpreter uv "$uv_exit" "$uv_body"+ stub_interpreter python3 "$python_exit" "$python_body"++ local out_dir="$workdir/$name-out"+ local env_file="$workdir/$name-env"+ local junit="$workdir/$name-junit.xml"+ : >"$env_file"+ printf '%s\n' "$report" >"$junit"++ set +e+ PATH="$stub_dir:$PATH" GITHUB_ENV="$env_file" bash "$script" "$out_dir" "$junit" >"$workdir/$name.log" 2>&1+ local status=$?+ set -e++ if [ "$status" -ne 0 ]; then+ echo "FAIL: $name exited $status, expected 0"+ cat "$workdir/$name.log"+ exit 1+ fi+ if [ "$expect_env" = "yes" ]; then+ if ! grep -qx "TRUNK_CODEOWNERS_PATH=$out_dir" "$env_file"; then+ echo "FAIL: $name did not export TRUNK_CODEOWNERS_PATH"+ exit 1+ fi+ if ! grep -qx "TRUNK_CODEOWNERS_TYPE=github" "$env_file"; then+ echo "FAIL: $name did not pin the CODEOWNERS parser"+ exit 1+ fi+ if [ ! -s "$out_dir/CODEOWNERS" ]; then+ echo "FAIL: $name did not write \$out_dir/CODEOWNERS"+ exit 1+ fi+ elif [ -s "$env_file" ]; then+ echo "FAIL: $name exported an ownership map it should have fallen back from"+ cat "$env_file"+ exit 1+ fi+ echo "ok: $name"+}++run_case generates-with-uv 0 '/a/ @PostHog/team-a' 1 '' yes+run_case falls-back-to-python3 1 '' 0 '/a/ @PostHog/team-a' yes+run_case falls-back-when-both-fail 1 '' 1 '' no+run_case falls-back-on-a-map-with-no-rules 0 '# only a header' 1 '' no+run_case skips-a-report-with-no-file-attribute 0 '/a/ @PostHog/team-a' 1 '' no "$unattributable_report"++env_file="$workdir/no-args-env"+: >"$env_file"+GITHUB_ENV="$env_file" bash "$script" >/dev/null 2>&1+if [ -s "$env_file" ]; then+ echo "FAIL: no-args exported an ownership map"+ exit 1+fi+echo "ok: no-args"++echo "Trunk ownership map regression cases passed."diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex d34ac5f2959e..2b855f1f3594 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -3687,6 +3687,17 @@ jobs:junit-*.xml!junit-*-retry-failures.xml+ # Exports TRUNK_CODEOWNERS_PATH for the uploads below, so Trunk attributes each test to+ # the team that owns its file. The guard is for an unrebased branch: this job checks out+ # the PR head ref, which may predate the script. Without it the uploader keeps reading+ # .github/CODEOWNERS, as it did before.+ - name: Build the Trunk ownership map+ if: ${{ !cancelled() && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}+ shell: bash+ run: |+ script=.github/scripts/trunk-codeowners.sh+ if [ -x "$script" ]; then "$script" "$RUNNER_TEMP/trunk-codeowners" "junit-*.xml"; fi+# Best-effort Trunk upload (continue-on-error); the "Fail on test failure" step below is# the verdict, so a Trunk outage can't red a passing shard. Internal PRs only (needs the# secret); cli-version pinned, not 'latest' (skips the release redirect).diff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.ymlindex d9ca8ef28e02..0b1dffaf6747 100644--- a/.github/workflows/ci-e2e-playwright.yml+++ b/.github/workflows/ci-e2e-playwright.yml@@ -1090,6 +1090,17 @@ jobs:path: playwright/junit-results.xmlif-no-files-found: ignore+ # Exports TRUNK_CODEOWNERS_PATH for the upload below, so Trunk attributes each test to+ # the team that owns its file. The guard is for an unrebased branch: this job checks out+ # the PR head ref, which may predate the script. Without it the uploader keeps reading+ # .github/CODEOWNERS, as it did before.+ - name: Build the Trunk ownership map+ if: ${{ !cancelled() && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}+ shell: bash+ run: |+ script=.github/scripts/trunk-codeowners.sh+ if [ -x "$script" ]; then "$script" "$RUNNER_TEMP/trunk-codeowners" "playwright/junit-results.xml"; fi+# Best-effort Trunk upload (continue-on-error); the "Fail on Playwright failure" step# below is the verdict, so a Trunk outage can't red a passing job. Internal PRs only# (needs the secret); cli-version pinned, not 'latest' (skips the release redirect).diff --git a/.github/workflows/shellcheck.yml b/.github/workflows/shellcheck.ymlindex ac1cfbd1645e..058009cbe909 100644--- a/.github/workflows/shellcheck.yml+++ b/.github/workflows/shellcheck.yml@@ -44,6 +44,14 @@ jobs:shellcheck .github/scripts/prepare-product-junit-for-trunk.sh .github/scripts/prepare-product-junit-for-trunk.test.shbash .github/scripts/prepare-product-junit-for-trunk.test.sh+ - name: Check Trunk ownership map script+ run: |+ # An open PR that has not rebased onto this commit does not carry these+ # scripts, so the step skips rather than failing before its own tests run.+ [ -f .github/scripts/trunk-codeowners.test.sh ] || exit 0+ shellcheck .github/scripts/trunk-codeowners.sh .github/scripts/trunk-codeowners.test.sh+ bash .github/scripts/trunk-codeowners.test.sh+- name: Check commit-time warning scriptsrun: |# An open PR that has not rebased onto this commit does not carry thesediff --git a/hogli.yaml b/hogli.yamlindex 1141b30858ca..cec8d1918a5a 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1079,6 +1079,9 @@ owners:owners:census:click: posthog_owners.cli:cmd_censusdescription: Count test files per owning team (optional PREFIX; --json for machine output)+ owners:codeowners:+ click: posthog_owners.cli:cmd_codeowners+ description: Emit a CODEOWNERS projection of test-file ownership for tools that only read CODEOWNERS (-o writes a file)owners:unowned:click: posthog_owners.cli:cmd_unowneddescription: List unowned tracked files, respecting owners:null exemptions (optional PREFIX)diff --git a/tools/owners/README.md b/tools/owners/README.mdindex eaab450b07d0..26d9c8e13970 100644--- a/tools/owners/README.md+++ b/tools/owners/README.md@@ -4,6 +4,28 @@ Resolver, linter, and formatter for PostHog's distributed `owners.yaml` ownershiIt walks the `owners.yaml` / `product.yaml` files a repo carries, merges them nearest-file-wins, and answers "who owns this path" as a library or CLI, plus a lint that catches schema errors, dead globs, conflicts, and coverage gaps.The ownership format and resolution semantics are documented in [`docs/internal/ownership-model-proposal.md`](../../docs/internal/ownership-model-proposal.md) and the `establishing-code-ownership` skill.+## CODEOWNERS projection++Some tools read CODEOWNERS and nothing else. `owners:codeowners` projects the map into that format+so they can attribute a file to a team:++```bash+hogli owners:codeowners # to stdout+hogli owners:codeowners -o /tmp/x/CODEOWNERS+```++It covers test files only, because the consumer this exists for (Trunk Flaky Tests) looks up nothing+else. A test file is spelled the way the runner that ran it writes the JUnit `file` attribute, which+is relative to that runner's working directory, so a file can appear under more than one rule. A+spelling two teams would both claim is dropped rather than guessed. An unowned file gets a rule with+no owner after the pattern, which keeps an ancestor rule from claiming it.++This never writes `.github/CODEOWNERS`. That file carries GitHub's blocking-approval semantics, is+hand-maintained, and is not part of the resolver's walk.++CI regenerates the projection per upload in `.github/scripts/trunk-codeowners.sh`, so the consumer+never reads a stale map.+## Use it from another repoThe package is self-contained (stdlib + pyyaml + click), so any repo carrying `owners.yaml` files can run it without vendoring anything:diff --git a/tools/owners/posthog_owners/__init__.py b/tools/owners/posthog_owners/__init__.pyindex 9782504161d0..ffc0ccf4f75e 100644--- a/tools/owners/posthog_owners/__init__.py+++ b/tools/owners/posthog_owners/__init__.py@@ -1,10 +1,12 @@"""Distributed ownership: owners.yaml matcher, schema, resolver, and CLI."""from .census import TeamTestCensus, census, first_team_owner, runner_for_path+from .codeowners import CodeownersProjection, owner_handle, package_dirs_from, project, spellingsfrom .matcher import compile_pattern, path_matches_patternfrom .resolver import DiskSource, OwnershipSource, OwnersResolver, Resolution__all__ = [+ "CodeownersProjection","DiskSource","OwnersResolver","OwnershipSource",@@ -13,6 +15,10 @@ __all__ = ["census","compile_pattern","first_team_owner",+ "owner_handle",+ "package_dirs_from","path_matches_pattern",+ "project","runner_for_path",+ "spellings",]diff --git a/tools/owners/posthog_owners/__main__.py b/tools/owners/posthog_owners/__main__.pyindex f87f165f8001..4103c245a53f 100644--- a/tools/owners/posthog_owners/__main__.py+++ b/tools/owners/posthog_owners/__main__.py@@ -8,6 +8,10 @@ JSON object keyed by normalized path to stdout::``--purpose notifications`` resolves ``slack`` to the team's automation channel(falls back to the people channel); the default is the people channel.+``--codeowners FILE`` switches to the other mode: it ignores the path arguments and writes a+CODEOWNERS projection of every tracked test file's ownership to FILE (``-`` for stdout), for a+consumer that reads CODEOWNERS and cannot read ``owners.yaml``.+``--repo-root`` names the directory holding the ownership files. Without it theresolver locates the repo with ``git rev-parse``, which needs a real worktree; aconsumer that fetched only the ``owners.yaml`` / ``product.yaml`` files into a@@ -27,6 +31,7 @@ import argparsefrom pathlib import Pathfrom typing import cast+from .codeowners import package_dirs_from, projectfrom .matcher import normalize_pathfrom .resolver import DEFAULT_PURPOSE, OwnersResolver, Purpose, read_stdin_paths, resolution_to_wire@@ -39,6 +44,12 @@ def main() -> None:default=None,help="Directory holding the ownership files; default: the enclosing git worktree",)+ parser.add_argument(+ "--codeowners",+ metavar="FILE",+ default=None,+ help="Write a CODEOWNERS projection of test-file ownership to FILE ('-' for stdout) and exit",+ )parser.add_argument("paths", nargs="*")ns = parser.parse_args()# A root that is not a directory reads as a repo with no ownership files, so every path@@ -47,9 +58,18 @@ def main() -> None:if ns.repo_root is not None and not (ns.repo_root and Path(ns.repo_root).is_dir()):parser.error(f"--repo-root {ns.repo_root!r} is not a directory")repo_root = Path(ns.repo_root) if ns.repo_root is not None else None- paths = ns.paths or read_stdin_paths()-resolver = OwnersResolver(repo_root=repo_root, purpose=cast("Purpose", ns.purpose))++ if ns.codeowners:+ tracked = resolver.tracked_files()+ rendered = project(tracked, resolver, package_dirs_from(tracked)).render()+ if ns.codeowners == "-":+ sys.stdout.write(rendered)+ else:+ Path(ns.codeowners).write_text(rendered)+ return++ paths = ns.paths or read_stdin_paths()result = {normalize_path(path): resolution_to_wire(resolver.resolve(path)) for path in paths}json.dump(result, sys.stdout)diff --git a/tools/owners/posthog_owners/cli.py b/tools/owners/posthog_owners/cli.pyindex 5b99ebfb5632..58b78d40df2a 100644--- a/tools/owners/posthog_owners/cli.py+++ b/tools/owners/posthog_owners/cli.py@@ -6,11 +6,13 @@ import sysimport jsonimport subprocessfrom collections import defaultdict+from pathlib import Pathfrom typing import castimport clickfrom .census import census+from .codeowners import package_dirs_from, projectfrom .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@@ -78,6 +80,28 @@ def cmd_census(as_json: bool, prefix: str | None) -> None:click.echo(f"\n{sum(r.test_file_count for r in rows)} test file(s) across {len(rows)} team(s)", err=True)[email protected](name="owners:codeowners", help="Emit a CODEOWNERS projection of test-file ownership")+ "--output",+ "-o",+ type=click.Path(dir_okay=False, writable=True),+ help="Write to this file instead of stdout",+)+def cmd_codeowners(output: str | None) -> None:+ resolver = OwnersResolver()+ tracked = resolver.tracked_files()+ projection = project(tracked, resolver, package_dirs_from(tracked))+ if output:+ Path(output).write_text(projection.render())+ else:+ click.echo(projection.render(), nl=False)+ click.echo(+ f"{len(projection.lines)} rule(s) covering {projection.owned_file_count} test file(s); "+ f"{projection.unowned_file_count} unowned, {len(projection.ambiguous_spellings)} ambiguous spelling(s) dropped",+ 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:@@ -335,6 +359,7 @@ def main() -> None:main.add_command(cmd_census, name="census")+main.add_command(cmd_codeowners, name="codeowners")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/posthog_owners/codeowners.py b/tools/owners/posthog_owners/codeowners.pynew file mode 100644index 000000000000..73c367fe8f91--- /dev/null+++ b/tools/owners/posthog_owners/codeowners.py@@ -0,0 +1,155 @@+"""A CODEOWNERS projection of the distributed owners.yaml map.++Some tools read CODEOWNERS and nothing else. Trunk Flaky Tests is the one this exists for: it+attributes each test to an owner by matching the JUnit ``file`` attribute against a CODEOWNERS file+in the checkout, so the repo's real ownership map is invisible to it.++The projection covers test files only, because that is all a test-attribution consumer looks up, and+it never writes to ``.github/CODEOWNERS``, which carries GitHub's blocking-approval semantics and+stays hand-maintained.+"""++from __future__ import annotations++from collections.abc import Iterable+from dataclasses import dataclass+from posixpath import dirname++from .census import runner_for_path+from .resolver import OwnersResolver++GITHUB_ORG = "PostHog"++# The jest project that runs the product frontends, so their tests are spelled from here and not+# from the product package that holds them.+JEST_PROJECT_DIR = "frontend"+++def owner_handle(owner: str, org: str = GITHUB_ORG) -> str:+ """A CODEOWNERS handle for one owners.yaml owner: a team slug becomes ``@org/slug``,+ an ``@handle`` for an individual is already in CODEOWNERS form."""+ return owner if owner.startswith("@") else f"@{org}/{owner}"+++def _package_relative(path: str, package_dirs: tuple[str, ...]) -> str | None:+ """``path`` as the nearest enclosing Node package would spell it, else None.++ A package under `products/` is excluded: its frontend tests belong to JEST_PROJECT_DIR.+ """+ for directory in package_dirs:+ if path.startswith(f"{directory}/"):+ if directory.startswith("products/"):+ return None+ return path[len(directory) + 1 :]+ return None+++def spellings(path: str, package_dirs: tuple[str, ...] = ()) -> list[str]:+ """Every way a test runner can spell ``path`` in a JUnit ``file`` attribute.++ jest-junit writes the attribute relative to the working directory the suite ran from, which is+ not always the package that holds the file. pytest runs from the repo root, so a Python test+ has one spelling.+ """+ found = [path]+ if runner_for_path(path) != "jest":+ return found+ relative = _package_relative(path, package_dirs)+ if relative is not None:+ found.append(relative)+ if path.startswith("products/") and f"/{JEST_PROJECT_DIR}/" in path:+ found.append(f"../{path}")+ return found+++@dataclass(frozen=True, kw_only=True, slots=True)+class CodeownersProjection:+ """The generated file plus what it does and does not cover."""++ lines: list[str]+ owned_file_count: int+ unowned_file_count: int+ ambiguous_spellings: list[str]++ def render(self) -> str:+ header = [+ "# Generated from the repo's owners.yaml map by `hogli owners:codeowners`. Do not edit.",+ "# Test files only, for tools that attribute a test to a team through CODEOWNERS.",+ "# GitHub reads .github/CODEOWNERS for review assignment, never this file.",+ "",+ ]+ return "\n".join([*header, *self.lines, ""])+++def _rule_depth(pattern: str) -> int:+ return len(pattern.strip("/").split("/"))+++def project(+ paths: Iterable[str],+ resolver: OwnersResolver,+ package_dirs: tuple[str, ...] = (),+ org: str = GITHUB_ORG,+) -> CodeownersProjection:+ """Project the ownership of every test file in ``paths`` into CODEOWNERS rules.++ A spelling that two files with different owners share is dropped rather than guessed, so an+ ambiguous path reaches the consumer unowned instead of wrongly owned.+ """+ owners_by_spelling: dict[str, tuple[str, ...]] = {}+ ambiguous: set[str] = set()+ owned_files = 0+ unowned_files = 0++ for path in paths:+ if runner_for_path(path) is None:+ continue+ owners = resolver.resolve(path).owners+ if owners:+ owned_files += 1+ else:+ unowned_files += 1+ # An unowned file keeps an empty tuple, which renders as a rule with no owner after the+ # pattern. CODEOWNERS reads that as "nobody owns this", so an ancestor rule cannot claim it.+ handles = tuple(owner_handle(owner, org) for owner in owners or ())+ for spelling in spellings(path, package_dirs):+ previous = owners_by_spelling.get(spelling)+ if previous is not None and previous != handles:+ ambiguous.add(spelling)+ owners_by_spelling[spelling] = handles++ # Unowned rather than absent, for the same reason: dropping the entry would leave a directory+ # rule free to claim the very spelling that is too ambiguous to attribute.+ for spelling in ambiguous:+ owners_by_spelling[spelling] = ()++ by_directory: dict[str, dict[tuple[str, ...], list[str]]] = {}+ for spelling, handles in owners_by_spelling.items():+ by_directory.setdefault(dirname(spelling), {}).setdefault(handles, []).append(spelling)++ # CODEOWNERS is last-match-wins, so sorting deeper rules later is what makes a directory rule+ # safe: every subdirectory that resolves elsewhere emits its own rule after it.+ rules: list[tuple[str, tuple[str, ...]]] = []+ for directory, groups in by_directory.items():+ if len(groups) == 1 and directory:+ [(handles, _)] = groups.items()+ rules.append((f"/{directory}/", handles))+ continue+ for handles, group in groups.items():+ rules.extend((f"/{spelling}", handles) for spelling in group)++ rules.sort(key=lambda rule: (_rule_depth(rule[0]), rule[0]))+ return CodeownersProjection(+ lines=[" ".join([pattern, *handles]) for pattern, handles in rules],+ owned_file_count=owned_files,+ unowned_file_count=unowned_files,+ ambiguous_spellings=sorted(ambiguous),+ )+++def package_dirs_from(paths: Iterable[str]) -> tuple[str, ...]:+ """Directories holding a package.json, which are the working directories a Node suite runs from,+ nearest first. The repo root is excluded because a path relative to it is already the+ repo-relative spelling."""+ directories = {dirname(path) for path in paths if path.endswith("package.json") and dirname(path)}+ return tuple(sorted(directories, key=len, reverse=True))diff --git a/tools/owners/tests/test_owners.py b/tools/owners/tests/test_owners.pyindex 08869c767584..5ad11e10e3b1 100644--- a/tools/owners/tests/test_owners.py+++ b/tools/owners/tests/test_owners.py@@ -11,6 +11,11 @@ from posthog_owners import (census,first_team_owner,fmt as fmt_module,+ owner_handle,+ package_dirs_from,+ project,+ runner_for_path,+ spellings,)from posthog_owners.cli import _consolidation_suggestions, _live_scope, _reserved_location_errorfrom posthog_owners.fmt import CanonicalPlacer, CanonicalPlan@@ -839,3 +844,96 @@ def test_json_entrypoint_rejects_a_repo_root_that_is_not_a_directory(registry_reassert result.returncode == 2assert "--repo-root" in result.stderrassert result.stdout == ""+++def _codeowners_lookup(rendered: str, path: str) -> list[str]:+ # The projection emits two rule shapes only: an exact file path, and a directory prefix ending+ # in "/". Last match wins, which is what CODEOWNERS consumers implement.+ owners: list[str] = []+ for line in rendered.splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ pattern, *rule_owners = line.split()+ pattern = pattern.lstrip("/")+ if pattern.endswith("/") and path.startswith(pattern):+ owners = rule_owners+ elif path == pattern:+ owners = rule_owners+ return owners+++def projection_repo(tmp_path: Path) -> Path:+ _write(tmp_path, "owners.yaml", "version: 1\nowners: []\n")+ _write(tmp_path, "posthog/security/owners.yaml", "version: 1\nowners: [team-security]\n")+ _write(tmp_path, "posthog/security/test/owners.yaml", "version: 1\nowners: null\n")+ _write(tmp_path, "products/alpha/owners.yaml", "version: 1\nowners: [team-alpha, '@someone']\n")+ _write(tmp_path, "products/beta/owners.yaml", "version: 1\nowners: [team-beta]\n")+ _write(tmp_path, "frontend/owners.yaml", "version: 1\nowners: [team-web]\n")+ _write(tmp_path, "nodejs/owners.yaml", "version: 1\nowners: [team-pipeline]\n")+ return tmp_path+++ "path,expected",+ [+ ("posthog/api/test_thing.py", ["posthog/api/test_thing.py"]),+ ("frontend/src/a.test.tsx", ["frontend/src/a.test.tsx", "src/a.test.tsx"]),+ (+ "products/alpha/frontend/a.test.tsx",+ ["products/alpha/frontend/a.test.tsx", "../products/alpha/frontend/a.test.tsx"],+ ),+ ],+ ids=["pytest-runs-from-the-repo-root", "jest-runs-from-its-package", "product-frontends-run-from-frontend"],+)+def test_spellings_cover_how_each_runner_writes_the_file_attribute(path: str, expected: list[str]) -> None:+ assert spellings(path, package_dirs_from(["frontend/package.json", "products/alpha/package.json"])) == expected+++def test_projection_resolves_every_spelling_to_what_the_resolver_says(projection_repo: Path) -> None:+ tracked = [+ "frontend/package.json",+ "products/alpha/package.json",+ "frontend/src/a.test.tsx",+ "posthog/security/test_sanitization.py",+ "posthog/security/test/test_proxy.py",+ "products/alpha/frontend/widget.test.tsx",+ "products/alpha/backend/test_api.py",+ "products/beta/backend/test_api.py",+ "products/beta/backend/api.py",+ ]+ resolver = OwnersResolver(projection_repo)++ projection = project(tracked, resolver, package_dirs_from(tracked))+ rendered = projection.render()++ for path in tracked:+ if runner_for_path(path) is None:+ continue+ expected = [owner_handle(owner) for owner in resolver.resolve(path).owners or []]+ for spelling in spellings(path, package_dirs_from(tracked)):+ assert _codeowners_lookup(rendered, spelling) == expected, f"{spelling} resolved wrongly"+ assert projection.owned_file_count == 5+ assert projection.unowned_file_count == 1+++def test_projection_drops_a_spelling_two_teams_would_both_claim(projection_repo: Path) -> None:+ tracked = [+ "frontend/package.json",+ "nodejs/package.json",+ "frontend/src/shared.test.ts",+ "nodejs/src/shared.test.ts",+ # A sibling that leaves one owner in the directory, so a rule for the directory would+ # otherwise claim the ambiguous spelling next to it.+ "frontend/src/solo.test.ts",+ ]++ projection = project(tracked, OwnersResolver(projection_repo), package_dirs_from(tracked))+ rendered = projection.render()++ assert projection.ambiguous_spellings == ["src/shared.test.ts"]+ assert _codeowners_lookup(rendered, "src/shared.test.ts") == []+ assert _codeowners_lookup(rendered, "src/solo.test.ts") == ["@PostHog/team-web"]+ assert _codeowners_lookup(rendered, "frontend/src/shared.test.ts") == ["@PostHog/team-web"]+ assert _codeowners_lookup(rendered, "nodejs/src/shared.test.ts") == ["@PostHog/team-pipeline"]