Skip to content

: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.

feat(eng-analytics): attribute quarantine debt from repo ownership (#91758)

Raúl Negrón-Oteroa373c8317d1c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3335d280cf74..e5777e99df0a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6644,6 +6644,10 @@ snapshots:
hash: v1.k794b7964.1bf2a96d4a8f8875fc554a67e7e7b28adc98b144607babe0ae8342de5a0f3edc.JM5CCK4syW_o4_XReB3Nn6NUpB0I643u2a05XZmoeck
scenes-app-engineering-analytics-test-health--trunk-quarantine-debt--light:
hash: v1.k794b7964.1f330c8921d0151e1a846cf3cdccd6cd8196fd012630780b3a20491cc5ff293f.oEUS4LgdANupAGuZ7t8vmArgxuzi4IBEIJIlWHFXOAw
+ scenes-app-engineering-analytics-test-health--trunk-quarantine-debt-owners-unavailable--dark:
+ hash: v1.k794b7964.322bfce5ccced64987eb75406fa77e8a2ad80575597378810b984986f9fede0f.EwXIJ9x_Rc-dgkCVJJZBQM1W3voRSFtgHX95x8GbYIE
+ scenes-app-engineering-analytics-test-health--trunk-quarantine-debt-owners-unavailable--light:
+ hash: v1.k794b7964.8916de545edf558f799cc98ee4a901c19ba00fe7d0bb4f5312266705755e3e70.EO6V5mC_JCbSh5ZRrmyU09RT-hFV9f4Mtu_JkZ9m5Ng
scenes-app-error-project-unavailable--access-revoked--dark:
hash: v1.k794b7964.30ace8f015100159e1dedbed07ff9f0b0b770535870d5c98ea764b10ff1f7621.dTVw9qLa7D_e7ZNme4tVuPZov-0Gg1o84aiDl5zihF0
scenes-app-error-project-unavailable--access-revoked--light:
diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.md
index 142eafcf6c18..a574f96ab50f 100644
--- a/products/engineering_analytics/README.md
+++ b/products/engineering_analytics/README.md
@@ -82,7 +82,7 @@ graph LR
- Job-level CI: per-job duration, queue time, runner tier, and dollar cost ride `workflow_jobs` (webhook stream plus bounded backfill).
- One write surface: test quarantine. The `quarantine/request` endpoint files a tracking issue plus a PR against the repo's checked-in `.test_quarantine.json` through the team's GitHub App; it is reachable via the API and MCP only, with no in-app UI. Everything else is read-only.
-- The test-health view is the Trunk quarantine debt scoreboard: every test Trunk currently quarantines, attributed to its owning team from the span-stamped ownership, aged against a TTL, and rolled up per team. A quarantine masks a failure without fixing it, so the board is the standing work queue of masked tests. The flaky-test queue itself (failures plus same-commit recovery evidence from the pytest and Jest suites, counted per CI run, ranked by blast radius) remains an endpoint and MCP tool; the weekly Slack report requests each runner separately and shows up to 10 pytest tests followed by up to 10 Jest tests; it is informational, so suppressed tests stay listed with their quarantine state. Logs-based rescue counts and links remain pytest-only.
+- The test-health view is the Trunk quarantine debt scoreboard: every test Trunk currently quarantines, attributed to the team that owns its file in the repository today, aged against a TTL, and rolled up per team. A quarantine masks a failure without fixing it, so the board is the standing work queue of masked tests. The flaky-test queue itself (failures plus same-commit recovery evidence from the pytest and Jest suites, counted per CI run, ranked by blast radius) remains an endpoint and MCP tool; the weekly Slack report requests each runner separately and shows up to 10 pytest tests followed by up to 10 Jest tests; it is informational, so suppressed tests stay listed with their quarantine state. Logs-based rescue counts and links remain pytest-only.
- Access control: per-user warehouse RBAC at the source resolver, `engineering_analytics:read` scopes on tools, feature-flag gated.
## The goal: CI Signals for PostHog Desktop
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 93c0b71733f7..0a049628d8fe 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -158,7 +158,8 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **Bot detection, defined once:** `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist; per-team config deferred.
- **Bots and drafts excluded by default** in throughput / cycle-time reads; first-class in bot-impact analysis, so never strip them at the substrate.
- **Time to merge** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (draft + ready combined). The precise companion is `ready_to_merge_seconds` = `merged_at` minus the last observed `ready_for_review` issue event (only the last draft/ready switch counts; a draft can't merge), falling back to `created_at` for a merged PR verifiably never drafted (no transition rows and its whole open-to-merge span inside the observed issue-event window, so the transitions can't merely be unsynced). NULL means "not observed", never zero: GitHub caps the issue-events history walk, so coverage grows forward from the first sync.
-- **Team ownership is stamped at CI emission time, never mirrored server-side.** The CI emitter stamps `test.owner_team` through `posthog_owners` (the repo's distributed `owners.yaml` files, with `products/*/product.yaml` as an alias; first listed team owner, individual `@handle` owners skipped); unstamped spans aggregate as the first-class team `unowned`. Capture-time truth is intentional: a test belongs to whoever owned it when it flaked. Team surfaces stay team-level: author→team joins (via the `team_members` snapshot) produce aggregates only, never per-member figures or cross-team rankings; a slug mismatch yields an empty series, never another team's data.
+- **Flake ownership is stamped at CI emission time, never mirrored server-side.** The CI emitter stamps `test.owner_team` through `posthog_owners` (the repo's distributed `owners.yaml` files, with `products/*/product.yaml` as an alias; first listed team owner, individual `@handle` owners skipped); unstamped spans aggregate as the first-class team `unowned`. Capture-time truth is intentional: a test belongs to whoever owned it when it flaked.
+- **Quarantine debt ownership is resolved from the repository as it stands**, by the same resolver over the ownership files fetched from the default branch. A deliberate split from the rule above: a quarantine outlives the CI signal that would name a team, so reading standing debt off the stamps attributes most of it to nobody. A test the repository cannot place, or whose path no team claims, is `unowned`; a failed read leaves the whole board `unowned` and says so through `owners_resolved`, rather than attributing part of it. Trunk's own `codeowners` field is not the shortcut it looks like: it is empty for all but a handful of tests, because this repo keeps CODEOWNERS deliberately sparse. Team surfaces stay team-level: author→team joins (via the `team_members` snapshot) produce aggregates only, never per-member figures or cross-team rankings; a slug mismatch yields an empty series, never another team's data.
- **The test-count denominator is a daily census event, never derived from spans.** Spans are signal-only (sub-threshold passes are not emitted), so a Celery task fetches each connected repo's tarball once a day, resolves every test file through `posthog_owners`, and captures one `eng_analytics_test_census` event per owning team into the team's own project. The roster joins census and merged-PR context by slug and adds census-only rows (zero signal, null `last_seen_at`) so an all-green team stays visible.
- **No provider abstraction until a second code host lands.** GitHub-isms stay below the builder boundary, canonical types above it; that seam makes extracting a `CodeHostProvider` Protocol mechanical.
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 37aaf93e33b2..d6161416e44c 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -628,14 +628,17 @@ class FlakyTestList:
# expires a quarantine, so this deadline is the product's own accountability bar.
TRUNK_QUARANTINE_TTL_DAYS = 15
+# The first-class team every unattributed test aggregates under, on every surface here.
+UNOWNED_TEAM = "unowned"
+
@dataclass(frozen=True)
class TrunkQuarantinedTest:
"""One test Trunk currently quarantines, aged against ``TRUNK_QUARANTINE_TTL_DAYS``.
- Rows come from the synced TrunkIo ``QuarantinedTests`` warehouse table. Ownership rides the
- per-test CI spans (the emitter stamps ``test.owner_team``); a quarantined test with no
- in-retention span aggregates under ``'unowned'``.
+ Rows come from the synced TrunkIo ``QuarantinedTests`` warehouse table. Ownership is the
+ repository's own, resolved from ``owners.yaml`` / ``product.yaml`` for the test's file: a test
+ the repository does not place, or whose path no team claims, aggregates under ``'unowned'``.
"""
# Runner label derived from Trunk's uploader-specific 'parent' field: 'pytest', 'jest',
@@ -644,6 +647,7 @@ class TrunkQuarantinedTest:
runner: str
# Runner-native test id reconstructed from Trunk's (file, classname, name) key.
nodeid: str
+ # Repo-relative path of the test's file, empty when neither the repository nor Trunk places it.
file: str
owner_team: str
# Trunk's health verdict on the test, e.g. 'FLAKY' or 'BROKEN'.
@@ -674,6 +678,9 @@ class TrunkQuarantineDebt:
no TrunkIo source has the QuarantinedTests endpoint synced — that is not an error."""
available: bool
+ # False when the repository's ownership files could not be read, which leaves every test
+ # 'unowned'. A board that says so beats one that reads as "nobody owns this debt".
+ owners_resolved: bool
ttl_days: int
# The 'owner/name' repository the debt was read for; test file paths are relative to it.
repository: str
diff --git a/products/engineering_analytics/backend/logic/ownership.py b/products/engineering_analytics/backend/logic/ownership.py
new file mode 100644
index 000000000000..2f7d4e7904ba
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/ownership.py
@@ -0,0 +1,287 @@
+"""Team ownership for a test, resolved from the repository's own ownership files.
+
+Quarantine debt asks who owes the fix now, so it resolves against the repo as it stands rather than
+the capture-time span stamp the flaky rollups keep (SPEC). The web container has no checkout, so the
+files are fetched and cached.
+"""
+
+import random
+from collections.abc import Callable, Iterable
+from concurrent.futures import ThreadPoolExecutor
+from http import HTTPStatus
+from time import monotonic
+from typing import Any, Protocol, TypeVar
+
+from django.core.cache import cache
+
+import requests
+import structlog
+from posthog_owners import OwnershipSource, OwnersResolver
+from posthog_owners.matcher import normalize_path
+from requests.adapters import HTTPAdapter
+
+from posthog.dataclasses import frozen
+from posthog.egress.github.transport import github_request
+from posthog.models.integration.github import _is_safe_github_repo_path
+
+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
+
+logger = structlog.get_logger(__name__)
+
+_T = TypeVar("_T")
+
+# The raw host serves a public repo's files off a CDN, so these reads draw on no GitHub API rate
+# limit, and the HEAD ref follows the default branch. A private repo answers 404 to all of it, which
+# the root-file guard in _place catches.
+_RAW_HOST = "https://raw.githubusercontent.com"
+_REF = "HEAD"
+_EGRESS_SOURCE = "engineering_analytics_ownership"
+# Egress metrics are labeled by endpoint, so a raw file path per label would be unbounded.
+_EGRESS_ENDPOINT = "/{owner}/{repo}/{ref}/{path}"
+_TIMEOUT_SECONDS = 5.0
+_FETCH_WORKERS = 16
+# A connected repository controls these files, so an unbounded read would put its bytes in a
+# worker's memory and in Redis. An ownership file is a few KB; this repo's whole set is under 25 KB.
+_MAX_FILE_BYTES = 1024 * 1024
+# The whole resolution, not one request. A quarantine snapshot is capped at HogQL's implicit 100
+# rows, so a cold board can ask for hundreds of files; if the raw host stalls, the per-request
+# timeout alone would still let one board load hold a web worker for minutes. Past this the board
+# says ownership is unavailable, which beats hanging.
+_RESOLVE_BUDGET_SECONDS = 20.0
+
+# Ownership files change at review speed, so a stale answer stays right, and only the request that
+# finds the cache cold pays for the fetches. A batch writes every key at once, so the jitter spreads
+# their expiry over later requests instead of stranding one with the whole refetch.
+_CACHE_TTL_SECONDS = 6 * 60 * 60
+_CACHE_TTL_JITTER_SECONDS = 60 * 60
+_CACHE_PREFIX = "eng_analytics:repo_file"
+# Absence needs a cache value of its own, and no file holds this one.
+_ABSENT = "\x00absent"
+
+_ROOT_OWNERS_FILE = "owners.yaml"
+
+# Directories a TypeScript suite can run from, so its tests arrive named relative to one of these.
+# Keep in step with jest_root_for_suite in .github/scripts/report_test_timings.py, which stamps the
+# same repositioning onto the CI spans.
+_SUITE_ROOTS = ("nodejs/", "frontend/", "services/mcp/", "common/replay-shared/")
+
+
+class OwnershipUnavailable(Exception):
+ """The repository's ownership files could not be read, so no attribution is trustworthy."""
+
+
+class RepoFiles(OwnershipSource, Protocol):
+ """An ownership source that also answers which paths the repository holds, in batches."""
+
+ def exists_all(self, paths: list[str]) -> dict[str, bool]: ...
+
+ def read_all(self, paths: list[str]) -> None: ...
+
+
+class GitHubRepoFiles:
+ """A public repository's files over HTTPS, cached in Redis. Build one per batch: it holds the
+ batch's memo and its HTTP connections."""
+
+ def __init__(self, repository: str) -> None:
+ self.repository = repository
+ # Raw cache values, so ``_ABSENT`` rather than None for a file the repository does not hold.
+ # The resolver reads each file again after the batch fetched it, and Redis is a network hop too.
+ self._bodies: dict[str, str] = {}
+ self._session = requests.Session()
+ # requests pools 10 connections by default and discards the overflow, so a smaller pool than
+ # the worker count makes most of the batch pay a fresh TLS handshake.
+ self._session.mount(_RAW_HOST, HTTPAdapter(pool_connections=_FETCH_WORKERS, pool_maxsize=_FETCH_WORKERS))
+ self._deadline = monotonic() + _RESOLVE_BUDGET_SECONDS
+
+ def read(self, path: str) -> str | None:
+ if path not in self._bodies:
+ self.read_all([path])
+ return None if self._bodies[path] == _ABSENT else self._bodies[path]
+
+ def read_all(self, paths: list[str]) -> None:
+ """Take every file the batch needs before it reads any, so one Redis round trip and one
+ concurrent fetch cover them all."""
+ self._bodies.update(self._batch("text", [p for p in paths if p not in self._bodies], self._get))
+
+ def exists_all(self, paths: list[str]) -> dict[str, bool]:
+ return self._batch("exists", paths, self._head)
+
+ def _batch(self, kind: str, paths: Iterable[str], fetch: Callable[[str], _T]) -> dict[str, _T]:
+ todo = list(dict.fromkeys(paths))
+ if not todo:
+ return {}
+ by_key = {self._key(kind, path): path for path in todo}
+ known = {by_key[key]: value for key, value in cache.get_many(list(by_key)).items()}
+ fetched = _fetch_all(fetch, [path for path in todo if path not in known], self._deadline)
+ if fetched:
+ cache.set_many({self._key(kind, path): value for path, value in fetched.items()}, _ttl())
+ known.update(fetched)
+ return known
+
+ def _key(self, kind: str, path: str) -> str:
+ return f"{_CACHE_PREFIX}:{kind}:{self.repository}:{_REF}:{path}"
+
+ def _get(self, path: str) -> str:
+ """The file's text, or ``_ABSENT`` when the repository has no such file."""
+ with self._response("GET", path, stream=True) as response:
+ if response.status_code == HTTPStatus.NOT_FOUND:
+ return _ABSENT
+ return self._capped_text(response, path)
+
+ def _head(self, path: str) -> bool:
+ with self._response("HEAD", path) as response:
+ return response.status_code != HTTPStatus.NOT_FOUND
+
+ def _response(self, method: str, path: str, **kwargs: Any) -> requests.Response:
+ """Any status but 200 or 404 raises rather than reading as absent, because a missing
+ ownership file silently reattributes everything under it to an ancestor."""
+ if not _is_safe_github_repo_path(self.repository):
+ # Source config is team-writable, so a crafted value must not steer the URL.
+ raise OwnershipUnavailable(f"unsafe repository path: {self.repository!r}")
+ url = f"{_RAW_HOST}/{self.repository}/{_REF}/{path}"
+ try:
+ response = github_request(
+ method,
+ url,
+ source=_EGRESS_SOURCE,
+ endpoint=_EGRESS_ENDPOINT,
+ timeout=_TIMEOUT_SECONDS,
+ session=self._session,
+ **kwargs,
+ )
+ except Exception as e:
+ raise OwnershipUnavailable(f"could not read {path} from {self.repository}: {e}") from e
+ if response.status_code not in (HTTPStatus.OK, HTTPStatus.NOT_FOUND):
+ raise OwnershipUnavailable(f"{self.repository} answered {response.status_code} for {path}")
+ return response
+
+ def _capped_text(self, response: requests.Response, path: str) -> str:
+ too_large = f"{path} in {self.repository} exceeds the {_MAX_FILE_BYTES}-byte limit"
+ # Content-Length can be absent or wrong, so the streamed read below is the actual ceiling.
+ declared = response.headers.get("Content-Length")
+ if declared is not None and declared.isdigit() and int(declared) > _MAX_FILE_BYTES:
+ raise OwnershipUnavailable(too_large)
+ body = bytearray()
+ for chunk in response.iter_content(chunk_size=8192):
+ body.extend(chunk)
+ if len(body) > _MAX_FILE_BYTES:
+ raise OwnershipUnavailable(too_large)
+ return body.decode(response.encoding or "utf-8", errors="replace")
+
+
+@frozen
+class QuarantinedTestFile:
+ """Where the quarantine snapshot says a test lives: a path as its suite reported it, or, for a
+ Rust test, only the crate."""
+
+ source_path: str
+ crate: str
+
+
+@frozen
+class PlacedTest:
+ path: str
+ owner_team: str
+
+
+UNPLACED = PlacedTest(path="", owner_team=UNOWNED_TEAM)
+
+
+@frozen
+class RepoOwnershipResult:
+ """One placement per test. Everything is unowned whether the read failed or no team claims the
+ paths, so only ``resolved`` separates a real finding from a blind board."""
+
+ tests: list[PlacedTest]
+ resolved: bool
+
+
+def resolve_test_ownership(
+ repository: str, tests: list[QuarantinedTestFile], files: RepoFiles | None = None
+) -> RepoOwnershipResult:
+ """Place every test in the repository and name the team that owns it."""
+ reader = files if files is not None else GitHubRepoFiles(repository)
+ try:
+ return RepoOwnershipResult(tests=_place(repository, reader, tests), resolved=True)
+ except OwnershipUnavailable:
+ # One unreadable file makes every later answer suspect too, so the batch fails together
+ # rather than attributing part of it.
+ logger.exception("repo_ownership_unavailable", repository=repository)
+ return RepoOwnershipResult(tests=[UNPLACED] * len(tests), resolved=False)
+
+
+def _place(repository: str, files: RepoFiles, tests: list[QuarantinedTestFile]) -> list[PlacedTest]:
+ if files.read(_ROOT_OWNERS_FILE) is None:
+ # Every repo this runs against declares one, so its absence proves the reader is blind
+ # (a private or renamed repo answers 404 to everything), not that nobody owns anything.
+ raise OwnershipUnavailable(f"{repository} has no root {_ROOT_OWNERS_FILE}")
+ resolver = OwnersResolver(source=files)
+ candidates = [_candidate_paths(test) for test in tests]
+ present = files.exists_all([path for group in candidates for path in group])
+ placed = [next((path for path in group if present[path]), None) for group in candidates]
+ found = [path for path in placed if path]
+ files.read_all(resolver.ownership_file_paths(found))
+ owners = resolver.map(found)
+ return [
+ PlacedTest(
+ # A Rust crate is placed by its manifest, which is not the test's file.
+ path="" if path is None or test.crate else path,
+ owner_team=_team(owners[path].owners if path else None),
+ )
+ for test, path in zip(tests, placed, strict=True)
+ ]
+
+
+def _ttl() -> int:
+ return _CACHE_TTL_SECONDS + random.randint(0, _CACHE_TTL_JITTER_SECONDS)
+
+
+def _team(owners: list[str] | None) -> str:
+ """An '@handle' owner is a person, and every surface downstream keys on a team slug."""
+ return next((owner for owner in owners or [] if not owner.startswith("@")), UNOWNED_TEAM)
+
+
+def _fetch_all(fetch: Callable[[str], _T], paths: Iterable[str], deadline: float) -> dict[str, _T]:
+ """Fetch every distinct path concurrently, within what is left of the batch's budget. The one
+ place this module waits on the network."""
+ todo = list(dict.fromkeys(paths))
+ if not todo:
+ return {}
+ with ThreadPoolExecutor(max_workers=min(_FETCH_WORKERS, len(todo))) as pool:
+ futures = {path: pool.submit(fetch, path) for path in todo}
+ try:
+ return {path: future.result(max(deadline - monotonic(), 0)) for path, future in futures.items()}
+ except TimeoutError as e:
+ pool.shutdown(cancel_futures=True)
+ raise OwnershipUnavailable(f"ownership took longer than {_RESOLVE_BUDGET_SECONDS}s") from e
+ except Exception:
+ # The batch is already lost, so drop the rest instead of holding the request thread.
+ pool.shutdown(cancel_futures=True)
+ raise
+
+
+def _candidate_paths(test: QuarantinedTestFile) -> list[str]:
+ """Paths that could decide the test's ownership, most specific first. The repository decides
+ which one holds the file.
+
+ Cargo names a crate, nextest reports that name, and the directory holding it need not match:
+ `common-kafka` lives at rust/common/kafka.
+ """
+ if test.crate:
+ return [
+ f"rust/{test.crate}/Cargo.toml",
+ f"rust/common/{test.crate.removeprefix('common-')}/Cargo.toml",
+ f"{test.crate}/Cargo.toml",
+ ]
+ reported = _strip_relative_prefix(normalize_path(test.source_path))
+ if "/" not in reported:
+ return [] # a suite name ('pytest', a jest project), not a file
+ if reported.endswith(".py"):
+ return [reported] # pytest runs from the repo root, and every suite root holds TypeScript
+ return [reported, *(f"{root}{reported}" for root in _SUITE_ROOTS)]
+
+
+def _strip_relative_prefix(path: str) -> str:
+ while path.startswith("../"):
+ path = path.partition("/")[2]
+ return path
diff --git a/products/engineering_analytics/backend/logic/queries/_test_spans.py b/products/engineering_analytics/backend/logic/queries/_test_spans.py
index f51284e6a1b4..8821cac25ade 100644
--- a/products/engineering_analytics/backend/logic/queries/_test_spans.py
+++ b/products/engineering_analytics/backend/logic/queries/_test_spans.py
@@ -29,6 +29,7 @@ from datetime import datetime
from posthog.hogql import ast
+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
from products.engineering_analytics.backend.logic.merge_queue import source_pr_string_expr
# On a merge-queue gate run the emitter stamps ``ci.pr_number`` from the webhook payload, which names
@@ -51,9 +52,6 @@ PYTEST_CI_SERVICE_NAME = "ci-backend"
JEST_CI_SERVICE_NAME = "ci-frontend"
CI_SERVICE_NAMES = [PYTEST_CI_SERVICE_NAME, JEST_CI_SERVICE_NAME]
-# Spans emitted before the owner stamp existed (or from paths with no owner) group here.
-UNOWNED_TEAM = "unowned"
-
_RUN_EVIDENCE = """
SELECT
diff --git a/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py b/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py
index b5b7ada8cd0c..e8ec2677a300 100644
--- a/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py
+++ b/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py
@@ -1,57 +1,27 @@
"""The standing Trunk quarantine debt, attributed to owning teams.
-Two substrates, joined in Python because they live on different clusters: the quarantined set from
-the synced TrunkIo ``QuarantinedTests`` warehouse table, and ownership from the per-test CI spans
-on the LOGS cluster (the emitter stamps ``test.owner_team``; SPEC locks ownership to that stamp,
-never a server-side map). A quarantined test with no in-retention span lands under ``'unowned'``.
-
-Trunk keys a test by (file, classname, name); the curated builder reconstructs the runner-native
-nodeid from that key, and the span side reports the same id as the span name — but each side can
-carry a longer path prefix (product suites run from their product dir), so the join matches on
-path suffixes rather than exact equality.
+The quarantined set comes from the synced TrunkIo ``QuarantinedTests`` warehouse table; ownership
+from the repository's own files (``logic.ownership``), because a quarantine outlives the CI signal
+that would otherwise name a team. A test the repo cannot place, or whose path no team claims, lands
+under ``'unowned'``.
"""
from datetime import UTC, datetime, timedelta
-from posthog.clickhouse.workload import Workload
-
from products.engineering_analytics.backend.facade.contracts import (
TrunkQuarantineDebt,
TrunkQuarantinedTest,
TrunkQuarantineTeamDebt,
)
+from products.engineering_analytics.backend.logic.ownership import QuarantinedTestFile, resolve_test_ownership
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
-from products.engineering_analytics.backend.logic.queries._test_spans import (
- UNOWNED_TEAM,
- run_evidence,
- scan_placeholders,
-)
-
-# One owner per test, resolved by its latest ownership stamp (same rule as the team rollups). The
-# selector rides along because it is the runner-native id Trunk's key reconstructs to; the span
-# nodeid folds the pytest file/class boundary and never matches a Trunk key directly.
-_OWNER_ROSTER_SELECT = f"""
- SELECT runner, nodeid, anyIf(selector, selector != '') AS selector, argMax(owner_team, run_signal_at) AS owner_team
- FROM ({run_evidence(bounded=False)})
- GROUP BY runner, nodeid
-"""
_QUARANTINED_SELECT = """
- SELECT runner, nodeid, file, status, quarantine_setting, test_case_id, quarantined_at
+ SELECT runner, nodeid, source_path, crate, status, quarantine_setting, test_case_id, quarantined_at
FROM __TRUNK_SOURCE__
"""
-def _nodeid_variants(nodeid: str) -> list[str]:
- """Every path-suffix variant of a nodeid, so either join side can hold the longer prefix.
- Stops above the bare filename, where two packages' same-named files would collide."""
- path, sep, tail = nodeid.partition("::")
- suffix = f"{sep}{tail}" if sep else ""
- segments = path.split("/")
- variants = [f"{'/'.join(segments[start:])}{suffix}" for start in range(max(len(segments) - 1, 1))]
- return variants or [nodeid]
-
-
def _trunk_url(org_url_slug: str | None, repository: str) -> str | None:
if not org_url_slug:
return None
@@ -69,7 +39,6 @@ def _trunk_test_url(org_url_slug: str | None, repository: str, test_case_id: str
def query_trunk_quarantine_debt(
*,
curated: CuratedGitHubSource,
- owner_window_from: datetime,
ttl_days: int,
now: datetime,
) -> TrunkQuarantineDebt:
@@ -78,7 +47,13 @@ def query_trunk_quarantine_debt(
source = curated.trunk_quarantined_tests_source()
if source is None:
return TrunkQuarantineDebt(
- available=False, ttl_days=ttl_days, repository=curated.repository, trunk_url=None, teams=[], tests=[]
+ available=False,
+ owners_resolved=True,
+ ttl_days=ttl_days,
+ repository=curated.repository,
+ trunk_url=None,
+ teams=[],
+ tests=[],
)
org_url_slug = curated.trunk_org_url_slug()
trunk_url = _trunk_url(org_url_slug, curated.repository)
@@ -91,33 +66,24 @@ def query_trunk_quarantine_debt(
rows = quarantined.results or []
if not rows:
return TrunkQuarantineDebt(
- available=True, ttl_days=ttl_days, repository=curated.repository, trunk_url=trunk_url, teams=[], tests=[]
+ available=True,
+ owners_resolved=True,
+ ttl_days=ttl_days,
+ repository=curated.repository,
+ trunk_url=trunk_url,
+ teams=[],
+ tests=[],
)
- owners = curated.run(
- _OWNER_ROSTER_SELECT,
- query_type="engineering_analytics.trunk_quarantine_owners",
- placeholders=scan_placeholders(repository=curated.repository, date_from=owner_window_from),
- workload=Workload.LOGS,
- )
- owner_by_variant: dict[tuple[str, str], str] = {}
- for runner, nodeid, selector, owner_team in owners.results or []:
- for key in (nodeid, selector):
- if not key:
- continue
- for variant in _nodeid_variants(key):
- owner_by_variant[(runner, variant)] = owner_team
-
+ parsed = [
+ (runner, nodeid, QuarantinedTestFile(source_path=source_path, crate=crate), status, setting, case_id, at)
+ for runner, nodeid, source_path, crate, status, setting, case_id, at in rows
+ ]
+ owned_by_test = resolve_test_ownership(curated.repository, [row[2] for row in parsed])
tests: list[TrunkQuarantinedTest] = []
- for runner, nodeid, file, status, quarantine_setting, test_case_id, quarantined_at in rows:
- owner = next(
- (
- owner_by_variant[(runner, variant)]
- for variant in _nodeid_variants(nodeid)
- if (runner, variant) in owner_by_variant
- ),
- UNOWNED_TEAM,
- )
+ for (runner, nodeid, _file, status, quarantine_setting, test_case_id, quarantined_at), owned in zip(
+ parsed, owned_by_test.tests, strict=True
+ ):
if quarantined_at.tzinfo is None:
quarantined_at = quarantined_at.replace(tzinfo=UTC)
age_days = max((now - quarantined_at) // timedelta(days=1), 0)
@@ -125,8 +91,8 @@ def query_trunk_quarantine_debt(
TrunkQuarantinedTest(
runner=runner,
nodeid=nodeid,
- file=file,
- owner_team=owner,
+ file=owned.path,
+ owner_team=owned.owner_team,
status=status,
quarantine_setting=quarantine_setting,
quarantined_at=quarantined_at,
@@ -143,14 +109,20 @@ def query_trunk_quarantine_debt(
teams = [
TrunkQuarantineTeamDebt(
owner_team=owner_team,
- test_count=len(owned),
- overdue_count=sum(1 for test in owned if test.overdue),
+ test_count=len(owned_tests),
+ overdue_count=sum(1 for test in owned_tests if test.overdue),
# tests is sorted oldest first above, so each owner's first entry carries the max age
- oldest_age_days=owned[0].age_days,
+ oldest_age_days=owned_tests[0].age_days,
)
- for owner_team, owned in rollup.items()
+ for owner_team, owned_tests in rollup.items()
]
teams.sort(key=lambda team: (-team.overdue_count, -team.test_count, -team.oldest_age_days, team.owner_team))
return TrunkQuarantineDebt(
- available=True, ttl_days=ttl_days, repository=curated.repository, trunk_url=trunk_url, teams=teams, tests=tests
+ available=True,
+ owners_resolved=owned_by_test.resolved,
+ ttl_days=ttl_days,
+ repository=curated.repository,
+ trunk_url=trunk_url,
+ teams=teams,
+ tests=tests,
)
diff --git a/products/engineering_analytics/backend/logic/suite_health.py b/products/engineering_analytics/backend/logic/suite_health.py
index c6d6d80084fa..ad22dcc3c419 100644
--- a/products/engineering_analytics/backend/logic/suite_health.py
+++ b/products/engineering_analytics/backend/logic/suite_health.py
@@ -64,11 +64,8 @@ def build_flaky_tests(
def build_trunk_quarantine(*, curated: CuratedGitHubSource) -> TrunkQuarantineDebt:
- # Owners come from the span roster over the widest window the flaky queue allows: older stamps
- # have aged out of Traces retention anyway, and a stale owner beats 'unowned'.
return query_trunk_quarantine_debt(
curated=curated,
- owner_window_from=_parse_date(curated.team, f"-{MAX_FLAKY_WINDOW_DAYS}d"),
ttl_days=TRUNK_QUARANTINE_TTL_DAYS,
now=datetime.now(UTC),
)
diff --git a/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py b/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py
index a5c7ac60fff6..f7dd24f52267 100644
--- a/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py
+++ b/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py
@@ -3,7 +3,7 @@
def build_query(table: str) -> str:
"""Curated SELECT over a synced Trunk quarantined-tests table: the reconstructed runner-native
- nodeid, a runner label, and the parsed quarantine timestamp.
+ nodeid, a runner label, where the test lives, and the parsed quarantine timestamp.
Trunk keys a test by (file, classname, name) and overloads ``parent`` per uploader (verified
against a real connected source): 'pytest' for pytest, the test file path for jest and
@@ -11,6 +11,9 @@ def build_query(table: str) -> str:
pytest class; jest and Playwright need no reassembly; Rust and Storybook rows carry no file, so
the nodeid falls back to classname::name. Rows without a name or quarantine time carry nothing
a consumer can attribute or age, so they drop here.
+
+ ``parent`` stays inside this view: the reading of it a consumer needs is ``source_path`` (where
+ the test file sits, as its suite reported it) and ``crate`` (Rust, which reports no file).
"""
return f"""
SELECT
@@ -21,6 +24,8 @@ def build_query(table: str) -> str:
name
) AS nodeid,
file,
+ any(source_path) AS source_path,
+ any(crate) AS crate,
any(status) AS status,
any(quarantine_setting) AS quarantine_setting,
any(test_case_id) AS test_case_id,
@@ -36,6 +41,9 @@ def build_query(table: str) -> str:
parent LIKE '%.stories.tsx', 'storybook',
'jest'
) AS runner,
+ ifNull(parent, '') AS parent,
+ if(runner = 'rust', '', if(ifNull(file, '') != '', ifNull(file, ''), parent)) AS source_path,
+ if(runner = 'rust', splitByString('::', parent)[1], '') AS crate,
ifNull(file, '') AS file,
ifNull(name, '') AS name,
ifNull(classname, '') AS classname,
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index d66b20733450..078f7e8c4db5 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -895,15 +895,45 @@ def _selector(module_dir: str, test_class: str, test_name: str) -> str:
return f"{module_dir}/{test_name}.py::{test_class}::{test_name}"
+# (file, test_class, name, parent, age_days). `parent` is what the uploader reports: 'pytest', the
+# test file for jest, the crate for Rust.
+_QUARANTINED_TESTS: list[tuple[str, str, str, str, int]] = [
+ ("products/replay_vision/backend/tests/test_api.py", "TestAPI", "test_tag_listing_pagination", "pytest", 41),
+ (
+ "products/batch_exports/backend/tests/test_service.py",
+ "TestService",
+ "test_backfill_window_overlap",
+ "pytest",
+ 30,
+ ),
+ ("posthog/api/test/test_person.py", "TestPerson", "test_person_merge_ordering", "pytest", 23),
+ ("posthog/hogql/test/test_query.py", "TestQuery", "test_property_type_coercion", "pytest", 16),
+ # Reported relative to the directory its suite ran from, which is how Trunk records them.
+ ("tests/utils.test.ts", "", "parses a malformed header", "tests/utils.test.ts", 9),
+ (
+ "src/scenes/experiments/utils.test.ts",
+ "",
+ "rounds a bayesian interval",
+ "src/scenes/experiments/utils.test.ts",
+ 5,
+ ),
+ ("", "", "remote_resolution_hardening", "cymbal::remote_resolution_hardening", 19),
+ ("", "", "flag evaluation stays stable", "feature-flags", 2),
+]
+
+
def _trunk_quarantined_rows() -> list[dict[str, Any]]:
- """Trunk-quarantined rows for the debt scoreboard, reusing the span roster so owner attribution
- resolves through the seeded spans. Ages are staggered on both sides of the TTL, and two rows
- (one of them jest) name tests outside the roster so the 'unowned' bucket renders."""
+ """Trunk-quarantined rows for the debt scoreboard.
+
+ The board resolves owners from the real repository, so these name real test files, one per team,
+ and two of them arrive relative to their suite's directory (as Trunk reports them) to exercise
+ placement. Ages straddle the TTL, and the last row names no file so the 'unowned' bucket renders.
+ """
anchor = timezone.now().replace(microsecond=0)
rows: list[dict[str, Any]] = []
-
- def add(*, file: str, name: str, classname: str, parent: str, age_days: int) -> None:
- quarantined_at = (anchor - timedelta(days=age_days, hours=len(rows))).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+ for index, (file, test_class, name, parent, age_days) in enumerate(_QUARANTINED_TESTS):
+ quarantined_at = (anchor - timedelta(days=age_days, hours=index)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+ module = file[:-3].replace("/", ".") if file.endswith(".py") else ""
rows.append(
{
"file": file,
@@ -912,43 +942,14 @@ def _trunk_quarantined_rows() -> list[dict[str, Any]]:
"parent": parent,
"status": "FLAKY",
"variant": "",
- "classname": classname,
+ "classname": f"{module}.{test_class}" if test_class else "",
"codeowners": "[]",
- "test_case_id": f"engseed-trunk-{len(rows):03d}",
+ "test_case_id": f"engseed-trunk-{index:03d}",
"quarantined_at": quarantined_at,
"quarantine_setting": "AUTO_QUARANTINE",
"status_last_updated_at": quarantined_at,
}
)
-
- age = 2
- for _owner_team, module_dir, tests in _SPAN_TEAMS:
- # Quarantine the first two roster tests per team; module = test_name (the span seed's rule).
- for test_class, test_name, _prior, _current in tests[:2]:
- module_path = f"{module_dir}/{test_name}.py"
- add(
- file=module_path,
- name=test_name,
- classname=f"{module_path[:-3].replace('/', '.')}.{test_class}",
- parent="pytest",
- age_days=age,
- )
- # Walks 2..44 in 7-day steps across the roster, landing rows on both sides of the TTL.
- age = (age + 7) % 45
- add(
- file="posthog/api/test/test_signup.py",
- name="test_social_signup_ratelimit",
- classname="posthog.api.test.test_signup.TestSignup",
- parent="pytest",
- age_days=41,
- )
- add(
- file="frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx",
- name="the activity log logic humanizes flag changes",
- classname="",
- parent="frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx",
- age_days=9,
- )
return rows
diff --git a/products/engineering_analytics/backend/presentation/serializers/suite_health.py b/products/engineering_analytics/backend/presentation/serializers/suite_health.py
index 09e9583a7a34..7d47a611b907 100644
--- a/products/engineering_analytics/backend/presentation/serializers/suite_health.py
+++ b/products/engineering_analytics/backend/presentation/serializers/suite_health.py
@@ -73,10 +73,13 @@ class TrunkQuarantinedTestSerializer(DataclassSerializer):
"nodeid": {
"help_text": "Runner-native test id reconstructed from Trunk's (file, classname, name) key.",
},
- "file": {"help_text": "Repo-relative path of the test file, as Trunk reports it."},
+ "file": {
+ "help_text": "Repo-relative path of the test file, empty when neither the repository nor "
+ "Trunk places it.",
+ },
"owner_team": {
- "help_text": "Owning team slug from the per-test CI spans' emission-time stamp, or 'unowned' "
- "when no in-retention span carries one.",
+ "help_text": "Owning team slug from the repository's ownership files, or 'unowned' when the "
+ "test's file cannot be placed or no team claims its path.",
},
"status": {"help_text": "Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'."},
"quarantine_setting": {
@@ -119,6 +122,10 @@ class TrunkQuarantineDebtSerializer(DataclassSerializer):
"available": {
"help_text": "False when no TrunkIo source has the QuarantinedTests endpoint synced; not an error.",
},
+ "owners_resolved": {
+ "help_text": "False when the repository's ownership files could not be read, so every "
+ "test reads as 'unowned' for that reason rather than because no team claims it.",
+ },
"ttl_days": {"help_text": "Days a quarantine may stand before it counts as overdue."},
"repository": {
"help_text": "The 'owner/name' repository the debt was read for; test file paths are relative to it.",
diff --git a/products/engineering_analytics/backend/presentation/views/suite_health.py b/products/engineering_analytics/backend/presentation/views/suite_health.py
index 84c07a16e262..bbc913199a7b 100644
--- a/products/engineering_analytics/backend/presentation/views/suite_health.py
+++ b/products/engineering_analytics/backend/presentation/views/suite_health.py
@@ -194,7 +194,7 @@ class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):
},
description=(
"The standing Trunk quarantine debt: every test Trunk currently quarantines (failures "
- "suppressed in CI), attributed to its owning team from the per-test CI spans, aged against a "
+ "suppressed in CI), attributed to the team that owns its file in the repository, aged against a "
"TTL, and rolled up per team with the most indebted first. A quarantine only masks a test; it "
"never fixes it, so this is the work queue of tests someone still has to repair or delete. "
"`available` is false when no TrunkIo source has the QuarantinedTests endpoint synced — that "
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
index fc8341006918..0c6059e294da 100644
--- a/products/engineering_analytics/backend/tests/_github_fixtures.py
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -73,6 +73,23 @@ def create_trunk_source(
)
+def _quarantined_row(*, file: str, name: str, classname: str, parent: str) -> dict[str, Any]:
+ return {
+ "file": file,
+ "name": name,
+ "labels": "[]",
+ "parent": parent,
+ "status": "FLAKY",
+ "variant": "",
+ "classname": classname,
+ "codeowners": "[]",
+ "test_case_id": f"case-{name}",
+ "quarantined_at": "2026-01-10T10:00:00.000Z",
+ "quarantine_setting": "AUTO_QUARANTINE",
+ "status_last_updated_at": "2026-01-10T10:00:00.000Z",
+ }
+
+
def _trunk_queue_row(
entry_id: str,
state: str,
diff --git a/products/engineering_analytics/backend/tests/test_ownership.py b/products/engineering_analytics/backend/tests/test_ownership.py
new file mode 100644
index 000000000000..b3ea56f69323
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_ownership.py
@@ -0,0 +1,186 @@
+from collections.abc import Iterator
+from dataclasses import field
+from time import monotonic, sleep
+
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.dataclasses import frozen
+
+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
+from products.engineering_analytics.backend.logic.ownership import (
+ _MAX_FILE_BYTES,
+ UNPLACED,
+ GitHubRepoFiles,
+ OwnershipUnavailable,
+ PlacedTest,
+ QuarantinedTestFile,
+ resolve_test_ownership,
+)
+
+_OWNERS = {
+ "owners.yaml": "version: 1\nowners: [team-root]\n",
+ "nodejs/src/owners.yaml": "version: 1\nowners: [team-ingestion]\n",
+ "frontend/src/scenes/owners.yaml": "version: 1\nowners: [team-product-analytics]\n",
+ "rust/owners.yaml": "version: 1\nowners: [team-rust]\n",
+ "rust/common/kafka/owners.yaml": "version: 1\nowners: ['@someone', team-streams]\n",
+}
+
+_TRACKED = {
+ "nodejs/src/cdp/cdp-e2e.serial.test.ts",
+ "frontend/src/scenes/insights/SQLBoxPlot.stories.tsx",
+ "products/product_analytics/backend/tests/test_insight.py",
+ "rust/personhog-coordination/Cargo.toml",
+ "rust/common/kafka/Cargo.toml",
+}
+
+
+@frozen(frozen=False)
+class _FakeRepoFiles:
+ owners: dict[str, str] = field(default_factory=lambda: dict(_OWNERS))
+ tracked: set[str] = field(default_factory=lambda: set(_TRACKED))
+
+ def read(self, path: str) -> str | None:
+ return self.owners.get(path)
+
+ def exists_all(self, paths: list[str]) -> dict[str, bool]:
+ return {path: path in self.tracked for path in paths}
+
+ def read_all(self, paths: list[str]) -> None:
+ pass
+
+
+def _placements(files: _FakeRepoFiles) -> list[PlacedTest]:
+ return resolve_test_ownership(
+ "PostHog/posthog",
+ [
+ QuarantinedTestFile(source_path="src/cdp/cdp-e2e.serial.test.ts", crate=""),
+ QuarantinedTestFile(source_path="", crate="personhog-coordination"),
+ ],
+ files=files,
+ ).tests
+
+
+class TestRepoOwnership(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # nodejs and frontend suites both report 'src/...', so placing by the reported path
+ # alone hands one team's test to the other.
+ ("src/cdp/cdp-e2e.serial.test.ts", "", "nodejs/src/cdp/cdp-e2e.serial.test.ts", "team-ingestion"),
+ (
+ "../../frontend/src/scenes/insights/SQLBoxPlot.stories.tsx",
+ "",
+ "frontend/src/scenes/insights/SQLBoxPlot.stories.tsx",
+ "team-product-analytics",
+ ),
+ (
+ "products/product_analytics/backend/tests/test_insight.py",
+ "",
+ "products/product_analytics/backend/tests/test_insight.py",
+ "team-root",
+ ),
+ # A crate is placed by its manifest, which is not the test's file, so nothing to link to.
+ ("", "personhog-coordination", "", "team-rust"),
+ # Cargo's crate name is not its directory, and '@handle' owners are people, not teams.
+ ("", "common-kafka", "", "team-streams"),
+ ("feature-flags", "", "", UNOWNED_TEAM),
+ ("src/gone/deleted.test.ts", "", "", UNOWNED_TEAM),
+ ]
+ )
+ def test_places_a_test_and_names_its_owner(self, source_path: str, crate: str, path: str, owner: str) -> None:
+ [placed] = resolve_test_ownership(
+ "PostHog/posthog", [QuarantinedTestFile(source_path=source_path, crate=crate)], files=_FakeRepoFiles()
+ ).tests
+ assert placed.path == path
+ assert placed.owner_team == owner
+
+ def test_a_failed_read_leaves_the_whole_batch_unowned(self) -> None:
+ class _Failing(_FakeRepoFiles):
+ def read(self, path: str) -> str | None:
+ raise OwnershipUnavailable("boom")
+
+ assert _placements(_Failing()) == [UNPLACED, UNPLACED]
+
+ def test_a_repository_missing_its_root_file_attributes_nothing(self) -> None:
+ # A private or renamed repo answers 404 to every path. Without the root-file guard the
+ # nested files this fake still serves would attribute part of the board.
+ no_root = _FakeRepoFiles(owners={k: v for k, v in _OWNERS.items() if k != "owners.yaml"})
+ assert _placements(no_root) == [UNPLACED, UNPLACED]
+
+ def test_a_resolved_batch_says_so(self) -> None:
+ assert resolve_test_ownership("PostHog/posthog", [], files=_FakeRepoFiles()).resolved
+
+
+class TestGitHubRepoFiles(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ @parameterized.expand([(500,), (403,)])
+ def test_an_unexpected_status_raises_rather_than_reading_as_absent(self, status: int) -> None:
+ # Reading a failure as "no such file" reattributes everything under it to an ancestor.
+ with patch(
+ "products.engineering_analytics.backend.logic.ownership.github_request",
+ return_value=_response(status),
+ ):
+ with self.assertRaises(OwnershipUnavailable):
+ GitHubRepoFiles("PostHog/posthog").read("owners.yaml")
+
+ def test_a_missing_file_is_absent_and_fetched_once(self) -> None:
+ with patch(
+ "products.engineering_analytics.backend.logic.ownership.github_request",
+ return_value=_response(404),
+ ) as request:
+ files = GitHubRepoFiles("PostHog/posthog")
+ assert files.read("nodejs/owners.yaml") is None
+ assert files.read("nodejs/owners.yaml") is None
+ assert GitHubRepoFiles("PostHog/posthog").read("nodejs/owners.yaml") is None
+ assert request.call_count == 1
+
+ def test_a_slow_repository_gives_up_instead_of_holding_the_worker(self) -> None:
+ # A cold board asks for hundreds of files. Without a budget for the whole resolution, a
+ # stalled raw host holds a web worker far past the per-request timeout.
+ def never_returns(_method: str, _url: str, **_kwargs: object) -> object:
+ sleep(2)
+ raise AssertionError("unreachable")
+
+ with patch("products.engineering_analytics.backend.logic.ownership.github_request", side_effect=never_returns):
+ files = GitHubRepoFiles("PostHog/posthog")
+ files._deadline = monotonic()
+ with self.assertRaises(OwnershipUnavailable):
+ files.read("owners.yaml")
+
+ @parameterized.expand([("declared", True), ("streamed", False)])
+ def test_an_oversized_file_is_refused(self, _name: str, declare_length: bool) -> None:
+ # A connected repository controls these files, so an unbounded read would put its bytes in
+ # a worker's memory and in Redis. Content-Length can lie, so the streamed read is the ceiling.
+ oversized = b"x" * (_MAX_FILE_BYTES + 1)
+ headers = {"Content-Length": str(len(oversized))} if declare_length else {}
+ with patch(
+ "products.engineering_analytics.backend.logic.ownership.github_request",
+ return_value=_response(200, body=oversized, headers=headers),
+ ):
+ with self.assertRaises(OwnershipUnavailable):
+ GitHubRepoFiles("PostHog/posthog").read("owners.yaml")
+
+
+class _response:
+ encoding = "utf-8"
+
+ def __init__(self, status: int, body: bytes = b"", headers: dict[str, str] | None = None) -> None:
+ self.status_code = status
+ self.headers = headers or {}
+ self._body = body
+
+ def iter_content(self, chunk_size: int) -> Iterator[bytes]:
+ for start in range(0, len(self._body), chunk_size):
+ yield self._body[start : start + chunk_size]
+
+ def __enter__(self) -> "_response":
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ pass
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index 69a055458dae..314feac55986 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -14,13 +14,15 @@ from products.engineering_analytics.backend.logic.sources import (
list_github_sources,
resolve_trunk_merge_queue_table,
)
-from products.engineering_analytics.backend.logic.views import pull_requests, workflow_runs
+from products.engineering_analytics.backend.logic.views import pull_requests, trunk_quarantined_tests, workflow_runs
from products.engineering_analytics.backend.logic.views.source_schema import (
PULL_REQUESTS_COLUMNS,
+ TRUNK_QUARANTINED_TESTS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
from products.engineering_analytics.backend.tests._github_fixtures import (
_pr_row,
+ _quarantined_row,
_run_row,
create_github_source,
create_github_warehouse_table,
@@ -412,3 +414,40 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
f"FROM ({workflow_runs.build_query(table_name)}) AS r"
)
assert rows[0] == ("completed", None, None, "", "", 0, None)
+
+ def test_trunk_quarantined_tests_view_labels_runners_and_reconstructs_paths(self) -> None:
+ # Trunk overloads `parent` per uploader, and ownership is resolved from the source_path and
+ # crate this view reads out of it, so getting either wrong unattributes the whole board.
+ table_name = self._create_table(
+ "trunkio_quarantinedtests",
+ TRUNK_QUARANTINED_TESTS_COLUMNS,
+ [
+ _quarantined_row(
+ file="posthog/api/test/test_person.py",
+ name="test_merge",
+ classname="posthog.api.test.test_person.TestPerson",
+ parent="pytest",
+ ),
+ _quarantined_row(
+ file="",
+ name="k3s_integration",
+ classname="personhog-coordination",
+ parent="personhog-coordination::k3s_integration",
+ ),
+ _quarantined_row(file="src/cdp/cdp.test.ts", name="routes", classname="", parent="src/cdp/cdp.test.ts"),
+ ],
+ )
+ rows = self._select(
+ f"SELECT runner, nodeid, source_path, crate FROM ({trunk_quarantined_tests.build_query(table_name)}) AS q "
+ "ORDER BY runner"
+ )
+ assert rows == [
+ ("jest", "src/cdp/cdp.test.ts::routes", "src/cdp/cdp.test.ts", ""),
+ (
+ "pytest",
+ "posthog/api/test/test_person.py::TestPerson::test_merge",
+ "posthog/api/test/test_person.py",
+ "",
+ ),
+ ("rust", "personhog-coordination::k3s_integration", "", "personhog-coordination"),
+ ]
diff --git a/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx b/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx
index 0419211a8864..4ed490be82e5 100644
--- a/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx
+++ b/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx
@@ -24,7 +24,7 @@ export function TeamQuarantinedTestsTable({
key: 'nodeid',
className: 'w-full max-w-0',
render: (_, row) => {
- // Rust and Storybook rows carry no file path in Trunk's data.
+ // A test the repository could not place carries no file path to link to.
const url = row.trunkUrl ?? (row.file ? githubFileUrl(repository, row.file) : null)
return (
<TestIdCell
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 000a21255c2b..f573a0f01a29 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -1460,9 +1460,9 @@ export interface TrunkQuarantinedTestApi {
runner: string
/** Runner-native test id reconstructed from Trunk's (file, classname, name) key. */
nodeid: string
- /** Repo-relative path of the test file, as Trunk reports it. */
+ /** Repo-relative path of the test file, empty when neither the repository nor Trunk places it. */
file: string
- /** Owning team slug from the per-test CI spans' emission-time stamp, or 'unowned' when no in-retention span carries one. */
+ /** Owning team slug from the repository's ownership files, or 'unowned' when the test's file cannot be placed or no team claims its path. */
owner_team: string
/** Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'. */
status: string
@@ -1488,6 +1488,8 @@ export interface TrunkQuarantineDebtApi {
tests: TrunkQuarantinedTestApi[]
/** False when no TrunkIo source has the QuarantinedTests endpoint synced; not an error. */
available: boolean
+ /** False when the repository's ownership files could not be read, so every test reads as 'unowned' for that reason rather than because no team claims it. */
+ owners_resolved: boolean
/** Days a quarantine may stand before it counts as overdue. */
ttl_days: number
/** The 'owner/name' repository the debt was read for; test file paths are relative to it. */
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index bbd338b8539b..846645f993ee 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -846,7 +846,7 @@ export const getEngineeringAnalyticsTrunkQuarantineUrl = (
}
/**
- * The standing Trunk quarantine debt: every test Trunk currently quarantines (failures suppressed in CI), attributed to its owning team from the per-test CI spans, aged against a TTL, and rolled up per team with the most indebted first. A quarantine only masks a test; it never fixes it, so this is the work queue of tests someone still has to repair or delete. `available` is false when no TrunkIo source has the QuarantinedTests endpoint synced — that is not an error.
+ * The standing Trunk quarantine debt: every test Trunk currently quarantines (failures suppressed in CI), attributed to the team that owns its file in the repository, aged against a TTL, and rolled up per team with the most indebted first. A quarantine only masks a test; it never fixes it, so this is the work queue of tests someone still has to repair or delete. `available` is false when no TrunkIo source has the QuarantinedTests endpoint synced — that is not an error.
* @summary Trunk quarantine debt by owning team
*/
export const engineeringAnalyticsTrunkQuarantine = async (
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx
index 4bb31d46c1c9..ed484b37b10a 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx
@@ -22,6 +22,7 @@ const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', pref
const TRUNK_QUARANTINE: TrunkQuarantineDebtApi = {
available: true,
+ owners_resolved: true,
ttl_days: 15,
repository: 'PostHog/posthog',
trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog',
@@ -113,3 +114,20 @@ export const TrunkQuarantineDebt: Story = {
render: () => <App />,
parameters: { pageUrl: urls.engineeringAnalyticsTestHealth() },
}
+
+const OWNERS_UNAVAILABLE: TrunkQuarantineDebtApi = {
+ ...TRUNK_QUARANTINE,
+ owners_resolved: false,
+ teams: [{ owner_team: 'unowned', test_count: 3, overdue_count: 2, oldest_age_days: 44 }],
+ tests: TRUNK_QUARANTINE.tests.map((test) => ({ ...test, file: '', owner_team: 'unowned' })),
+}
+
+export const TrunkQuarantineDebtOwnersUnavailable: Story = {
+ render: () => <App />,
+ parameters: { pageUrl: urls.engineeringAnalyticsTestHealth() },
+ decorators: [
+ mswDecorator({
+ get: { 'api/projects/:team_id/engineering_analytics/trunk_quarantine/': OWNERS_UNAVAILABLE },
+ }),
+ ],
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
index f54c157bcc63..30f6c5f006c8 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
@@ -120,6 +120,12 @@ function TrunkQuarantineDebtBoard(): JSX.Element {
loading={trunkQuarantineLoading}
/>
</div>
+ {trunkQuarantine && !trunkQuarantine.ownersResolved && (
+ <LemonBanner type="warning">
+ We could not read {trunkQuarantine.repository}'s ownership files, so every test below is listed as
+ unowned. Try again in a few minutes.
+ </LemonBanner>
+ )}
<LemonTable
data-attr="engineering-analytics-trunk-debt-teams-table"
size="small"
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index 2e2a71a94a39..c563633e32b4 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -198,6 +198,7 @@ describe('engineeringAnalyticsLogic', () => {
mockSources.mockResolvedValue([])
mockTrunkQuarantine.mockResolvedValue({
available: true,
+ owners_resolved: true,
ttl_days: 15,
repository: 'PostHog/posthog',
trunk_url: null,
@@ -705,6 +706,7 @@ describe('engineeringAnalyticsLogic', () => {
it('maps the trunk quarantine endpoint and filters the tests by team', async () => {
mockTrunkQuarantine.mockResolvedValue({
available: true,
+ owners_resolved: true,
ttl_days: 15,
repository: 'PostHog/posthog',
trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog',
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index 5fd5e2eeffd0..eb98381b91f7 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -365,6 +365,8 @@ export interface TrunkQuarantineTeamRow {
export interface TrunkQuarantineData {
/** False when no TrunkIo source has the QuarantinedTests endpoint synced; not an error. */
available: boolean
+ /** False when the repository's ownership files could not be read, so every test reads as unowned. */
+ ownersResolved: boolean
ttlDays: number
/** 'owner/name' the debt was read for; test file paths are relative to it. */
repository: string
@@ -813,6 +815,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
})
return {
available: data.available,
+ ownersResolved: data.owners_resolved,
ttlDays: data.ttl_days,
repository: data.repository,
trunkUrl: data.trunk_url ?? null,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 198366fe3da1..2098ad1c828c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -86292,9 +86292,9 @@ export namespace Schemas {
runner: string;
/** Runner-native test id reconstructed from Trunk's (file, classname, name) key. */
nodeid: string;
- /** Repo-relative path of the test file, as Trunk reports it. */
+ /** Repo-relative path of the test file, empty when neither the repository nor Trunk places it. */
file: string;
- /** Owning team slug from the per-test CI spans' emission-time stamp, or 'unowned' when no in-retention span carries one. */
+ /** Owning team slug from the repository's ownership files, or 'unowned' when the test's file cannot be placed or no team claims its path. */
owner_team: string;
/** Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'. */
status: string;
@@ -86320,6 +86320,8 @@ export namespace Schemas {
tests: TrunkQuarantinedTest[];
/** False when no TrunkIo source has the QuarantinedTests endpoint synced; not an error. */
available: boolean;
+ /** False when the repository's ownership files could not be read, so every test reads as 'unowned' for that reason rather than because no team claims it. */
+ owners_resolved: boolean;
/** Days a quarantine may stand before it counts as overdue. */
ttl_days: number;
/** The 'owner/name' repository the debt was read for; test file paths are relative to it. */
diff --git a/tools/owners/posthog_owners/__init__.py b/tools/owners/posthog_owners/__init__.py
index 87b89a4ce2e6..9782504161d0 100644
--- a/tools/owners/posthog_owners/__init__.py
+++ b/tools/owners/posthog_owners/__init__.py
@@ -2,10 +2,12 @@
from .census import TeamTestCensus, census, first_team_owner, runner_for_path
from .matcher import compile_pattern, path_matches_pattern
-from .resolver import OwnersResolver, Resolution
+from .resolver import DiskSource, OwnershipSource, OwnersResolver, Resolution
__all__ = [
+ "DiskSource",
"OwnersResolver",
+ "OwnershipSource",
"Resolution",
"TeamTestCensus",
"census",
diff --git a/tools/owners/posthog_owners/resolver.py b/tools/owners/posthog_owners/resolver.py
index 5fd03a95f9d4..01048cacb533 100644
--- a/tools/owners/posthog_owners/resolver.py
+++ b/tools/owners/posthog_owners/resolver.py
@@ -12,7 +12,7 @@ import subprocess
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Literal, TypedDict
+from typing import Literal, Protocol, TypedDict
from .matcher import compile_pattern, normalize_path
from .schema import UNSET, OwnersFile, TeamEntry, _Unset, parse_owners_file, parse_product_yaml_as_owners
@@ -143,15 +143,44 @@ def _git_repo_root() -> Path:
return Path(result.stdout.strip())
+class OwnershipSource(Protocol):
+ """An ownership file's text by repo-relative path, or None when absent. Only ``resolve`` reads
+ through this; lint and format still walk a real worktree."""
+
+ def read(self, path: str) -> str | None: ...
+
+
+@dataclass(frozen=True)
+class DiskSource:
+ """Ownership files read from a worktree."""
+
+ repo_root: Path
+
+ def read(self, path: str) -> str | None:
+ file = self.repo_root / path
+ return file.read_text() if file.is_file() else None
+
+
+# Names a sourceless resolver's files, so a Resolution still reports the path that decided ownership.
+VIRTUAL_ROOT = Path("/")
+
+
class OwnersResolver:
- """Resolves ownership by reading ``owners.yaml`` / ``product.yaml`` from disk.
+ """Resolves ownership by reading ``owners.yaml`` / ``product.yaml`` through an ``OwnershipSource``.
- Works from any CWD by locating the repo root via ``git rev-parse`` (override
- with ``repo_root`` for testing). Parsed files are cached per directory.
+ Reads a worktree by default, locating the repo root via ``git rev-parse`` (override with
+ ``repo_root`` for testing). Pass ``source`` to resolve without one. Parsed files are cached per
+ directory.
"""
- def __init__(self, repo_root: Path | None = None, purpose: Purpose = DEFAULT_PURPOSE) -> None:
- self.repo_root = (repo_root or _git_repo_root()).resolve()
+ def __init__(
+ self,
+ repo_root: Path | None = None,
+ purpose: Purpose = DEFAULT_PURPOSE,
+ source: OwnershipSource | None = None,
+ ) -> None:
+ self.repo_root = (repo_root or (VIRTUAL_ROOT if source is not None else _git_repo_root())).resolve()
+ self.source = source if source is not None else DiskSource(self.repo_root)
self.purpose = purpose
self._dir_cache: dict[str, OwnersFile | None] = {}
# The worktree is treated as immutable for the resolver's lifetime.
@@ -164,20 +193,24 @@ class OwnersResolver:
if directory in self._dir_cache:
return self._dir_cache[directory]
- base = self.repo_root if directory == "" else self.repo_root / directory
+ prefix = f"{directory}/" if directory else ""
result: OwnersFile | None = None
- owners_path = base / OWNERS_FILENAME
- if owners_path.is_file():
- parsed, _errors = parse_owners_file(owners_path.read_text(), path=owners_path, directory=directory)
+ owners_rel = f"{prefix}{OWNERS_FILENAME}"
+ owners_text = self.source.read(owners_rel)
+ if owners_text is not None:
+ parsed, _errors = parse_owners_file(owners_text, path=self.repo_root / owners_rel, directory=directory)
result = parsed
# A product.yaml alias only applies when there is no owners.yaml (a
# directory with both is a lint error; resolve prefers owners.yaml).
if result is None:
- product_path = base / PRODUCT_FILENAME
- if product_path.is_file():
- result = parse_product_yaml_as_owners(product_path.read_text(), path=product_path, directory=directory)
+ product_rel = f"{prefix}{PRODUCT_FILENAME}"
+ product_text = self.source.read(product_rel)
+ if product_text is not None:
+ result = parse_product_yaml_as_owners(
+ product_text, path=self.repo_root / product_rel, directory=directory
+ )
self._dir_cache[directory] = result
return result
@@ -232,6 +265,18 @@ class OwnersResolver:
contrib.inherit = matched.inherit
return contrib
+ def ownership_file_paths(self, paths: list[str]) -> list[str]:
+ """Every ownership file that could decide any of ``paths``. A source that fetches over the
+ network reads this first, so it can fetch the batch's files together."""
+ return sorted(
+ {
+ f"{directory}/{name}" if directory else name
+ for path in paths
+ for directory in self._ancestor_dirs(normalize_path(path))
+ for name in (OWNERS_FILENAME, PRODUCT_FILENAME)
+ }
+ )
+
def resolve(self, path: str) -> Resolution:
norm = normalize_path(path)
merged = _Merged()
diff --git a/tools/owners/tests/test_owners.py b/tools/owners/tests/test_owners.py
index 64ee5dc8dadd..3fc0f0680181 100644
--- a/tools/owners/tests/test_owners.py
+++ b/tools/owners/tests/test_owners.py
@@ -680,6 +680,22 @@ 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_resolver_reads_through_an_injected_source() -> None:
+ files = {
+ "owners.yaml": "version: 1\nowners: [team-root]\n",
+ "posthog/temporal/owners.yaml": "version: 1\nowners: [team-batch]\n",
+ }
+
+ class DictSource:
+ def read(self, path: str) -> str | None:
+ return files.get(path)
+
+ resolver = OwnersResolver(source=DictSource())
+ assert resolver.resolve("posthog/temporal/test_run.py").owners == ["team-batch"]
+ assert resolver.resolve("posthog/other.py").owners == ["team-root"]
+ assert resolver.resolve("posthog/temporal/test_run.py").source == "posthog/temporal/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")