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): census and merged-pr columns on teams roster (#92562)

Raúl Negrón-Otero1eca205dde50
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5421589db95a..de3cbb39d3c0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6633,9 +6633,9 @@ snapshots:
scenes-app-engineering-analytics-run-activity-chart--default--light:
hash: v1.k794b7964.f63752ff3ebf3bbee3be4ddc83d1ff657d9cdd11ee71e7283c30ce5a1aefde72.yTb8kpRqcG51TbM2CqgRmC5YvgE7-6pV1Trc7y5wuto
scenes-app-engineering-analytics-teams--team-ci-health-roster--dark:
- hash: v1.k794b7964.10bc7ae302cfe76b44f0efc6417a03f865126fb7fb3139d81615bcef2b13a3fb.islcHyz6-MSRZdmYI6AFJYKK-g28eAo3AtiL1jGemvE
+ hash: v1.k794b7964.d2d7578360ba54b7fc61f23ee770a6874cf52b5a5cabd288bc1a28431e964263.YrKgeAKxWLMc3r7KjVvcYQ7QF9liZE7jBm9y_Z94k0A
scenes-app-engineering-analytics-teams--team-ci-health-roster--light:
- hash: v1.k794b7964.86bf01dd65cb6a52cf1ec21ab03e88bad821ca3bbf96727513ac58b50f1dabbb.yveewhKz1q_fJNGD9YDmxy__v0lpk1rOrrO6rhtc-JM
+ hash: v1.k794b7964.43abadb51ad09d1188cc15a614ef2182f8678d11e9874ccb1e42879135fb0683.k0QpKiVLrIBNL7JL530nbIOnzlDa_fqrtLA6_9AZIIY
scenes-app-engineering-analytics-test-health--trunk-quarantine-debt--dark:
hash: v1.k794b7964.1bf2a96d4a8f8875fc554a67e7e7b28adc98b144607babe0ae8342de5a0f3edc.JM5CCK4syW_o4_XReB3Nn6NUpB0I643u2a05XZmoeck
scenes-app-engineering-analytics-test-health--trunk-quarantine-debt--light:
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 09ae82067bb7..790967576e07 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -993,7 +993,6 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="prune old streamlit app versions",
)
- # Engineering analytics daily test-ownership census fan-out.
sender.add_periodic_task(
TEST_CENSUS_CRONTAB,
emit_test_ownership_census.s(),
diff --git a/products/engineering_analytics/AGENTS.md b/products/engineering_analytics/AGENTS.md
index c5c2b1ffa851..99017b21e55f 100644
--- a/products/engineering_analytics/AGENTS.md
+++ b/products/engineering_analytics/AGENTS.md
@@ -6,6 +6,8 @@ Before designing or changing anything here, read both in full; don't re-derive w
@SPEC.md
@README.md
+For any frontend change in this product, also read [frontend/AGENTS.md](./frontend/AGENTS.md): the scope-panel rule (picker-bound content inside the outlined panel, current-state content outside), the single comparison vocabulary, and the table conventions.
+
The decision most often re-derived wrong: **CI ↔ PR linkage is by PR number (the run's `pull_requests` association), never head SHA**.
A head-SHA join silently drops every push but the latest, because the `github_pull_requests` snapshot keeps only the current head.
See SPEC §6 (Locked decisions).
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 65c9a376bfa9..93c0b71733f7 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -159,6 +159,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **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.
+- **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.
## 7. Data sources
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 7c23b3d4222f..31ec904cadfa 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -383,6 +383,7 @@ def list_team_ci_health(
date_to: str | None = None,
min_failed_prs: int | None = None,
limit: int | None = None,
+ owner_team: str | None = None,
source_id: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> TeamCIHealthList:
@@ -392,6 +393,7 @@ def list_team_ci_health(
date_to=date_to,
min_failed_prs=min_failed_prs,
limit=limit,
+ owner_team=owner_team,
)
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index a348673a433d..37aaf93e33b2 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -694,7 +694,7 @@ class TeamCIHealthItem:
every figure is an absolute count, never a rate.
"""
- # Owning team slug (CODEOWNERS handle minus '@PostHog/'), or 'unowned' for unstamped spans.
+ # Owning team slug from the repo's owners.yaml map, or 'unowned' for unstamped spans.
owner_team: str
# Owned tests one commit was seen both failing and passing: the same proof, and the same word,
# the test-health queue's `confirmed_flake` uses.
@@ -711,8 +711,18 @@ class TeamCIHealthItem:
# Runs where an owned test recorded a tolerated failure while quarantined: already masked, still failing.
quarantined_failed_run_count: int
quarantined_failed_run_count_prior: int
- # Most recent failure, recovery, or quarantined-failure run across the team's owned tests, either window.
- last_seen_at: datetime
+ # Most recent failure, recovery, or quarantined-failure run across the team's owned tests,
+ # either window. None for a team present only through the census (no CI signal recorded).
+ last_seen_at: datetime | None
+ # Test files the team owns per the daily owners.yaml census; None until a census event
+ # exists for the repository.
+ test_file_count: int | None = None
+ # The latest census value at or before the window start, for the trend.
+ test_file_count_prior: int | None = None
+ # Merged PRs authored by the team's members in the window, bots excluded; None when the
+ # team_members snapshot isn't synced.
+ merged_pr_count: int | None = None
+ merged_pr_count_prior: int | None = None
@dataclass(frozen=True)
diff --git a/products/engineering_analytics/backend/logic/_shared.py b/products/engineering_analytics/backend/logic/_shared.py
index 1f77e9529258..9fd6c1ce71f0 100644
--- a/products/engineering_analytics/backend/logic/_shared.py
+++ b/products/engineering_analytics/backend/logic/_shared.py
@@ -2,6 +2,7 @@
from datetime import datetime
+from posthog.dataclasses import frozen
from posthog.models.team import Team
from posthog.utils import relative_date_parse
@@ -32,6 +33,29 @@ def _parse_window(
return parsed_from, parsed_to
+@frozen
+class ScanWindow:
+ """The resolved window end and the start of the equal-length prior twin."""
+
+ scan_from: datetime
+ resolved_to: datetime
+
+
+@frozen
+class WindowedCount:
+ """A per-key figure with its prior-window twin, for enrichment joins."""
+
+ current: int | None
+ prior: int | None
+
+
+def _prior_window(date_from: datetime, date_to: datetime | None) -> ScanWindow:
+ """Resolve the prior-twin scan bounds in one place so every *_prior figure on a row
+ shares the same boundary."""
+ resolved_to = date_to or datetime.now(tz=date_from.tzinfo)
+ return ScanWindow(scan_from=date_from - (resolved_to - date_from), resolved_to=resolved_to)
+
+
def _require_repo(repo: str | None) -> tuple[str, str]:
"""`_split_repo` for builders whose repo argument is mandatory."""
owner, name = _split_repo(repo)
diff --git a/products/engineering_analytics/backend/logic/queries/census_counts.py b/products/engineering_analytics/backend/logic/queries/census_counts.py
new file mode 100644
index 000000000000..d3fbf6b48760
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/census_counts.py
@@ -0,0 +1,58 @@
+"""Latest per-team test-file counts from the daily census events, read from ``events``
+through the curated handle so team scope stays in one place (the ``llm_spend`` pattern)."""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.logic._shared import WindowedCount
+from products.engineering_analytics.backend.logic.census import CENSUS_EVENT
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+
+_SELECT = """
+ SELECT
+ toString(properties.owner_team) AS owner_team,
+ argMax(accurateCastOrNull(properties.test_file_count, 'Int64'), timestamp) AS test_file_count,
+ argMaxIf(
+ accurateCastOrNull(properties.test_file_count, 'Int64'),
+ timestamp,
+ timestamp < {date_from}
+ ) AS test_file_count_prior
+ FROM events
+ WHERE event = {census_event}
+ AND properties.repository = {repository}
+ AND timestamp >= {scan_from}
+ AND timestamp <= {date_to}
+ GROUP BY owner_team
+"""
+
+
+def query_census_counts(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ scan_from: datetime,
+ date_to: datetime,
+) -> dict[str, WindowedCount]:
+ """``owner_team -> test-file counts``; empty when no census ran."""
+ if not curated.repository:
+ return {}
+ response = curated.run(
+ _SELECT,
+ query_type="engineering_analytics.team_test_census",
+ placeholders={
+ "census_event": ast.Constant(value=CENSUS_EVENT),
+ "repository": ast.Constant(value=curated.repository),
+ "date_from": ast.Constant(value=date_from),
+ "scan_from": ast.Constant(value=scan_from),
+ "date_to": ast.Constant(value=date_to),
+ },
+ )
+ return {
+ owner_team: WindowedCount(
+ current=int(count) if count is not None else None,
+ prior=int(prior) if prior is not None else None,
+ )
+ for owner_team, count, prior in (response.results or [])
+ if owner_team
+ }
diff --git a/products/engineering_analytics/backend/logic/queries/team_ci_health.py b/products/engineering_analytics/backend/logic/queries/team_ci_health.py
index a2ec52541631..12b2a08e8606 100644
--- a/products/engineering_analytics/backend/logic/queries/team_ci_health.py
+++ b/products/engineering_analytics/backend/logic/queries/team_ci_health.py
@@ -31,6 +31,7 @@ from products.engineering_analytics.backend.facade.contracts import (
TeamCIHealthList,
TeamTestSignal,
)
+from products.engineering_analytics.backend.logic._shared import _prior_window
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries._test_spans import (
run_evidence,
@@ -80,6 +81,7 @@ _ROSTER_SELECT = f"""
GROUP BY runner, nodeid
)
GROUP BY owner_team
+ __OWNER_FILTER__
ORDER BY
(flaky_test_count + regression_test_count) DESC,
(flaky_test_count_prior + regression_test_count_prior) DESC,
@@ -110,10 +112,9 @@ def _window_placeholders(
*, curated: CuratedGitHubSource, date_from: datetime, date_to: datetime | None
) -> dict[str, ast.Expr]:
# The prior window twins the current one: [scan_from, date_from) vs [date_from, date_to].
- resolved_to = date_to or datetime.now(tz=date_from.tzinfo)
- prior_from = date_from - (resolved_to - date_from)
+ window = _prior_window(date_from, date_to)
return scan_placeholders(
- repository=curated.repository, date_from=date_from, scan_from=prior_from, date_to=resolved_to
+ repository=curated.repository, date_from=date_from, scan_from=window.scan_from, date_to=window.resolved_to
)
@@ -124,6 +125,7 @@ def query_team_ci_health(
date_to: datetime | None,
min_failed_prs: int,
limit: int,
+ owner_team: str | None = None,
) -> TeamCIHealthList:
# Fail closed, same as flaky_tests: without a repository identity another connected
# repo's spans would leak into this roster.
@@ -133,9 +135,13 @@ def query_team_ci_health(
placeholders = _window_placeholders(curated=curated, date_from=date_from, date_to=date_to)
placeholders["min_failed_prs"] = ast.Constant(value=min_failed_prs)
placeholders["limit_plus_one"] = ast.Constant(value=limit + 1)
+ if owner_team is not None:
+ placeholders["roster_owner_team"] = ast.Constant(value=owner_team)
response = curated.run(
- _ROSTER_SELECT,
+ _ROSTER_SELECT.replace(
+ "__OWNER_FILTER__", "HAVING owner_team = {roster_owner_team}" if owner_team is not None else ""
+ ),
query_type="engineering_analytics.team_ci_health",
placeholders=placeholders,
workload=Workload.LOGS,
diff --git a/products/engineering_analytics/backend/logic/queries/team_merged_prs.py b/products/engineering_analytics/backend/logic/queries/team_merged_prs.py
new file mode 100644
index 000000000000..07d3fac7915a
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/team_merged_prs.py
@@ -0,0 +1,52 @@
+"""Merged-PR counts per team over a window and its prior twin, attributed through the
+``team_members`` snapshot exactly as ``team_merge_trend`` is: team aggregates only, bots
+excluded (SPEC §2/§6). A member of several teams credits each of them."""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.logic._shared import WindowedCount
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+
+_SELECT = """
+ SELECT
+ members.team_slug AS owner_team,
+ countIf(pr.merged_at >= {date_from}) AS merged_pr_count,
+ countIf(pr.merged_at < {date_from}) AS merged_pr_count_prior
+ FROM __PR_SOURCE__ AS pr
+ JOIN __MEMBERS_SOURCE__ AS members ON pr.author_handle = members.member_handle
+ WHERE pr.merged_at IS NOT NULL
+ AND pr.merged_at >= {scan_from}
+ AND pr.merged_at <= {date_to}
+ AND NOT pr.is_bot
+ GROUP BY owner_team
+"""
+
+
+def query_team_merged_pr_counts(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ scan_from: datetime,
+ date_to: datetime,
+) -> dict[str, WindowedCount] | None:
+ """``team_slug -> merged-PR counts``; None when the membership snapshot isn't synced, so
+ callers can degrade honestly instead of reporting zero merges."""
+ members_source = curated.members_source()
+ if members_source is None:
+ return None
+ sql = _SELECT.replace("__PR_SOURCE__", curated.pr_source()).replace("__MEMBERS_SOURCE__", members_source)
+ response = curated.run(
+ sql,
+ query_type="engineering_analytics.team_merged_pr_counts",
+ placeholders={
+ "date_from": ast.Constant(value=date_from),
+ "scan_from": ast.Constant(value=scan_from),
+ "date_to": ast.Constant(value=date_to),
+ },
+ )
+ return {
+ owner_team: WindowedCount(current=int(count), prior=int(prior))
+ for owner_team, count, prior in (response.results or [])
+ }
diff --git a/products/engineering_analytics/backend/logic/teams.py b/products/engineering_analytics/backend/logic/teams.py
index bc2d525f51bd..8800c375730a 100644
--- a/products/engineering_analytics/backend/logic/teams.py
+++ b/products/engineering_analytics/backend/logic/teams.py
@@ -1,18 +1,34 @@
"""Team-level orchestration: CI health rollups, per-team activity, and merge trend."""
-from products.engineering_analytics.backend.facade.contracts import TeamCIActivity, TeamCIHealthList, TeamMergeTrend
-from products.engineering_analytics.backend.logic._shared import _parse_window
+from dataclasses import replace
+from datetime import datetime, timedelta
+
+from products.engineering_analytics.backend.facade.contracts import (
+ TeamCIActivity,
+ TeamCIHealthItem,
+ TeamCIHealthList,
+ TeamMergeTrend,
+)
+from products.engineering_analytics.backend.logic._shared import WindowedCount, _parse_window, _prior_window
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._test_spans import UNOWNED_TEAM
+from products.engineering_analytics.backend.logic.queries.census_counts import query_census_counts
from products.engineering_analytics.backend.logic.queries.team_ci_health import (
query_team_ci_activity,
query_team_ci_health,
)
from products.engineering_analytics.backend.logic.queries.team_merge_trend import query_team_merge_trend
+from products.engineering_analytics.backend.logic.queries.team_merged_prs import query_team_merged_pr_counts
from products.engineering_analytics.backend.logic.suite_health import (
DEFAULT_FLAKY_MIN_FAILED_PRS,
MAX_FLAKY_WINDOW_DAYS,
)
+# The census emits one value per team per day, so a few days of lookback always finds the
+# value standing at the window start; scanning the full prior twin would read days of
+# events only to discard them.
+_CENSUS_LOOKBACK = timedelta(days=3)
+
# Team CI health rollups scan the current window plus an equal-length prior twin, so the
# default sits below the flaky ceiling to keep both windows inside Traces retention. At the
# 30d cap the prior twin reaches past retention and *_prior counts read low.
@@ -30,6 +46,7 @@ def build_team_ci_health(
date_to: str | None = None,
min_failed_prs: int | None = None,
limit: int | None = None,
+ owner_team: str | None = None,
) -> TeamCIHealthList:
parsed_from, parsed_to = _parse_window(
curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=MAX_FLAKY_WINDOW_DAYS
@@ -42,12 +59,84 @@ def build_team_ci_health(
limit = limit if limit is not None else _DEFAULT_TEAM_LIMIT
if not 1 <= limit <= _MAX_TEAM_LIMIT:
raise ValueError(f"limit must be between 1 and {_MAX_TEAM_LIMIT}")
- return query_team_ci_health(
+ roster = query_team_ci_health(
curated=curated,
date_from=parsed_from,
date_to=parsed_to,
min_failed_prs=min_failed_prs,
limit=limit,
+ owner_team=owner_team,
+ )
+ return _enrich_roster(
+ roster, curated=curated, date_from=parsed_from, date_to=parsed_to, limit=limit, owner_team=owner_team
+ )
+
+
+def _enrich_roster(
+ roster: TeamCIHealthList,
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ limit: int,
+ owner_team: str | None,
+) -> TeamCIHealthList:
+ """Attach census and merged-PR context, and add census-only rows so a team whose tests
+ all pass still appears in the roster instead of vanishing with the signal."""
+ window = _prior_window(date_from, date_to)
+ census = query_census_counts(
+ curated=curated, date_from=date_from, scan_from=date_from - _CENSUS_LOOKBACK, date_to=window.resolved_to
+ )
+ merged = query_team_merged_pr_counts(
+ curated=curated, date_from=date_from, scan_from=window.scan_from, date_to=window.resolved_to
+ )
+ _NO_COUNTS = WindowedCount(current=None, prior=None)
+ _ZERO_COUNTS = WindowedCount(current=0, prior=0)
+
+ def enrich(item: TeamCIHealthItem) -> TeamCIHealthItem:
+ # 'unowned' is not a GitHub team, so a zero merged-PR count would be a made-up number.
+ merged_counts = (
+ merged.get(item.owner_team, _ZERO_COUNTS)
+ if merged is not None and item.owner_team != UNOWNED_TEAM
+ else _NO_COUNTS
+ )
+ census_counts = census.get(item.owner_team, _NO_COUNTS)
+ return replace(
+ item,
+ test_file_count=census_counts.current,
+ test_file_count_prior=census_counts.prior,
+ merged_pr_count=merged_counts.current,
+ merged_pr_count_prior=merged_counts.prior,
+ )
+
+ signal_slugs = {item.owner_team for item in roster.items}
+ quiet_slugs = [
+ slug
+ for slug, _counts in sorted(census.items(), key=lambda kv: (-(kv[1].current or 0), kv[0]))
+ if slug not in signal_slugs and (owner_team is None or slug == owner_team)
+ ]
+ items = [enrich(item) for item in roster.items] + [enrich(_zero_row(slug)) for slug in quiet_slugs]
+ return TeamCIHealthList(
+ items=items[:limit],
+ truncated=roster.truncated or len(items) > limit,
+ limit=limit,
+ )
+
+
+def _zero_row(owner_team: str) -> TeamCIHealthItem:
+ return TeamCIHealthItem(
+ owner_team=owner_team,
+ flaky_test_count=0,
+ flaky_test_count_prior=0,
+ regression_test_count=0,
+ regression_test_count_prior=0,
+ failed_run_count=0,
+ failed_run_count_prior=0,
+ same_commit_recovery_run_count=0,
+ same_commit_recovery_run_count_prior=0,
+ quarantined_failed_run_count=0,
+ quarantined_failed_run_count_prior=0,
+ last_seen_at=None,
)
diff --git a/products/engineering_analytics/backend/presentation/serializers/teams.py b/products/engineering_analytics/backend/presentation/serializers/teams.py
index 88e71c44034a..a25785795dac 100644
--- a/products/engineering_analytics/backend/presentation/serializers/teams.py
+++ b/products/engineering_analytics/backend/presentation/serializers/teams.py
@@ -17,7 +17,7 @@ class TeamCIHealthItemSerializer(DataclassSerializer):
dataclass = TeamCIHealthItem
extra_kwargs = {
"owner_team": {
- "help_text": "Owning team slug (the CODEOWNERS handle minus '@PostHog/', e.g. 'team-replay'), "
+ "help_text": "Owning team slug from the repo's owners.yaml map (e.g. 'team-replay'), "
"or the literal 'unowned' for tests whose spans carry no ownership stamp.",
},
"flaky_test_count": {
@@ -51,8 +51,20 @@ class TeamCIHealthItemSerializer(DataclassSerializer):
"quarantined_failed_run_count_prior": {"help_text": "Same count over the prior window."},
"last_seen_at": {
"help_text": "Most recent failure, recovery, or quarantined-failure run across the team's owned "
- "tests, either window."
+ "tests, either window. Null for a team present only through the census (no CI signal recorded)."
},
+ "test_file_count": {
+ "help_text": "Test files the team owns per the daily owners.yaml census. Null until a census "
+ "event exists for the repository.",
+ },
+ "test_file_count_prior": {
+ "help_text": "The latest census value at or before the window start, for the trend.",
+ },
+ "merged_pr_count": {
+ "help_text": "Merged PRs authored by the team's members in the window, bots excluded. Null when "
+ "the team_members snapshot isn't synced, or for 'unowned'.",
+ },
+ "merged_pr_count_prior": {"help_text": "Same count over the prior window."},
}
diff --git a/products/engineering_analytics/backend/presentation/views/teams.py b/products/engineering_analytics/backend/presentation/views/teams.py
index ed1e7aa86d4e..cb30ee9ca9de 100644
--- a/products/engineering_analytics/backend/presentation/views/teams.py
+++ b/products/engineering_analytics/backend/presentation/views/teams.py
@@ -55,6 +55,14 @@ class TeamActionsMixin(EngineeringAnalyticsViewSetBase):
required=False,
description="Maximum number of teams to return (1-200). Defaults to 100.",
),
+ OpenApiParameter(
+ name="owner_team",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Restrict the roster to one owning team slug (or 'unowned'). The cheap way to "
+ "read a single team's rollup.",
+ ),
_SOURCE_ID,
],
responses={
@@ -71,7 +79,10 @@ class TeamActionsMixin(EngineeringAnalyticsViewSetBase):
"equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI "
"emission time from the repo's ownership map (the distributed owners.yaml files); unstamped "
"spans aggregate under the literal team 'unowned', and a re-stamped test lands under its latest "
- "owner only. Teams are organizational owners of code surfaces, never authors. " + FLAKY_TEST_SIGNAL_CAVEAT
+ "owner only. Each row also carries test_file_count (the daily owners.yaml census denominator, with "
+ "a window-start twin) and merged_pr_count (merged PRs by the team's members, bots excluded); teams "
+ "with census counts but no CI signal appear with zero signal counts and a null last_seen_at. Teams "
+ "are organizational owners of code surfaces, never authors. " + FLAKY_TEST_SIGNAL_CAVEAT
),
)
@action(detail=False, methods=["get"], pagination_class=None)
@@ -83,6 +94,7 @@ class TeamActionsMixin(EngineeringAnalyticsViewSetBase):
date_to=request.query_params.get("date_to") or None,
min_failed_prs=_optional_int_param(request, "min_failed_prs"),
limit=_optional_int_param(request, "limit"),
+ owner_team=request.query_params.get("owner_team") or None,
source_id=request.query_params.get("source_id") or None,
user_access_control=self.user_access_control,
)
diff --git a/products/engineering_analytics/backend/tests/test_team_ci_health.py b/products/engineering_analytics/backend/tests/test_team_ci_health.py
index acd04ad31e96..f99591b1d4f9 100644
--- a/products/engineering_analytics/backend/tests/test_team_ci_health.py
+++ b/products/engineering_analytics/backend/tests/test_team_ci_health.py
@@ -1,12 +1,13 @@
from datetime import UTC, datetime, timedelta
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event
from rest_framework import status
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
+from products.engineering_analytics.backend.logic.census import CENSUS_EVENT
from products.engineering_analytics.backend.tests._github_fixtures import connect_github_source_without_data
T_REPLAY_PRS = "products/replay/backend/tests/test_snap/TestSnap::test_prs"
@@ -215,3 +216,39 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
def test_activity_requires_owner_team(self) -> None:
response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/team_ci_activity/")
assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_roster_carries_census_counts_and_census_only_teams(self) -> None:
+ now = datetime.now(UTC)
+ for owner, count, days_ago in [
+ ("team-replay", 210, 1),
+ ("team-replay", 190, 16),
+ ("team-quiet-green", 40, 1),
+ ]:
+ _create_event(
+ event=CENSUS_EVENT,
+ team=self.team,
+ distinct_id="census",
+ properties={
+ "repository": "PostHog/posthog",
+ "owner_team": owner,
+ "pytest_file_count": count,
+ "jest_file_count": 0,
+ "test_file_count": count,
+ },
+ timestamp=now - timedelta(days=days_ago),
+ )
+
+ rows = self._roster()
+
+ replay = rows["team-replay"]
+ assert (replay["test_file_count"], replay["test_file_count_prior"]) == (210, 190)
+ # No membership snapshot in this fixture: merged-PR context degrades to null, never zero.
+ assert replay["merged_pr_count"] is None
+ # A team with census counts but no CI signal still gets a row, with null last_seen_at.
+ quiet = rows["team-quiet-green"]
+ assert (quiet["test_file_count"], quiet["flaky_test_count"], quiet["last_seen_at"]) == (40, 0, None)
+ assert rows["unowned"]["merged_pr_count"] is None
+
+ def test_roster_filters_to_one_owner_team(self) -> None:
+ data = self._get("team_ci_health", owner_team="team-replay", limit="1")
+ assert [item["owner_team"] for item in data["items"]] == ["team-replay"]
diff --git a/products/engineering_analytics/frontend/AGENTS.md b/products/engineering_analytics/frontend/AGENTS.md
new file mode 100644
index 000000000000..85607340f5b7
--- /dev/null
+++ b/products/engineering_analytics/frontend/AGENTS.md
@@ -0,0 +1,29 @@
+# Engineering analytics frontend conventions
+
+UI grammar for every scene in this product. `frontend/src/AGENTS.md` and the repo skills still apply; these rules are the product-specific layer on top. Model new surfaces on `RepoOverviewScene.tsx` (the repo hub), which is the reference implementation for all of them.
+
+## The scope panel bounds what the pickers govern
+
+- Content a window or repo picker modifies lives inside `ScopePanel` (`components/ScopePanel.tsx`): controls dock on its rim via the `controls` prop, and `busy` shows the rim spinner while anything inside reloads.
+- Current-state content (a backlog, a "now" signal list) sits outside the panel and must not refetch when a picker changes. If a section does not move with the picker, it does not belong inside the border, and the reverse.
+- Navigation (repo chip and crumbs via `ScopeBar`, `showDate={false}` when the page has its own picker) sits above the panel; it scopes identity, not time.
+
+## One comparison vocabulary
+
+- Window-vs-window comparison renders as `WindowComparisonCard` ("This window / Previous window" bars plus a `DeltaBadge`). Nothing else: no invented forms (a muted "was N" companion value was tried and removed), no `MetricTile` delta pills for windowed metrics.
+- Table cells hold plain current values via `CountCell` (`components/CountCell.tsx`). Comparison never lives in a table cell.
+
+## Information altitude
+
+- List pages (the Teams roster) are scannable snapshots: few columns, plain numbers, fixed default window stated in tooltips, no picker.
+- Detail pages carry the depth: the picker, the comparison cards, charts, and drill-in tables.
+
+## Test tables
+
+- The test id cell is `TestIdCell` (`components/TestIdCell.tsx`) in a `w-full max-w-0` column: link to Trunk when the payload carries a `trunk_url`, else to the file on GitHub via `githubFileUrl` in `lib/github.ts`.
+- Include a `Runner` column; render times with `TZLabel`.
+
+## Components and copy
+
+- Lemon for all UI chrome; `@posthog/quill-charts` only for data viz (charts, the `MetricCard` pill). Never raw `@posthog/quill` primitives here.
+- No boilerplate subheader paragraphs under section titles. Method caveats go in column and card tooltips; the scene subtitle is one plain line.
diff --git a/products/engineering_analytics/frontend/CLAUDE.md b/products/engineering_analytics/frontend/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/engineering_analytics/frontend/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/engineering_analytics/frontend/components/CountCell.tsx b/products/engineering_analytics/frontend/components/CountCell.tsx
new file mode 100644
index 000000000000..4d630a64646a
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/CountCell.tsx
@@ -0,0 +1,6 @@
+import { compactCount } from '../lib/format'
+
+/** Plain right-aligned count for table cells; comparison belongs in the tiles, never here. */
+export function CountCell({ value }: { value: number | null }): JSX.Element {
+ return <div className="text-right text-sm font-semibold tabular-nums">{compactCount(value)}</div>
+}
diff --git a/products/engineering_analytics/frontend/components/MetricTile.tsx b/products/engineering_analytics/frontend/components/MetricTile.tsx
index 41668c8a5ef8..725c92c8ead9 100644
--- a/products/engineering_analytics/frontend/components/MetricTile.tsx
+++ b/products/engineering_analytics/frontend/components/MetricTile.tsx
@@ -9,7 +9,6 @@ import { MetricCard, type MetricChange } from '@posthog/quill-charts'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { cn } from 'lib/utils/css-classes'
-import { humanFriendlyNumber } from 'lib/utils/numbers'
/** Relative change in percent, or null when there's no meaningful baseline. */
export function percentChange(current: number | null | undefined, previous: number | null | undefined): number | null {
@@ -33,7 +32,6 @@ export function DeltaBadge({
unit = '%',
goodWhenDown = false,
precision = 0,
- vs = 'vs the previous window',
}: {
/** The delta to show; null hides the badge (no baseline to compare against). */
value: number | null
@@ -41,7 +39,6 @@ export function DeltaBadge({
/** For costs, durations, failures — a drop is the good direction. */
goodWhenDown?: boolean
precision?: number
- vs?: string
}): JSX.Element | null {
if (value == null) {
return null
@@ -49,7 +46,7 @@ export function DeltaBadge({
const rounded = Number(value.toFixed(precision))
if (rounded === 0) {
return (
- <Tooltip title={vs}>
+ <Tooltip title="vs the previous window">
<span className="text-xs font-medium text-tertiary whitespace-nowrap">±0{unit}</span>
</Tooltip>
)
@@ -59,7 +56,7 @@ export function DeltaBadge({
// A near-zero baseline turns growth into a meaningless five-digit percentage — clamp the display.
const display = Math.abs(rounded) > 999 ? '>999' : Math.abs(rounded).toFixed(precision)
return (
- <Tooltip title={vs}>
+ <Tooltip title="vs the previous window">
<span className={cn('text-xs font-semibold whitespace-nowrap', good ? 'text-success' : 'text-danger')}>
{up ? '▲' : '▼'} {display}
{unit}
@@ -68,23 +65,6 @@ export function DeltaBadge({
)
}
-/** Current count with the prior window's count as muted context. Table cells stay colorless on
- * purpose: four colored percent badges per row drown the numbers they annotate. */
-export function CountWithPrior({ current, prior }: { current: number; prior: number }): JSX.Element {
- return (
- <div className="flex items-baseline justify-end gap-1.5">
- <span className="text-sm font-semibold tabular-nums">{humanFriendlyNumber(current)}</span>
- {prior !== current && (
- <Tooltip title="Count in the previous window">
- <span className="text-xs text-tertiary tabular-nums whitespace-nowrap">
- was {humanFriendlyNumber(prior)}
- </span>
- </Tooltip>
- )}
- </div>
- )
-}
-
export interface TileDelta {
/** The delta to show; null (no baseline) and ±0 both hide the pill. */
value: number | null
diff --git a/products/engineering_analytics/frontend/components/ScopePanel.tsx b/products/engineering_analytics/frontend/components/ScopePanel.tsx
index 3c74f41034ff..44acccfc2220 100644
--- a/products/engineering_analytics/frontend/components/ScopePanel.tsx
+++ b/products/engineering_analytics/frontend/components/ScopePanel.tsx
@@ -9,18 +9,25 @@ import { ScopeDateFilter, SourceScopeChip } from './ScopeBar'
export function ScopePanel({
busy = false,
+ controls,
children,
}: {
/** Reloading with data already on screen, so a window change reads as "updating" rather than a silent swap. */
busy?: boolean
+ /** Rim controls; defaults to the shared source chip and window picker. A page with its own window state passes its picker. */
+ controls?: ReactNode
children: ReactNode
}): JSX.Element {
return (
<div className="relative mt-4 rounded-lg border border-primary p-4">
<div className="absolute -top-4 right-3 flex flex-wrap items-center justify-end gap-2 bg-primary px-2">
{busy && <Spinner className="text-secondary" />}
- <SourceScopeChip pickerOnly />
- <ScopeDateFilter />
+ {controls ?? (
+ <>
+ <SourceScopeChip pickerOnly />
+ <ScopeDateFilter />
+ </>
+ )}
</div>
<div className="flex flex-col gap-4 pt-2">{children}</div>
</div>
diff --git a/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx b/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx
index 7aeb6bd2b264..0419211a8864 100644
--- a/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx
+++ b/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx
@@ -1,10 +1,11 @@
-import { IconExternal } from '@posthog/icons'
-import { LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { pluralize } from 'lib/utils/strings'
+import { githubFileUrl } from '../lib/github'
import { TrunkQuarantinedTestRow } from '../scenes/engineeringAnalyticsLogic'
+import { TestIdCell } from './TestIdCell'
/** One team's quarantined tests, rendered inside the debt table's expanded row. */
export function TeamQuarantinedTestsTable({
@@ -21,33 +22,16 @@ export function TeamQuarantinedTestsTable({
{
title: 'Test',
key: 'nodeid',
- // max-w-0 lets the auto-layout cell shrink to the distributed width, so a long
- // nodeid truncates instead of pushing the table wider than the scene.
className: 'w-full max-w-0',
render: (_, row) => {
// Rust and Storybook rows carry no file path in Trunk's data.
- const url =
- row.trunkUrl ?? (row.file ? `https://github.com/${repository}/blob/master/${row.file}` : null)
- if (!url) {
- return (
- <Tooltip title={row.nodeid}>
- <span className="block max-w-full truncate font-mono text-xs">{row.nodeid}</span>
- </Tooltip>
- )
- }
+ const url = row.trunkUrl ?? (row.file ? githubFileUrl(repository, row.file) : null)
return (
- <Tooltip title={row.trunkUrl ? `${row.nodeid} - open in Trunk` : row.nodeid}>
- <Link
- to={url}
- target="_blank"
- targetBlankIcon={false}
- className="flex max-w-full items-center gap-1 font-mono text-xs"
- >
- {/* Icon leads so truncating a long nodeid never clips it away. */}
- <IconExternal className="shrink-0" />
- <span className="truncate">{row.nodeid}</span>
- </Link>
- </Tooltip>
+ <TestIdCell
+ nodeid={row.nodeid}
+ url={url}
+ tooltip={row.trunkUrl ? `${row.nodeid} - open in Trunk` : row.nodeid}
+ />
)
},
},
diff --git a/products/engineering_analytics/frontend/components/TestIdCell.tsx b/products/engineering_analytics/frontend/components/TestIdCell.tsx
new file mode 100644
index 000000000000..8ccfbac88b92
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/TestIdCell.tsx
@@ -0,0 +1,34 @@
+import { IconExternal } from '@posthog/icons'
+import { Link, Tooltip } from '@posthog/lemon-ui'
+
+/** The test-id cell every test table shares: a truncating mono id, linked out when a URL
+ * exists. Render inside a `w-full max-w-0` column so a long nodeid truncates instead of
+ * pushing the table wider than the scene. */
+export function TestIdCell({
+ nodeid,
+ url,
+ tooltip,
+}: {
+ nodeid: string
+ url: string | null
+ tooltip: string
+}): JSX.Element {
+ return (
+ <Tooltip title={tooltip}>
+ {url ? (
+ <Link
+ to={url}
+ target="_blank"
+ targetBlankIcon={false}
+ className="flex max-w-full items-center gap-1 font-mono text-xs"
+ >
+ {/* Icon leads so truncating a long nodeid never clips it away. */}
+ <IconExternal className="shrink-0" />
+ <span className="truncate">{nodeid}</span>
+ </Link>
+ ) : (
+ <span className="block max-w-full truncate font-mono text-xs">{nodeid}</span>
+ )}
+ </Tooltip>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx b/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx
index 0b838c5a7664..7410279375db 100644
--- a/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx
+++ b/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx
@@ -154,7 +154,6 @@ export function WindowComparisonCard({
unit={deltaUnit ?? '%'}
goodWhenDown={goodWhenDown}
precision={deltaPrecision}
- vs="vs the previous window"
/>
</div>
<div className="flex flex-col gap-1.5">
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index b1fa33d6277c..000a21255c2b 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -1360,7 +1360,7 @@ export interface TeamCIActivityApi {
}
export interface TeamCIHealthItemApi {
- /** Owning team slug (the CODEOWNERS handle minus '@PostHog/', e.g. 'team-replay'), or the literal 'unowned' for tests whose spans carry no ownership stamp. */
+ /** Owning team slug from the repo's owners.yaml map (e.g. 'team-replay'), or the literal 'unowned' for tests whose spans carry no ownership stamp. */
owner_team: string
/** Owned tests one commit was seen both failing and passing in the window: the same proof, and the same word, that flaky_tests calls a confirmed_flake. Compare with flaky_test_count_prior for the delta. */
flaky_test_count: number
@@ -1382,8 +1382,31 @@ export interface TeamCIHealthItemApi {
quarantined_failed_run_count: number
/** Same count over the prior window. */
quarantined_failed_run_count_prior: number
- /** Most recent failure, recovery, or quarantined-failure run across the team's owned tests, either window. */
- last_seen_at: string
+ /**
+ * Most recent failure, recovery, or quarantined-failure run across the team's owned tests, either window. Null for a team present only through the census (no CI signal recorded).
+ * @nullable
+ */
+ last_seen_at: string | null
+ /**
+ * Test files the team owns per the daily owners.yaml census. Null until a census event exists for the repository.
+ * @nullable
+ */
+ test_file_count?: number | null
+ /**
+ * The latest census value at or before the window start, for the trend.
+ * @nullable
+ */
+ test_file_count_prior?: number | null
+ /**
+ * Merged PRs authored by the team's members in the window, bots excluded. Null when the team_members snapshot isn't synced, or for 'unowned'.
+ * @nullable
+ */
+ merged_pr_count?: number | null
+ /**
+ * Same count over the prior window.
+ * @nullable
+ */
+ merged_pr_count_prior?: number | null
}
export interface TeamCIHealthListApi {
@@ -1997,6 +2020,10 @@ export type EngineeringAnalyticsTeamCiHealthParams = {
* An unrecovered test counts toward regression_test_count once it failed on at least this many distinct pull requests in the window. Minimum 1. Defaults to 3. Does not affect flaky_test_count, which needs proof, not a threshold.
*/
min_failed_prs?: number
+ /**
+ * Restrict the roster to one owning team slug (or 'unowned'). The cheap way to read a single team's rollup.
+ */
+ owner_team?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 09954c8e14fb..bbd338b8539b 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -780,7 +780,7 @@ export const getEngineeringAnalyticsTeamCiHealthUrl = (
}
/**
- * Per-owning-team rollup of the CI test surfaces each team owns, over the same run evidence as flaky_tests and with the same meaning of flaky: flaky_test_count is owned tests one commit was seen both failing and passing in the window, regression_test_count is owned tests that failed with no such proof and still hit the blast-radius bar, plus failed/recovery/quarantined run counts. Each has an equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI emission time from the repo's ownership map (the distributed owners.yaml files); unstamped spans aggregate under the literal team 'unowned', and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces, never authors. Counts are absolute, never rates: CI emits every failure but omits ordinary passing spans, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.
+ * Per-owning-team rollup of the CI test surfaces each team owns, over the same run evidence as flaky_tests and with the same meaning of flaky: flaky_test_count is owned tests one commit was seen both failing and passing in the window, regression_test_count is owned tests that failed with no such proof and still hit the blast-radius bar, plus failed/recovery/quarantined run counts. Each has an equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI emission time from the repo's ownership map (the distributed owners.yaml files); unstamped spans aggregate under the literal team 'unowned', and a re-stamped test lands under its latest owner only. Each row also carries test_file_count (the daily owners.yaml census denominator, with a window-start twin) and merged_pr_count (merged PRs by the team's members, bots excluded); teams with census counts but no CI signal appear with zero signal counts and a null last_seen_at. Teams are organizational owners of code surfaces, never authors. Counts are absolute, never rates: CI emits every failure but omits ordinary passing spans, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.
*/
export const engineeringAnalyticsTeamCiHealth = async (
projectId: string,
diff --git a/products/engineering_analytics/frontend/lib/github.ts b/products/engineering_analytics/frontend/lib/github.ts
index a0b58f907ea2..34a53f24614a 100644
--- a/products/engineering_analytics/frontend/lib/github.ts
+++ b/products/engineering_analytics/frontend/lib/github.ts
@@ -14,3 +14,8 @@ export function githubRunUrl(repoOwner: string, repoName: string, runId: number)
export function githubCommitUrl(repoOwner: string, repoName: string, sha: string): string {
return `https://github.com/${repoOwner}/${repoName}/commit/${sha}`
}
+
+/** `repository` is 'owner/name'. HEAD resolves the default branch, whatever it is named. */
+export function githubFileUrl(repository: string, file: string): string {
+ return `https://github.com/${repository}/blob/HEAD/${file}`
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx
index 22ed81ac0375..352f3c2c92ab 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconPeople } from '@posthog/icons'
-import { LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'
import { TimeSeriesLineChart, useChartTheme } from '@posthog/quill-charts'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
@@ -14,12 +14,24 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { CountCell } from '../components/CountCell'
import { EntityHeader } from '../components/EntityHeader'
-import { CountWithPrior } from '../components/MetricTile'
+import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
+import { ScopePanel } from '../components/ScopePanel'
import { Section } from '../components/Section'
+import { TestIdCell } from '../components/TestIdCell'
+import { WindowComparisonCard } from '../components/WindowComparisonCard'
import { compactHoursLabel } from '../lib/format'
+import { githubFileUrl } from '../lib/github'
+import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
import { TeamDetailLogicProps, TeamTestSignalRow, teamDetailLogic } from './teamDetailLogic'
-import { TEAMS_WINDOW_DATE_OPTIONS, TEAMS_WINDOW_LABELS, UNOWNED_TEAM, isTeamsWindow } from './teamsLogic'
+import {
+ DEFAULT_TEAMS_WINDOW,
+ TEAMS_WINDOW_DATE_OPTIONS,
+ TEAMS_WINDOW_LABELS,
+ UNOWNED_TEAM,
+ isTeamsWindow,
+} from './teamsLogic'
export const scene: SceneExport<TeamDetailLogicProps> = {
component: EngineeringAnalyticsTeamScene,
@@ -32,40 +44,56 @@ export const scene: SceneExport<TeamDetailLogicProps> = {
}
export function EngineeringAnalyticsTeamScene(): JSX.Element {
- const { activity, activityLoading, mergeTrend, mergeTrendLoading, mergeTrendSeries, window, ownerTeam } =
- useValues(teamDetailLogic)
+ const {
+ activity,
+ activityLoading,
+ healthRow,
+ healthRowLoading,
+ mergeTrend,
+ mergeTrendLoading,
+ mergeTrendSeries,
+ window,
+ ownerTeam,
+ } = useValues(teamDetailLogic)
const { setWindow } = useActions(teamDetailLogic)
+ const { activeSource } = useValues(engineeringAnalyticsLogic)
const { timezone } = useValues(teamLogic)
+ const repository = activeSource?.repo ?? null
const chartTheme = useChartTheme()
- const labels = TEAMS_WINDOW_LABELS[window]
const isUnowned = ownerTeam === UNOWNED_TEAM
const testColumns: LemonTableColumns<TeamTestSignalRow> = [
{
title: 'Test',
key: 'nodeid',
- render: (_, row) => (
- <Tooltip title={row.selector}>
- <span className="truncate font-mono text-xs">{row.nodeid}</span>
- </Tooltip>
- ),
+ className: 'w-full max-w-0',
+ render: (_, row) => {
+ const file = row.selector.split('::')[0]
+ return (
+ <TestIdCell
+ nodeid={row.nodeid}
+ url={repository && file ? githubFileUrl(repository, file) : null}
+ tooltip={row.selector}
+ />
+ )
+ },
},
{
- title: labels.prior,
- key: 'signalCountPrior',
- width: 140,
- align: 'right',
- sorter: (a, b) => a.signalCountPrior - b.signalCountPrior,
- render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.signalCountPrior)}</span>,
+ title: 'Runner',
+ key: 'runner',
+ width: 90,
+ render: (_, row) => row.runner,
},
{
- title: labels.current,
+ title: TEAMS_WINDOW_LABELS[DEFAULT_TEAMS_WINDOW].current,
key: 'signalCount',
width: 140,
align: 'right',
+ tooltip:
+ 'Runs where this test failed, errored, or a retry recovered it. Fixed window; the picker above does not move this list.',
sorter: (a, b) => a.signalCount - b.signalCount,
- render: (_, row) => <CountWithPrior current={row.signalCount} prior={row.signalCountPrior} />,
+ render: (_, row) => <CountCell value={row.signalCount} />,
},
{
title: 'Last seen',
@@ -83,64 +111,114 @@ export function EngineeringAnalyticsTeamScene(): JSX.Element {
return (
<SceneContent className="pb-16">
<SceneTitleSection name="Team CI health" resourceType={{ type: 'health' }} />
- <div className="flex items-start justify-between gap-3">
- <EntityHeader
- icon={<IconPeople />}
- title={isUnowned ? 'Unowned surfaces' : ownerTeam}
- titleSuffix={
- isUnowned ? (
- <Tooltip title="Tests whose CI spans carry no ownership stamp. An ownership gap to close, not a real team.">
- <LemonTag type="warning">ownership gap</LemonTag>
- </Tooltip>
- ) : undefined
- }
- slug={
- <>
- <Link to={urls.engineeringAnalyticsTeams()}>← All teams</Link>
- {!isUnowned && <span>owner: {ownerTeam}</span>}
- </>
- }
- />
- <DateFilter
- dateFrom={window}
- onChange={(from) => isTeamsWindow(from) && setWindow(from)}
- dateOptions={TEAMS_WINDOW_DATE_OPTIONS}
- size="small"
- />
- </div>
+ <EntityHeader
+ icon={<IconPeople />}
+ title={isUnowned ? 'Unowned surfaces' : ownerTeam}
+ titleSuffix={
+ isUnowned ? (
+ <Tooltip title="Tests whose CI spans carry no ownership stamp. An ownership gap to close, not a real team.">
+ <LemonTag type="warning">ownership gap</LemonTag>
+ </Tooltip>
+ ) : undefined
+ }
+ slug={null}
+ />
+ <ScopeBar
+ repoSlot={<RepoScopeChip label={repository ?? 'repository'} to={urls.engineeringAnalytics()} />}
+ crumbs={[
+ { label: 'teams', to: urls.engineeringAnalyticsTeams() },
+ { label: isUnowned ? 'unowned' : ownerTeam },
+ ]}
+ showDate={false}
+ />
- {!isUnowned && (
- <Section id="team-merge-trend" title="Time to merge" busy={mergeTrendLoading}>
- {mergeTrendSeries ? (
- // Flex column: the quill chart root is flex-1 and only gets height from a flex parent.
- <div className="flex h-48 w-full flex-col">
- <TimeSeriesLineChart
- series={[
- { key: 'median', label: 'Median', data: mergeTrendSeries.median },
- { key: 'average', label: 'Average', data: mergeTrendSeries.average },
- ]}
- labels={mergeTrendSeries.labels}
- theme={chartTheme}
- config={{
- xAxis: { timezone, interval: 'day' },
- yAxis: { format: 'duration' },
- tooltip: { valueFormatter: (value) => compactHoursLabel(value) },
- legend: { show: true },
- }}
- />
- </div>
- ) : mergeTrend && !mergeTrend.hasMembershipData ? (
- <div className="flex h-32 items-center text-xs text-secondary">
- No team membership data. Sync the GitHub source's team_members endpoint (needs the org
- Members read grant) to attribute merges to teams.
- </div>
- ) : (
- <div className="flex h-32 items-center text-xs text-secondary">
- No merged PRs in this window.
- </div>
+ <ScopePanel
+ busy={healthRowLoading || mergeTrendLoading}
+ controls={
+ <DateFilter
+ dateFrom={window}
+ onChange={(from) => isTeamsWindow(from) && setWindow(from)}
+ dateOptions={TEAMS_WINDOW_DATE_OPTIONS}
+ size="small"
+ />
+ }
+ >
+ <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
+ <WindowComparisonCard
+ title="Tests owned"
+ tooltip="Test files this team owns per the daily owners.yaml census."
+ value={healthRow?.testFileCount}
+ previousValue={healthRow?.testFileCountPrior}
+ formatValue={humanFriendlyNumber}
+ loading={healthRowLoading}
+ emptyText="No census yet for this repository."
+ />
+ <WindowComparisonCard
+ title="Flaky tests"
+ tooltip="Owned tests one commit was seen both failing and passing in this window. Only tests with that recovery proof count as flaky."
+ value={healthRow?.flakyTestCount}
+ previousValue={healthRow?.flakyTestCountPrior}
+ formatValue={humanFriendlyNumber}
+ goodWhenDown
+ loading={healthRowLoading}
+ emptyText="No signal in this window."
+ />
+ <WindowComparisonCard
+ title="Failed runs"
+ tooltip="CI runs where an owned test failed or errored. Absolute counts, not rates: passing runs are mostly not recorded."
+ value={healthRow?.failedRunCount}
+ previousValue={healthRow?.failedRunCountPrior}
+ formatValue={humanFriendlyNumber}
+ goodWhenDown
+ loading={healthRowLoading}
+ emptyText="No signal in this window."
+ />
+ {!isUnowned && (
+ <WindowComparisonCard
+ title="PRs merged"
+ tooltip="PRs merged by this team's members in the window, bots excluded. Attribution comes from the GitHub team membership snapshot."
+ value={healthRow?.mergedPrCount}
+ previousValue={healthRow?.mergedPrCountPrior}
+ formatValue={humanFriendlyNumber}
+ loading={healthRowLoading}
+ emptyText="No team membership data. Sync the GitHub source's team_members endpoint to attribute merges."
+ />
)}
- </Section>
- )}
+ </div>
+
+ {!isUnowned && (
+ <Section id="team-merge-trend" title="Time to merge" busy={mergeTrendLoading}>
+ {mergeTrendSeries ? (
+ // Flex column: the quill chart root is flex-1 and only gets height from a flex parent.
+ <div className="flex h-48 w-full flex-col">
+ <TimeSeriesLineChart
+ series={[
+ { key: 'median', label: 'Median', data: mergeTrendSeries.median },
+ { key: 'average', label: 'Average', data: mergeTrendSeries.average },
+ ]}
+ labels={mergeTrendSeries.labels}
+ theme={chartTheme}
+ config={{
+ xAxis: { timezone, interval: 'day' },
+ yAxis: { format: 'duration' },
+ tooltip: { valueFormatter: (value) => compactHoursLabel(value) },
+ legend: { show: true },
+ }}
+ />
+ </div>
+ ) : mergeTrend && !mergeTrend.hasMembershipData ? (
+ <div className="flex h-32 items-center text-xs text-secondary">
+ No team membership data. Sync the GitHub source's team_members endpoint (needs the org
+ Members read grant) to attribute merges to teams.
+ </div>
+ ) : (
+ <div className="flex h-32 items-center text-xs text-secondary">
+ No merged PRs in this window.
+ </div>
+ )}
+ </Section>
+ )}
+ </ScopePanel>
<Section id="team-tests" title="Owned tests with signal" busy={activityLoading}>
<LemonTable
@@ -152,12 +230,12 @@ export function EngineeringAnalyticsTeamScene(): JSX.Element {
loading={activityLoading}
pagination={{ pageSize: 25 }}
useURLForSorting={false}
- emptyState="No owned tests with signal in this window."
+ emptyState="No owned tests with signal."
nouns={['test', 'tests']}
/>
{activity?.truncatedTests && (
<div className="mt-2 text-xs text-tertiary">
- Showing the strongest signals. More owned tests had signal in this window.
+ Showing the strongest signals. More owned tests had signal.
</div>
)}
</Section>
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.stories.tsx
index 574a2703a5d5..2b338d6e43d0 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.stories.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.stories.tsx
@@ -6,68 +6,61 @@ import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
-import type { GitHubSourceApi, TeamCIHealthListApi } from '../generated/api.schemas'
+import type { GitHubSourceApi, TeamCIHealthItemApi, TeamCIHealthListApi } from '../generated/api.schemas'
const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '' }]
+function healthRow(overrides: Partial<TeamCIHealthItemApi> & { owner_team: string }): TeamCIHealthItemApi {
+ return {
+ flaky_test_count: 0,
+ flaky_test_count_prior: 0,
+ regression_test_count: 0,
+ regression_test_count_prior: 0,
+ failed_run_count: 0,
+ failed_run_count_prior: 0,
+ same_commit_recovery_run_count: 0,
+ same_commit_recovery_run_count_prior: 0,
+ quarantined_failed_run_count: 0,
+ quarantined_failed_run_count_prior: 0,
+ last_seen_at: null,
+ test_file_count: null,
+ test_file_count_prior: null,
+ merged_pr_count: null,
+ merged_pr_count_prior: null,
+ ...overrides,
+ }
+}
+
+// The table's whole state space: a signal row, the unowned bucket, and a census-only quiet team.
const TEAM_CI_HEALTH: TeamCIHealthListApi = {
items: [
- {
+ healthRow({
owner_team: 'unowned',
flaky_test_count: 12,
- flaky_test_count_prior: 30,
regression_test_count: 41,
- regression_test_count_prior: 22,
failed_run_count: 512,
- failed_run_count_prior: 431,
- same_commit_recovery_run_count: 18,
- same_commit_recovery_run_count_prior: 40,
- quarantined_failed_run_count: 6,
- quarantined_failed_run_count_prior: 0,
last_seen_at: '2026-07-02T09:12:00Z',
- },
- {
+ test_file_count: 581,
+ test_file_count_prior: 590,
+ }),
+ healthRow({
owner_team: 'team-replay',
flaky_test_count: 8,
- flaky_test_count_prior: 8,
regression_test_count: 3,
- regression_test_count_prior: 1,
failed_run_count: 96,
- failed_run_count_prior: 240,
- same_commit_recovery_run_count: 11,
- same_commit_recovery_run_count_prior: 12,
- quarantined_failed_run_count: 0,
- quarantined_failed_run_count_prior: 0,
last_seen_at: '2026-07-02T08:40:00Z',
- },
- {
- owner_team: 'batch-exports',
- flaky_test_count: 0,
- flaky_test_count_prior: 2,
- regression_test_count: 7,
- regression_test_count_prior: 0,
- failed_run_count: 130,
- failed_run_count_prior: 6,
- same_commit_recovery_run_count: 0,
- same_commit_recovery_run_count_prior: 2,
- quarantined_failed_run_count: 0,
- quarantined_failed_run_count_prior: 0,
- last_seen_at: '2026-07-01T22:05:00Z',
- },
- {
- owner_team: 'team-product-analytics',
- flaky_test_count: 1,
- flaky_test_count_prior: 0,
- regression_test_count: 2,
- regression_test_count_prior: 5,
- failed_run_count: 44,
- failed_run_count_prior: 44,
- same_commit_recovery_run_count: 1,
- same_commit_recovery_run_count_prior: 0,
- quarantined_failed_run_count: 0,
- quarantined_failed_run_count_prior: 0,
- last_seen_at: '2026-07-01T16:30:00Z',
- },
+ test_file_count: 204,
+ test_file_count_prior: 201,
+ merged_pr_count: 31,
+ merged_pr_count_prior: 28,
+ }),
+ healthRow({
+ owner_team: 'team-quiet-green',
+ test_file_count: 64,
+ test_file_count_prior: 60,
+ merged_pr_count: 12,
+ merged_pr_count_prior: 15,
+ }),
],
truncated: false,
limit: 100,
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx
index a66e638026a7..0264074b4862 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx
@@ -1,45 +1,36 @@
-import { useActions, useValues } from 'kea'
+import { useValues } from 'kea'
import { combineUrl } from 'kea-router'
import { IconPeople } from '@posthog/icons'
import { LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
-import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { urls } from 'scenes/urls'
-import { CountWithPrior } from '../components/MetricTile'
+import { CountCell } from '../components/CountCell'
import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
import { rowNavigationProps } from '../lib/rowNavigation'
-import {
- TEAMS_WINDOW_DATE_OPTIONS,
- TeamCIHealthRow,
- TeamsWindow,
- UNOWNED_TEAM,
- isTeamsWindow,
- teamsLogic,
-} from './teamsLogic'
+import { DEFAULT_TEAMS_WINDOW, TEAMS_WINDOW_LABELS, TeamCIHealthRow, UNOWNED_TEAM, teamsLogic } from './teamsLogic'
-/** The team's detail page, carrying the roster's window and active source so it opens scoped the same. */
-function detailUrlOf(ownerTeam: string, window: TeamsWindow, sourceId: string | null): string {
- return combineUrl(urls.engineeringAnalyticsTeam(ownerTeam), { window, ...(sourceId ? { source: sourceId } : {}) })
- .url
+const FIXED_WINDOW = TEAMS_WINDOW_LABELS[DEFAULT_TEAMS_WINDOW].current.toLowerCase()
+
+/** The team's detail page, carrying the active source so it opens scoped the same. */
+function detailUrlOf(ownerTeam: string, sourceId: string | null): string {
+ return combineUrl(urls.engineeringAnalyticsTeam(ownerTeam), sourceId ? { source: sourceId } : {}).url
}
export function EngineeringAnalyticsTeams(): JSX.Element {
- const { teams, teamsLoading, teamsWindow, sourceId } = useValues(teamsLogic)
- const { setTeamsWindow } = useActions(teamsLogic)
+ const { teams, teamsLoading, sourceId } = useValues(teamsLogic)
const columns: LemonTableColumns<TeamCIHealthRow> = [
{
title: 'Team',
key: 'ownerTeam',
- width: 260,
sorter: (a, b) => a.ownerTeam.localeCompare(b.ownerTeam),
render: (_, row) =>
row.ownerTeam === UNOWNED_TEAM ? (
<div className="flex items-center gap-2">
<Link
- to={detailUrlOf(row.ownerTeam, teamsWindow, sourceId)}
+ to={detailUrlOf(row.ownerTeam, sourceId)}
className="font-semibold"
data-attr="eng-analytics-team-link"
>
@@ -53,7 +44,7 @@ export function EngineeringAnalyticsTeams(): JSX.Element {
</div>
) : (
<Link
- to={detailUrlOf(row.ownerTeam, teamsWindow, sourceId)}
+ to={detailUrlOf(row.ownerTeam, sourceId)}
className="font-mono text-xs font-semibold"
data-attr="eng-analytics-team-link"
>
@@ -61,73 +52,42 @@ export function EngineeringAnalyticsTeams(): JSX.Element {
</Link>
),
},
+ {
+ title: 'Tests',
+ key: 'testFileCount',
+ width: 120,
+ align: 'right',
+ tooltip: 'Test files this team owns per the daily owners.yaml census.',
+ sorter: (a, b) => (a.testFileCount ?? -1) - (b.testFileCount ?? -1),
+ render: (_, row) => <CountCell value={row.testFileCount} />,
+ },
{
title: 'Flaky tests',
key: 'flakyTestCount',
- width: 140,
+ width: 120,
align: 'right',
- tooltip:
- 'Owned tests one commit was seen both failing and passing in this window, vs the previous one. Only tests with that recovery proof count as flaky.',
+ tooltip: `Owned tests one commit was seen both failing and passing in the ${FIXED_WINDOW}. Only tests with that recovery proof count as flaky.`,
sorter: (a, b) => a.flakyTestCount - b.flakyTestCount,
- render: (_, row) => <CountWithPrior current={row.flakyTestCount} prior={row.flakyTestCountPrior} />,
+ render: (_, row) => <CountCell value={row.flakyTestCount} />,
},
{
title: 'Regressions',
key: 'regressionTestCount',
- width: 140,
+ width: 120,
align: 'right',
- tooltip:
- 'Owned tests that failed with no recorded recovery and still hit several PRs or master. Treat as real breaks until a recovery proves otherwise.',
+ tooltip: `Owned tests that failed in the ${FIXED_WINDOW} with no recorded recovery and still hit several PRs or master. Treat as real breaks until a recovery proves otherwise.`,
sorter: (a, b) => a.regressionTestCount - b.regressionTestCount,
- render: (_, row) => (
- <CountWithPrior current={row.regressionTestCount} prior={row.regressionTestCountPrior} />
- ),
- },
- {
- title: 'Failed runs',
- key: 'failedRunCount',
- width: 130,
- align: 'right',
- tooltip:
- 'CI runs where an owned test failed or errored. Absolute counts, not rates: passing runs are mostly not recorded.',
- sorter: (a, b) => a.failedRunCount - b.failedRunCount,
- render: (_, row) => <CountWithPrior current={row.failedRunCount} prior={row.failedRunCountPrior} />,
- },
- {
- title: 'Recoveries',
- key: 'sameCommitRecoveryRunCount',
- width: 130,
- align: 'right',
- tooltip:
- 'Runs where one commit both failed and passed an owned test (a re-run went green, or an in-job retry recovered it). This is what proves a flake.',
- sorter: (a, b) => a.sameCommitRecoveryRunCount - b.sameCommitRecoveryRunCount,
- render: (_, row) => (
- <CountWithPrior current={row.sameCommitRecoveryRunCount} prior={row.sameCommitRecoveryRunCountPrior} />
- ),
+ render: (_, row) => <CountCell value={row.regressionTestCount} />,
},
]
return (
<div className="flex flex-col gap-4">
<ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />
- <div className="flex items-start justify-between gap-2">
- <div className="flex flex-col gap-0.5">
- <h3 className="m-0 flex items-center gap-1.5 text-base font-semibold">
- <IconPeople className="text-lg" />
- Team CI health
- </h3>
- <p className="m-0 text-xs text-tertiary">
- The CI test surfaces each team owns (flaky tests and failures), with the previous window for
- comparison. Ownership comes from the repo's owners.yaml files, never from authorship.
- </p>
- </div>
- <DateFilter
- dateFrom={teamsWindow}
- onChange={(from) => isTeamsWindow(from) && setTeamsWindow(from)}
- dateOptions={TEAMS_WINDOW_DATE_OPTIONS}
- size="small"
- />
- </div>
+ <h3 className="m-0 flex items-center gap-1.5 text-base font-semibold">
+ <IconPeople className="text-lg" />
+ Team CI health
+ </h3>
<LemonTable
data-attr="engineering-analytics-teams-table"
size="small"
@@ -135,16 +95,16 @@ export function EngineeringAnalyticsTeams(): JSX.Element {
dataSource={teams?.rows ?? []}
rowKey={(row) => row.ownerTeam}
rowClassName="cursor-pointer"
- onRow={(row) => rowNavigationProps(detailUrlOf(row.ownerTeam, teamsWindow, sourceId))}
+ onRow={(row) => rowNavigationProps(detailUrlOf(row.ownerTeam, sourceId))}
loading={teamsLoading}
- pagination={{ pageSize: 10 }}
+ pagination={{ pageSize: 20 }}
useURLForSorting={false}
- emptyState="No team-attributed CI signal in this window. Signal appears once CI emits test spans with ownership stamps."
+ emptyState="No team-attributed CI signal yet. Signal appears once CI emits test spans with ownership stamps."
nouns={['team', 'teams']}
/>
{teams?.truncated && (
<div className="text-xs text-tertiary">
- Showing the {teams.limit} teams with the most signal. More teams qualified in this window.
+ Showing the {teams.limit} teams with the most signal. More teams qualified.
</div>
)}
</div>
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
index 0fd67ee3a301..b9dbf19a99c3 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
@@ -10,7 +10,7 @@ export const VIEW_DESCRIPTIONS: Record<EngineeringAnalyticsView, string> = {
'pull-requests': 'Pull requests and their CI status across connected repos.',
workflows: 'Run volume, success rate, and duration per workflow over the selected window.',
'test-health': 'Quarantine debt by team: which quarantined tests each team owns, and how long they have stood.',
- teams: 'CI test surfaces rolled up by owning team: flaky signal and failures, compared with the previous window.',
+ teams: 'CI test health by owning team, from the owners.yaml map.',
health: 'DORA-style deploy metrics from the GitHub deployments data: frequency, merge to deploy lead time, and failure proxies.',
}
diff --git a/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts b/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts
index 78fd4d838983..cc4e093c51d8 100644
--- a/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts
@@ -4,9 +4,13 @@ import { loaders } from 'kea-loaders'
import { ApiConfig } from 'lib/api'
import { Dayjs, dayjs } from 'lib/dayjs'
-import { engineeringAnalyticsTeamCiActivity, engineeringAnalyticsTeamMergeTrend } from '../generated/api'
+import {
+ engineeringAnalyticsTeamCiActivity,
+ engineeringAnalyticsTeamCiHealth,
+ engineeringAnalyticsTeamMergeTrend,
+} from '../generated/api'
import type { TeamTestSignalApi } from '../generated/api.schemas'
-import { DEFAULT_TEAMS_WINDOW, TeamsWindow, UNOWNED_TEAM } from './teamsLogic'
+import { DEFAULT_TEAMS_WINDOW, TeamCIHealthRow, TeamsWindow, UNOWNED_TEAM, toTeamCIHealthRow } from './teamsLogic'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
@@ -21,7 +25,6 @@ export interface TeamTestSignalRow {
nodeid: string
selector: string
signalCount: number
- signalCountPrior: number
lastSeenAt: string
}
@@ -45,6 +48,8 @@ export interface TeamMergeTrendData {
export interface teamDetailLogicValues {
activity: TeamActivityData | null
activityLoading: boolean
+ healthRow: TeamCIHealthRow | null
+ healthRowLoading: boolean
mergeTrend: TeamMergeTrendData | null
mergeTrendLoading: boolean
mergeTrendSeries: {
@@ -73,6 +78,21 @@ export interface teamDetailLogicActions {
activity: TeamActivityData
payload?: any
}
+ loadHealthRow: () => any
+ loadHealthRowFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadHealthRowSuccess: (
+ healthRow: TeamCIHealthRow | null,
+ payload?: any
+ ) => {
+ healthRow: TeamCIHealthRow | null
+ payload?: any
+ }
loadMergeTrend: () => any
loadMergeTrendFailure: (
error: string,
@@ -128,9 +148,11 @@ export const teamDetailLogic = kea<teamDetailLogicType>([
null as TeamActivityData | null,
{
loadActivity: async (): Promise<TeamActivityData> => {
+ // Current-state list on the fixed default window, deliberately outside the
+ // window picker's scope (the panel rule in ../AGENTS.md).
const data = await engineeringAnalyticsTeamCiActivity(projectId(), {
owner_team: props.ownerTeam,
- date_from: values.window,
+ date_from: DEFAULT_TEAMS_WINDOW,
source_id: props.sourceId ?? undefined,
})
return {
@@ -139,7 +161,6 @@ export const teamDetailLogic = kea<teamDetailLogicType>([
nodeid: t.nodeid,
selector: t.selector,
signalCount: t.signal_count,
- signalCountPrior: t.signal_count_prior,
lastSeenAt: t.last_seen_at,
})),
truncatedTests: data.truncated_tests,
@@ -147,6 +168,21 @@ export const teamDetailLogic = kea<teamDetailLogicType>([
},
},
],
+ healthRow: [
+ null as TeamCIHealthRow | null,
+ {
+ loadHealthRow: async (): Promise<TeamCIHealthRow | null> => {
+ const data = await engineeringAnalyticsTeamCiHealth(projectId(), {
+ date_from: values.window,
+ owner_team: props.ownerTeam,
+ limit: 1,
+ source_id: props.sourceId ?? undefined,
+ })
+ const item = data.items[0]
+ return item ? toTeamCIHealthRow(item) : null
+ },
+ },
+ ],
mergeTrend: [
null as TeamMergeTrendData | null,
{
@@ -218,12 +254,13 @@ export const teamDetailLogic = kea<teamDetailLogicType>([
}),
listeners(({ actions }) => ({
setWindow: () => {
- actions.loadActivity()
actions.loadMergeTrend()
+ actions.loadHealthRow()
},
})),
afterMount(({ actions }) => {
actions.loadActivity()
actions.loadMergeTrend()
+ actions.loadHealthRow()
}),
])
diff --git a/products/engineering_analytics/frontend/scenes/teamsLogic.ts b/products/engineering_analytics/frontend/scenes/teamsLogic.ts
index bcf120d27fda..f3255fde581c 100644
--- a/products/engineering_analytics/frontend/scenes/teamsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/teamsLogic.ts
@@ -1,10 +1,11 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
import { loaders } from 'kea-loaders'
import { ApiConfig } from 'lib/api'
import { dateMapping } from 'lib/utils/dateFilters'
import { engineeringAnalyticsTeamCiHealth } from '../generated/api'
+import type { TeamCIHealthItemApi } from '../generated/api.schemas'
import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
@@ -36,11 +37,14 @@ export interface TeamCIHealthRow {
flakyTestCountPrior: number
/** Owned tests that failed with no such proof and still hit the blast-radius bar. */
regressionTestCount: number
- regressionTestCountPrior: number
failedRunCount: number
failedRunCountPrior: number
- sameCommitRecoveryRunCount: number
- sameCommitRecoveryRunCountPrior: number
+ /** Owned test files per the daily owners.yaml census; null until a census ran. */
+ testFileCount: number | null
+ testFileCountPrior: number | null
+ /** Merged PRs by the team's members; null without the membership snapshot. */
+ mergedPrCount: number | null
+ mergedPrCountPrior: number | null
}
export interface TeamsData {
@@ -49,12 +53,26 @@ export interface TeamsData {
limit: number
}
+export function toTeamCIHealthRow(it: TeamCIHealthItemApi): TeamCIHealthRow {
+ return {
+ ownerTeam: it.owner_team,
+ flakyTestCount: it.flaky_test_count,
+ flakyTestCountPrior: it.flaky_test_count_prior,
+ regressionTestCount: it.regression_test_count,
+ failedRunCount: it.failed_run_count,
+ failedRunCountPrior: it.failed_run_count_prior,
+ testFileCount: it.test_file_count ?? null,
+ testFileCountPrior: it.test_file_count_prior ?? null,
+ mergedPrCount: it.merged_pr_count ?? null,
+ mergedPrCountPrior: it.merged_pr_count_prior ?? null,
+ }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface teamsLogicValues {
sourceId: string | null // engineeringAnalyticsLogic
teams: TeamsData | null
teamsLoading: boolean
- teamsWindow: TeamsWindow
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -77,9 +95,6 @@ export interface teamsLogicActions {
teams: TeamsData
payload?: any
}
- setTeamsWindow: (window: TeamsWindow) => {
- window: TeamsWindow
- }
}
export type teamsLogicType = MakeLogicType<teamsLogicValues, teamsLogicActions>
@@ -90,35 +105,17 @@ export const teamsLogic = kea<teamsLogicType>([
values: [engineeringAnalyticsLogic, ['sourceId']],
actions: [engineeringAnalyticsLogic, ['setSourceId']],
})),
- actions({
- setTeamsWindow: (window: TeamsWindow) => ({ window }),
- }),
- reducers({
- teamsWindow: [DEFAULT_TEAMS_WINDOW as TeamsWindow, { setTeamsWindow: (_, { window }) => window }],
- }),
loaders(({ values }) => ({
teams: [
null as TeamsData | null,
{
loadTeams: async (): Promise<TeamsData> => {
const data = await engineeringAnalyticsTeamCiHealth(projectId(), {
- date_from: values.teamsWindow,
+ date_from: DEFAULT_TEAMS_WINDOW,
source_id: values.sourceId ?? undefined,
})
return {
- rows: data.items.map(
- (it): TeamCIHealthRow => ({
- ownerTeam: it.owner_team,
- flakyTestCount: it.flaky_test_count,
- flakyTestCountPrior: it.flaky_test_count_prior,
- regressionTestCount: it.regression_test_count,
- regressionTestCountPrior: it.regression_test_count_prior,
- failedRunCount: it.failed_run_count,
- failedRunCountPrior: it.failed_run_count_prior,
- sameCommitRecoveryRunCount: it.same_commit_recovery_run_count,
- sameCommitRecoveryRunCountPrior: it.same_commit_recovery_run_count_prior,
- })
- ),
+ rows: data.items.map(toTeamCIHealthRow),
truncated: data.truncated,
limit: data.limit,
}
@@ -127,7 +124,6 @@ export const teamsLogic = kea<teamsLogicType>([
],
})),
listeners(({ actions }) => ({
- setTeamsWindow: () => actions.loadTeams(),
setSourceId: () => actions.loadTeams(),
})),
afterMount(({ actions }) => {
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index eb36545a02b7..cbcd8866cd57 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -238,9 +238,11 @@ tools:
now" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI
emission time from the repo's ownership map (the distributed owners.yaml files); spans without a stamp
aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team),
- and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces,
- never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there
- is no honest denominator.
+ and a re-stamped test lands under its latest owner only. Each row also carries test_file_count (the daily
+ owners.yaml census denominator, with a window-start twin) and merged_pr_count (merged PRs by the team's
+ members, bots excluded); teams with census counts but no CI signal appear with zero signal counts and a null
+ last_seen_at. Teams are organizational owners of code surfaces, never authors. Read all counts as absolute
+ signal, never rates: fast passing runs are not emitted, so there is no honest denominator.
feature_flag: engineering-analytics
engineering-analytics-team-merge-trend:
operation: engineering_analytics_team_merge_trend
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index b2e055372941..f1f193bc1f39 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3349,7 +3349,7 @@
"feature_flag": "engineering-analytics"
},
"engineering-analytics-team-ci-health": {
- "description": "Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d, maximum 30 days). It reads the same per-run evidence as engineering-analytics-flaky-tests and means the same thing by flaky: flaky_test_count is owned tests one commit was seen both failing and passing in the window (a re-run attempt went green, or an in-job retry recovered it), regression_test_count is owned tests that failed with no such proof and still hit min_failed_prs distinct PRs or master, and failed_run_count / same_commit_recovery_run_count / quarantined_failed_run_count are run counts. Each has an equal-length previous-window twin (*_prior) for honest deltas. Use this for \"which team owns the flakiest surfaces right now\" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map (the distributed owners.yaml files); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team), and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest denominator.",
+ "description": "Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d, maximum 30 days). It reads the same per-run evidence as engineering-analytics-flaky-tests and means the same thing by flaky: flaky_test_count is owned tests one commit was seen both failing and passing in the window (a re-run attempt went green, or an in-job retry recovered it), regression_test_count is owned tests that failed with no such proof and still hit min_failed_prs distinct PRs or master, and failed_run_count / same_commit_recovery_run_count / quarantined_failed_run_count are run counts. Each has an equal-length previous-window twin (*_prior) for honest deltas. Use this for \"which team owns the flakiest surfaces right now\" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map (the distributed owners.yaml files); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team), and a re-stamped test lands under its latest owner only. Each row also carries test_file_count (the daily owners.yaml census denominator, with a window-start twin) and merged_pr_count (merged PRs by the team's members, bots excluded); teams with census counts but no CI signal appear with zero signal counts and a null last_seen_at. Teams are organizational owners of code surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest denominator.",
"category": "Engineering analytics",
"feature": "engineering_analytics",
"summary": "Team CI health roster",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a055e2f689f2..7ab4b0bc583a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3378,7 +3378,7 @@
"feature_flag": "engineering-analytics"
},
"engineering-analytics-team-ci-health": {
- "description": "Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d, maximum 30 days). It reads the same per-run evidence as engineering-analytics-flaky-tests and means the same thing by flaky: flaky_test_count is owned tests one commit was seen both failing and passing in the window (a re-run attempt went green, or an in-job retry recovered it), regression_test_count is owned tests that failed with no such proof and still hit min_failed_prs distinct PRs or master, and failed_run_count / same_commit_recovery_run_count / quarantined_failed_run_count are run counts. Each has an equal-length previous-window twin (*_prior) for honest deltas. Use this for \"which team owns the flakiest surfaces right now\" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map (the distributed owners.yaml files); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team), and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest denominator.",
+ "description": "Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d, maximum 30 days). It reads the same per-run evidence as engineering-analytics-flaky-tests and means the same thing by flaky: flaky_test_count is owned tests one commit was seen both failing and passing in the window (a re-run attempt went green, or an in-job retry recovered it), regression_test_count is owned tests that failed with no such proof and still hit min_failed_prs distinct PRs or master, and failed_run_count / same_commit_recovery_run_count / quarantined_failed_run_count are run counts. Each has an equal-length previous-window twin (*_prior) for honest deltas. Use this for \"which team owns the flakiest surfaces right now\" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map (the distributed owners.yaml files); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team), and a re-stamped test lands under its latest owner only. Each row also carries test_file_count (the daily owners.yaml census denominator, with a window-start twin) and merged_pr_count (merged PRs by the team's members, bots excluded); teams with census counts but no CI signal appear with zero signal counts and a null last_seen_at. Teams are organizational owners of code surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest denominator.",
"category": "Engineering analytics",
"feature": "engineering_analytics",
"summary": "Team CI health roster",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9295b2ff5e9d..008a6cf7f8af 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -85702,7 +85702,7 @@ export namespace Schemas {
}
export interface TeamCIHealthItem {
- /** Owning team slug (the CODEOWNERS handle minus '@PostHog/', e.g. 'team-replay'), or the literal 'unowned' for tests whose spans carry no ownership stamp. */
+ /** Owning team slug from the repo's owners.yaml map (e.g. 'team-replay'), or the literal 'unowned' for tests whose spans carry no ownership stamp. */
owner_team: string;
/** Owned tests one commit was seen both failing and passing in the window: the same proof, and the same word, that flaky_tests calls a confirmed_flake. Compare with flaky_test_count_prior for the delta. */
flaky_test_count: number;
@@ -85724,8 +85724,31 @@ export namespace Schemas {
quarantined_failed_run_count: number;
/** Same count over the prior window. */
quarantined_failed_run_count_prior: number;
- /** Most recent failure, recovery, or quarantined-failure run across the team's owned tests, either window. */
- last_seen_at: string;
+ /**
+ * Most recent failure, recovery, or quarantined-failure run across the team's owned tests, either window. Null for a team present only through the census (no CI signal recorded).
+ * @nullable
+ */
+ last_seen_at: string | null;
+ /**
+ * Test files the team owns per the daily owners.yaml census. Null until a census event exists for the repository.
+ * @nullable
+ */
+ test_file_count?: number | null;
+ /**
+ * The latest census value at or before the window start, for the trend.
+ * @nullable
+ */
+ test_file_count_prior?: number | null;
+ /**
+ * Merged PRs authored by the team's members in the window, bots excluded. Null when the team_members snapshot isn't synced, or for 'unowned'.
+ * @nullable
+ */
+ merged_pr_count?: number | null;
+ /**
+ * Same count over the prior window.
+ * @nullable
+ */
+ merged_pr_count_prior?: number | null;
}
export interface TeamCIHealthList {
@@ -93410,6 +93433,10 @@ export namespace Schemas {
* An unrecovered test counts toward regression_test_count once it failed on at least this many distinct pull requests in the window. Minimum 1. Defaults to 3. Does not affect flaky_test_count, which needs proof, not a threshold.
*/
min_failed_prs?: number;
+ /**
+ * Restrict the roster to one owning team slug (or 'unowned'). The cheap way to read a single team's rollup.
+ */
+ owner_team?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index ac562379d846..9e87e2e83322 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -208,7 +208,7 @@ export const EngineeringAnalyticsSourcesParams = /* @__PURE__ */ zod.object({
})
/**
- * Per-owning-team rollup of the CI test surfaces each team owns, over the same run evidence as flaky_tests and with the same meaning of flaky: flaky_test_count is owned tests one commit was seen both failing and passing in the window, regression_test_count is owned tests that failed with no such proof and still hit the blast-radius bar, plus failed/recovery/quarantined run counts. Each has an equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI emission time from the repo's ownership map (the distributed owners.yaml files); unstamped spans aggregate under the literal team 'unowned', and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces, never authors. Counts are absolute, never rates: CI emits every failure but omits ordinary passing spans, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.
+ * Per-owning-team rollup of the CI test surfaces each team owns, over the same run evidence as flaky_tests and with the same meaning of flaky: flaky_test_count is owned tests one commit was seen both failing and passing in the window, regression_test_count is owned tests that failed with no such proof and still hit the blast-radius bar, plus failed/recovery/quarantined run counts. Each has an equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI emission time from the repo's ownership map (the distributed owners.yaml files); unstamped spans aggregate under the literal team 'unowned', and a re-stamped test lands under its latest owner only. Each row also carries test_file_count (the daily owners.yaml census denominator, with a window-start twin) and merged_pr_count (merged PRs by the team's members, bots excluded); teams with census counts but no CI signal appear with zero signal counts and a null last_seen_at. Teams are organizational owners of code surfaces, never authors. Counts are absolute, never rates: CI emits every failure but omits ordinary passing spans, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.
*/
export const EngineeringAnalyticsTeamCiHealthParams = /* @__PURE__ */ zod.object({
project_id: zod
@@ -233,6 +233,12 @@ export const EngineeringAnalyticsTeamCiHealthQueryParams = /* @__PURE__ */ zod.o
.describe(
'An unrecovered test counts toward regression_test_count once it failed on at least this many distinct pull requests in the window. Minimum 1. Defaults to 3. Does not affect flaky_test_count, which needs proof, not a threshold.'
),
+ owner_team: zod
+ .string()
+ .optional()
+ .describe(
+ "Restrict the roster to one owning team slug (or 'unowned'). The cheap way to read a single team's rollup."
+ ),
source_id: zod
.string()
.optional()
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index e3c4edc688b5..b77109dea833 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -170,6 +170,7 @@ const engineeringAnalyticsTeamCiHealth = (): ToolBase<
date_to: params.date_to,
limit: params.limit,
min_failed_prs: params.min_failed_prs,
+ owner_team: params.owner_team,
source_id: params.source_id,
},
})