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): add team ci health surfaces (#70840)

Raúl Negrón-Otero1aa0ce9186fa
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx
index 5b23d18af9fb..7304783a01ba 100644
--- a/frontend/src/productScenes.tsx
+++ b/frontend/src/productScenes.tsx
@@ -72,6 +72,8 @@ export const productScenes: Record<string, () => Promise<any>> = {
import('../../products/engineering_analytics/frontend/scenes/WorkflowRunsScene'),
EngineeringAnalyticsAuthor: () =>
import('../../products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene'),
+ EngineeringAnalyticsTeam: () =>
+ import('../../products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene'),
ErrorTracking: () => import('../../products/error_tracking/frontend/scenes/ErrorTrackingScene/ErrorTrackingScene'),
ErrorTrackingIssue: () =>
import('../../products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene'),
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 98404e031db1..7211e929ef10 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -128,6 +128,8 @@ export const productRoutes: Record<string, [string, string]> = {
'/engineering-analytics/pull-requests': ['EngineeringAnalytics', 'engineeringAnalyticsPullRequestList'],
'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],
'/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],
+ '/engineering-analytics/teams': ['EngineeringAnalytics', 'engineeringAnalyticsTeams'],
+ '/engineering-analytics/teams/:ownerTeam': ['EngineeringAnalyticsTeam', 'engineeringAnalyticsTeam'],
'/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number': [
'EngineeringAnalyticsPullRequest',
'engineeringAnalyticsPullRequest',
@@ -597,6 +599,13 @@ export const productConfiguration: Record<string, any> = {
description: "One author's pull requests \u2014 a filtered view for finding work, not a ranking.",
iconType: 'health',
},
+ EngineeringAnalyticsTeam: {
+ projectBased: true,
+ name: 'Team CI health',
+ layout: 'app-container',
+ description: "One owning team's merge timing and the before/after signal on its owned tests.",
+ iconType: 'health',
+ },
ErrorTracking: {
projectBased: true,
name: 'Error tracking',
@@ -1024,6 +1033,9 @@ export const productUrls = {
engineeringAnalyticsPullRequestList: (): string => '/engineering-analytics/pull-requests',
engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',
engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',
+ engineeringAnalyticsTeams: (): string => '/engineering-analytics/teams',
+ engineeringAnalyticsTeam: (ownerTeam: string): string =>
+ `/engineering-analytics/teams/${encodeURIComponent(ownerTeam)}`,
engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>
`/engineering-analytics/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/pull-requests/${number}`,
engineeringAnalyticsWorkflowRun: (repoOwner: string, repoName: string, runId: number | string): string =>
@@ -1783,6 +1795,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
'EngineeringAnalyticsWorkflowRun',
'EngineeringAnalyticsWorkflowRuns',
'EngineeringAnalyticsAuthor',
+ 'EngineeringAnalyticsTeam',
],
},
{
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 070fbecc09be..dcd5206ca700 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -146,6 +146,9 @@ A PR's current CI status is the head-SHA join between the two (the `ci_rollup` C
- `pr_lifecycle` — PR header + ordered CI-run timeline (a genuine assembly; `metric_quality = "partial"` until reviews/deploys land).
- `ci_failure_logs` — the thinned failure log lines for a PR's CI, grouped by job. Resolves the PR to its run_ids via the same `pull_requests` attribution as `pr_runs`, then reads the Logs product (`service.name = github-ci-logs`) joined on `run_id`. Reads from Logs, not the warehouse.
- `flaky_tests` — the flaky-test leaderboard: per-test CI spans from the Traces product (`trace_spans`, emitted by Backend CI's report-test-timings job) grouped by pytest nodeid over a window (default `-7d`, max 30 days), scoped to the selected GitHub source via the emitted `ci.repository`, and ranked by flakiness signal. A test qualifies by passing on retry (`rerun_passed`) at least `min_rerun_passes` times (default 1) OR failing on at least `min_failed_prs` distinct PRs (default 3). Absolute counts only, never rates — sub-threshold passing runs aren't emitted, so denominators are biased. Reads from Traces, not the warehouse.
+- `team_ci_health`: the per-owning-team rollup of the same per-test CI spans. Per team: flaky-test count (the leaderboard's qualification bar, applied per team), failed/error and pass-on-retry span counts, each with an equal-length previous-window twin (`*_prior`) for honest deltas (default window `-14d`, max 30 days; the scan covers twice the window). Ownership rides on the spans themselves: the CI emitter stamps `test.owner_team` from the repo's ownership map (`products/*/product.yaml` + CODEOWNERS, first listed owner) at emission time, so no server-side ownership map exists; unstamped spans aggregate under the literal team `unowned`, a first-class row that surfaces ownership gaps. Teams are organizational owners of code surfaces, never authors (§2's non-goal is untouched: no author aggregation).
+- `team_ci_activity`: one team's detail assembly, the per-test current-vs-prior signal pairs (the before/after comparison) capped at `test_limit`. Same ownership and caveat rules as `team_ci_health`.
+- `team_merge_trend`: one team's daily time-to-merge trend: the median and average `open_to_merge_seconds` over the PRs the team's members merged each day (median vs average diverge when a few long-running PRs drag the mean). Attribution is PR author login joined to the GitHub source's optional `team_members` snapshot (org team slug, matched exactly against the caller's team slug); `has_membership_data` is false when that snapshot isn't synced, and the read degrades rather than 500s. Bots excluded; team-level aggregates only, never per-member figures (see §8, team taxonomy).
**UI:** a read-only scene on the same endpoints via the generated API client — a PR list (CI status, CI duration, age), the count cards (open / stuck >7d / failing CI), and a workflow-health view. Read-only; **no saved views or stateful filters in this phase** (persisted/stateful surfaces are a later, separate decision). Columns that need deferred data — time-in-review, reviewers/approvals, per-check counts, DORA — are out until the event substrate lands (§9).
@@ -294,7 +297,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
Use the current default; revisit when the relevant data lands (§9).
-- Team taxonomy (CODEOWNERS vs config file vs author allowlist) — defer until team-level rollups are asked for.
+- Team taxonomy: **resolved** (team-level rollups were asked for). Ownership is the repo's own map (`products/*/product.yaml` + CODEOWNERS, first listed owner on the rare multi-owner path), resolved **at CI emission time** where the repo is checked out and stamped onto the emitted spans (`test.owner_team`). No server-side ownership mirror, no per-team config model, no author allowlist. Capture-time truth is intentional: a test is attributed to whoever owned it when it flaked. Unstamped spans aggregate as `unowned`. Team surfaces aggregate owned code surfaces, plus one sanctioned member-level aggregation. _(Changed, reason:)_ the earlier "never member activity" line predates the warehouse `team_members` snapshot (GitHub org team membership) landing as a source endpoint; a DevEx reader prioritizing CI work needs the team's delivery context (time to merge), and code-surface ownership cannot attribute a PR to a team until changed-file data lands. `team_merge_trend` therefore joins PR author login to GitHub team membership, under hard limits that keep §2 intact: team-level aggregates only (median/average), no per-member figures or splits inside a team page, no cross-team rankings, bots excluded. The GitHub team slug is a second namespace beside the ownership slug; they are matched by exact slug and a mismatch yields an empty team series, never another team's data.
- Cycle time variants (first-commit, ready-for-review, first-approval) — need review + state-transition data.
- Deploy definition (deployment events vs named workflow vs tag push) — decide when deploy data lands.
- Path-based filtering (which files a PR touched) — not in the current snapshot; comes with the lifecycle-event data.
@@ -311,6 +314,7 @@ Available now (warehouse snapshots, read via the curated query builders):
- `github_pull_requests` — PR snapshot: number, title, author, state, created_at, merged_at, closed_at, draft flag, base/head refs, **labels and `base.repo.full_name` in the raw JSON** (mapped in the read layer, not new ingestion). Current state only — transitions are overwritten on update.
- `github_workflow_runs` — CI runs: workflow name, status, conclusion, run_started_at, updated_at, head SHA, **`run_attempt` and the `pull_requests` association** (the per-PR push / re-run rollup keys on these). Each run is immutable, so durations and their trends are precise.
+- `github_team_members`: GitHub org team membership (member login with the parent team's id/slug/name injected per row), the author→team key behind `team_merge_trend`. Optional and off by default at the source (needs the org Members: Read grant), so every read that touches it must degrade gracefully when it isn't synced.
Landing (the cost substrate, via a new warehouse source):
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 3718a5af7a0f..b53a60536c6b 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -40,6 +40,9 @@ from products.engineering_analytics.backend.facade.contracts import (
QuarantineRequestResult,
RepoOverview,
RunFailureLogs,
+ TeamCIActivity,
+ TeamCIHealthList,
+ TeamMergeTrend,
WorkflowCost,
WorkflowHealthItem,
WorkflowJob,
@@ -312,6 +315,63 @@ def list_flaky_tests(
)
+def list_team_ci_health(
+ *,
+ team: Team,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ min_rerun_passes: int | None = None,
+ min_failed_prs: int | None = None,
+ limit: int | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> TeamCIHealthList:
+ return logic.build_team_ci_health(
+ curated=_authorized_source(team, source_id, user_access_control),
+ date_from=date_from,
+ date_to=date_to,
+ min_rerun_passes=min_rerun_passes,
+ min_failed_prs=min_failed_prs,
+ limit=limit,
+ )
+
+
+def get_team_ci_activity(
+ *,
+ team: Team,
+ owner_team: str,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ test_limit: int | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> TeamCIActivity:
+ return logic.build_team_ci_activity(
+ curated=_authorized_source(team, source_id, user_access_control),
+ owner_team=owner_team,
+ date_from=date_from,
+ date_to=date_to,
+ test_limit=test_limit,
+ )
+
+
+def get_team_merge_trend(
+ *,
+ team: Team,
+ owner_team: str,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> TeamMergeTrend:
+ return logic.build_team_merge_trend(
+ curated=_authorized_source(team, source_id, user_access_control),
+ owner_team=owner_team,
+ date_from=date_from,
+ date_to=date_to,
+ )
+
+
def get_broken_tests(
*,
team: Team,
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index adc23de265a9..fde93787c9fc 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -545,6 +545,99 @@ class FlakyTestList:
limit: int
+@dataclass(frozen=True)
+class TeamCIHealthItem:
+ """One owning team's rollup of the CI test surfaces it owns, with equal-length
+ previous-window twins so a caller can render honest deltas.
+
+ Ownership rides on the spans themselves (the CI emitter stamps ``test.owner_team``
+ from the repo's ownership map at emission time); spans with no stamp aggregate
+ under the literal team ``'unowned'``. See ``FLAKY_TEST_SIGNAL_CAVEAT`` for why
+ every figure is an absolute count, never a rate.
+ """
+
+ # Owning team slug (CODEOWNERS handle minus '@PostHog/'), or 'unowned' for unstamped spans.
+ owner_team: str
+ # Owned tests meeting the flaky-leaderboard bar in the window (rerun passes OR distinct failed PRs).
+ flaky_test_count: int
+ flaky_test_count_prior: int
+ # Signal spans on owned tests with outcome 'failed' or 'error' in the window.
+ failed_count: int
+ failed_count_prior: int
+ # Spans on owned tests that failed first, then passed on an automatic retry.
+ rerun_passed_count: int
+ rerun_passed_count_prior: int
+ # Spans on owned tests that failed while quarantined (xfail): already masked, still flaky.
+ xfailed_count: int
+ xfailed_count_prior: int
+ # Most recent signal span across the team's owned tests, either window.
+ last_seen_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamCIHealthList:
+ """The per-team CI health roster over a window (same {items, truncated, limit} shape as
+ ``FlakyTestList``). Teams compare as organizational owners of code surfaces; this list
+ never aggregates by author.
+ """
+
+ items: list[TeamCIHealthItem]
+ truncated: bool
+ limit: int
+
+
+@dataclass(frozen=True)
+class TeamTestSignal:
+ """One owned test's flaky signal across the current window and its equal-length prior
+ window, the pair behind a before-vs-after slope reading. Signal = failed + error +
+ pass-on-retry spans (xfail excluded: already-quarantined noise).
+ """
+
+ nodeid: str
+ selector: str
+ signal_count: int
+ signal_count_prior: int
+ last_seen_at: datetime
+
+
+@dataclass(frozen=True)
+class TeamCIActivity:
+ """One team's detail assembly: the per-test current-vs-prior signal pairs over the
+ window and its equal-length prior twin, capped at the test limit.
+ """
+
+ owner_team: str
+ tests: list[TeamTestSignal]
+ truncated_tests: bool
+
+
+@dataclass(frozen=True)
+class TeamMergeTrendPoint:
+ """One day of the team's merged-PR timing: the median and average open→merge over the
+ PRs the team's members merged that day. Both are None on a day the team merged nothing;
+ ``merged_count`` says how many merges back them.
+ """
+
+ day: datetime
+ median_seconds: float | None
+ average_seconds: float | None
+ merged_count: int
+
+
+@dataclass(frozen=True)
+class TeamMergeTrend:
+ """A team's time-to-merge trend over the window. Attribution is PR author login →
+ GitHub org team membership (the ``team_members`` snapshot); only team-level medians
+ are surfaced, never per-member figures or cross-team rankings (SPEC §2/§7).
+ """
+
+ owner_team: str
+ # False when the source has no team_members snapshot synced: the chart has no honest
+ # team attribution, as opposed to "synced but this team merged nothing".
+ has_membership_data: bool
+ points: list[TeamMergeTrendPoint]
+
+
@dataclass(frozen=True)
class CIStatusRollup:
"""A PR's CI, collapsed from the latest workflow run per workflow on its head
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index d09d64170b9c..41cccf56cd38 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -31,6 +31,9 @@ from products.engineering_analytics.backend.facade.contracts import (
PullRequestList,
RepoOverview,
RunFailureLogs,
+ TeamCIActivity,
+ TeamCIHealthList,
+ TeamMergeTrend,
WorkflowCost,
WorkflowHealthItem,
WorkflowHealthRunScope,
@@ -72,6 +75,11 @@ from products.engineering_analytics.backend.logic.queries.repo_overview import (
)
from products.engineering_analytics.backend.logic.queries.repo_run_activity import query_repo_run_activity
from products.engineering_analytics.backend.logic.queries.resolve_branch import query_resolve_branch
+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.workflow_health import query_workflow_health
from products.engineering_analytics.backend.logic.queries.workflow_jobs import query_workflow_jobs
from products.engineering_analytics.backend.logic.queries.workflow_run import query_workflow_run
@@ -105,6 +113,15 @@ _DEFAULT_FLAKY_MIN_FAILED_PRS = 3
_DEFAULT_FLAKY_LIMIT = 50
_MAX_FLAKY_LIMIT = 200
+# 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.
+_DEFAULT_TEAM_WINDOW = "-14d"
+_DEFAULT_TEAM_LIMIT = 100
+_MAX_TEAM_LIMIT = 200
+_DEFAULT_TEAM_TEST_LIMIT = 25
+_MAX_TEAM_TEST_LIMIT = 100
+
# Broken-tests panel: a fixed short window (not caller-tunable in v1, like current_branch_health).
# Two days keeps the logs-cluster scan light while still spanning the classifier's boundaries — a
# flaky failure needs a >24h span and a novel one needs first-seen <24h, both fitting inside 48h.
@@ -330,6 +347,84 @@ def build_flaky_tests(
)
+def build_team_ci_health(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ min_rerun_passes: int | None = None,
+ min_failed_prs: int | None = None,
+ limit: int | 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
+ )
+ min_rerun_passes = min_rerun_passes if min_rerun_passes is not None else _DEFAULT_FLAKY_MIN_RERUN_PASSES
+ min_failed_prs = min_failed_prs if min_failed_prs is not None else _DEFAULT_FLAKY_MIN_FAILED_PRS
+ # Same explicit-positive-bar rule as the flaky leaderboard: a zero threshold would
+ # silently qualify every test with any signal span.
+ if min_rerun_passes < 1 or min_failed_prs < 1:
+ raise ValueError("min_rerun_passes and min_failed_prs must be at least 1")
+ 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(
+ curated=curated,
+ date_from=parsed_from,
+ date_to=parsed_to,
+ min_rerun_passes=min_rerun_passes,
+ min_failed_prs=min_failed_prs,
+ limit=limit,
+ )
+
+
+def build_team_ci_activity(
+ *,
+ curated: CuratedGitHubSource,
+ owner_team: str,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ test_limit: int | None = None,
+) -> TeamCIActivity:
+ normalized_team = owner_team.strip()
+ if not normalized_team:
+ raise ValueError("owner_team is required")
+ parsed_from, parsed_to = _parse_window(
+ curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=_MAX_FLAKY_WINDOW_DAYS
+ )
+ test_limit = test_limit if test_limit is not None else _DEFAULT_TEAM_TEST_LIMIT
+ if not 1 <= test_limit <= _MAX_TEAM_TEST_LIMIT:
+ raise ValueError(f"test_limit must be between 1 and {_MAX_TEAM_TEST_LIMIT}")
+ return query_team_ci_activity(
+ curated=curated,
+ owner_team=normalized_team,
+ date_from=parsed_from,
+ date_to=parsed_to,
+ test_limit=test_limit,
+ )
+
+
+def build_team_merge_trend(
+ *,
+ curated: CuratedGitHubSource,
+ owner_team: str,
+ date_from: str | None = None,
+ date_to: str | None = None,
+) -> TeamMergeTrend:
+ normalized_team = owner_team.strip()
+ if not normalized_team:
+ raise ValueError("owner_team is required")
+ parsed_from, parsed_to = _parse_window(
+ curated.team, date_from, date_to, default=_DEFAULT_TEAM_WINDOW, max_days=_MAX_FLAKY_WINDOW_DAYS
+ )
+ return query_team_merge_trend(
+ curated=curated,
+ owner_team=normalized_team,
+ date_from=parsed_from,
+ date_to=parsed_to,
+ )
+
+
def build_broken_tests(*, curated: CuratedGitHubSource) -> BrokenTestsResult:
# Fixed windows resolved through the module's relative-date entry point (like current_branch_health):
# the 2-day analysis window and the 24h sparkline window. The SQL uses now() for the age/span/offset
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 3e6f03f5e0ec..f7566840d241 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -27,7 +27,13 @@ from posthog.clickhouse.workload import Workload
from posthog.models.team import Team
from products.engineering_analytics.backend.logic.sources import GitHubTables, resolve_github_tables
-from products.engineering_analytics.backend.logic.views import job_costs, pull_requests, workflow_jobs, workflow_runs
+from products.engineering_analytics.backend.logic.views import (
+ job_costs,
+ pull_requests,
+ team_members,
+ workflow_jobs,
+ workflow_runs,
+)
if TYPE_CHECKING:
from posthog.rbac.user_access_control import UserAccessControl
@@ -92,6 +98,12 @@ class CuratedGitHubSource:
return None
return f"({workflow_jobs.build_query(self._tables.workflow_jobs)})"
+ def members_source(self) -> str | None:
+ """Curated team-membership ``SELECT`` subquery, or None when the optional table isn't synced."""
+ if not self._tables.team_members:
+ return None
+ return f"({team_members.build_query(self._tables.team_members)})"
+
def job_cost_source(self) -> str | None:
"""Per-job cost ``SELECT`` subquery — the same view body ``engineering_analytics_job_costs``
exposes, but with the endpoint-only run pass-through columns (``run_started_at`` /
diff --git a/products/engineering_analytics/backend/logic/queries/_test_spans.py b/products/engineering_analytics/backend/logic/queries/_test_spans.py
new file mode 100644
index 000000000000..f0671c4d3236
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/_test_spans.py
@@ -0,0 +1,94 @@
+"""The one definition of the per-test CI span scan (domain rules defined once, APOSD).
+
+Backend CI emits one OTel span per test into the Traces store (span name = reconstructed
+pytest nodeid, ``test.*`` attributes, ``ci.*`` resource attributes; see
+``.github/scripts/report_test_timings.py``). Every query over that signal (the flaky-test
+leaderboard and the per-team rollups) embeds this scan, so the service fence, the signal
+outcomes, the repository scoping, and the ownership fallback cannot drift apart.
+"""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+# Only test spans carry test.outcome (job-root and setup spans don't), and only these
+# outcomes are flaky signal; plain 'passed'/'skipped' spans never reach any aggregation.
+SIGNAL_OUTCOMES = ["failed", "error", "rerun_passed", "xfailed"]
+
+# Scope to the CI test-timing emitter (report_test_timings.py sets this as service.name);
+# without it any team span carrying a test.outcome attribute would pollute.
+CI_SERVICE_NAME = "ci-backend"
+
+# Spans emitted before the owner stamp existed (or from paths with no owner) group here.
+UNOWNED_TEAM = "unowned"
+
+
+def flaky_bar(rerun_count: str, failed_pr_count: str) -> str:
+ """The one flaky-test qualification bar (SPEC §5): enough rerun passes OR enough distinct failed PRs."""
+ return f"{rerun_count} >= {{min_rerun_passes}} OR {failed_pr_count} >= {{min_failed_prs}}"
+
+
+# Scans [scan_from, date_to?]; `is_current` splits rows at {date_from} so a caller scanning
+# an extra prior window (scan_from < date_from) gets the current/prior split for free. A
+# caller without a prior window passes scan_from = date_from and ignores the column.
+_SCAN = """
+ SELECT
+ name AS nodeid,
+ attributes['test.selector'] AS selector,
+ attributes['test.outcome'] AS outcome,
+ coalesce(nullIf(attributes['test.owner_team'], ''), {unowned_team}) AS owner_team,
+ resource_attributes['ci.pr_number'] AS pr_number,
+ resource_attributes['ci.branch'] AS branch,
+ timestamp AS span_timestamp,
+ timestamp >= {date_from} AS is_current
+ FROM posthog.trace_spans
+ WHERE service_name = {service_name}
+ AND attributes['test.outcome'] IN {signal_outcomes}
+ AND lower(resource_attributes['ci.repository']) = lower({repository})
+ AND timestamp >= {scan_from}__DATE_TO__
+"""
+
+
+def span_scan(*, bounded: bool) -> str:
+ """The scan SELECT, with or without the upper time bound (some callers scan to now)."""
+ return _SCAN.replace("__DATE_TO__", " AND timestamp <= {date_to}" if bounded else "")
+
+
+def scan_placeholders(
+ *,
+ repository: str,
+ date_from: datetime,
+ scan_from: datetime | None = None,
+ date_to: datetime | None = None,
+) -> dict[str, ast.Expr]:
+ placeholders: dict[str, ast.Expr] = {
+ "service_name": ast.Constant(value=CI_SERVICE_NAME),
+ "signal_outcomes": ast.Constant(value=SIGNAL_OUTCOMES),
+ "unowned_team": ast.Constant(value=UNOWNED_TEAM),
+ "repository": ast.Constant(value=repository),
+ "date_from": ast.Constant(value=date_from),
+ "scan_from": ast.Constant(value=scan_from if scan_from is not None else date_from),
+ }
+ if date_to is not None:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+ return placeholders
+
+
+def selector_from_nodeid(nodeid: str) -> str:
+ """Best-effort runnable pytest selector for a span the CI reporter emitted before it stamped
+ ``test.selector``. The nodeid folds the file/class boundary into '/' and drops '.py'
+ ('posthog/api/test/test_x/TestX::test_y'); re-split on the convention that class segments are
+ CamelCase and everything before them is the module file. Newer spans skip this: they carry the
+ exact selector, built from JUnit's ``file`` where the boundary isn't guessed. Removable once every
+ in-retention span carries ``test.selector`` (i.e. the emitter has been live longer than Traces
+ retention).
+ """
+ class_path, sep, test_part = nodeid.partition("::")
+ if not sep or "/" not in class_path:
+ return nodeid
+ segments = class_path.split("/")
+ module_end = len(segments)
+ while module_end > 1 and segments[module_end - 1][:1].isupper():
+ module_end -= 1
+ module = "/".join(segments[:module_end]) + ".py"
+ return "::".join([module, *segments[module_end:], test_part])
diff --git a/products/engineering_analytics/backend/logic/queries/flaky_tests.py b/products/engineering_analytics/backend/logic/queries/flaky_tests.py
index b7a590125922..47ec58cef398 100644
--- a/products/engineering_analytics/backend/logic/queries/flaky_tests.py
+++ b/products/engineering_analytics/backend/logic/queries/flaky_tests.py
@@ -1,14 +1,13 @@
"""HogQL aggregation of per-test CI spans into a flaky-test leaderboard.
-Backend CI emits one OTel span per test into the Traces store (span name = reconstructed
-pytest nodeid, ``test.outcome`` / ``test.attempts`` span attributes, ``ci.*`` resource
-attributes — see ``.github/scripts/report_test_timings.py``). This groups the signal spans
-by nodeid over a window and ranks tests by flakiness signal.
+Embeds the shared per-test span scan (``_test_spans``, the one definition of the service
+fence, signal outcomes, and repository scoping) and groups the signal spans by nodeid over
+a window, ranking tests by flakiness signal.
Two data caveats shape the query:
- Passing tests under the emitter's duration threshold are dropped, while failures, errors,
- xfails, and reruns are always emitted — denominators are biased, so everything here is an
+ xfails, and reruns are always emitted, so denominators are biased and everything here is an
absolute count, never a rate.
- ``rerun_passed`` (pass-on-retry, the strongest flaky signal) only flows from lanes running
pytest with reruns enabled. Lanes without reruns surface a flake as a plain ``failed`` /
@@ -16,8 +15,7 @@ Two data caveats shape the query:
Ranking is ``rerun_passed_count + failed_pr_count``: reruns catch the rerun-enabled lanes,
distinct-PRs-hit catches the rest, and neither is inflated by one broken PR failing the same
-test on every push (that raises only ``failed_count``, the tiebreaker). Spans are scoped by
-``ci.repository`` so the selected GitHub source cannot mix signals from another repository.
+test on every push (that raises only ``failed_count``, the tiebreaker).
Reads the ``posthog.trace_spans`` table on the LOGS ClickHouse cluster, not the warehouse.
"""
@@ -30,16 +28,14 @@ from posthog.clickhouse.workload import Workload
from products.engineering_analytics.backend.facade.contracts import FlakyTestItem, FlakyTestList
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
-
-# Only test spans carry test.outcome (job-root and setup spans don't), and only these
-# outcomes are flaky signal — plain 'passed'/'skipped' spans never reach the aggregation.
-_SIGNAL_OUTCOMES = ["failed", "error", "rerun_passed", "xfailed"]
-
-# Scope the aggregation to the CI test-timing emitter (report_test_timings.py sets this as
-# service.name); without it any team span carrying a test.outcome attribute would pollute.
-_CI_SERVICE_NAME = "ci-backend"
-
-_SELECT = """
+from products.engineering_analytics.backend.logic.queries._test_spans import (
+ flaky_bar,
+ scan_placeholders,
+ selector_from_nodeid,
+ span_scan,
+)
+
+_SELECT = f"""
SELECT
nodeid,
anyIf(selector, selector != '') AS selector,
@@ -50,47 +46,14 @@ _SELECT = """
uniqIf(branch, branch != '') AS branch_count,
countIf(outcome = 'xfailed') AS xfailed_count,
max(span_timestamp) AS last_seen_at
- FROM (
- SELECT
- name AS nodeid,
- attributes['test.selector'] AS selector,
- attributes['test.outcome'] AS outcome,
- resource_attributes['ci.pr_number'] AS pr_number,
- resource_attributes['ci.branch'] AS branch,
- timestamp AS span_timestamp
- FROM posthog.trace_spans
- WHERE service_name = {service_name}
- AND attributes['test.outcome'] IN {signal_outcomes}
- AND lower(resource_attributes['ci.repository']) = lower({repository})
- AND timestamp >= {date_from} __DATE_TO__
- )
+ FROM (__SPAN_SCAN__)
GROUP BY nodeid
- HAVING rerun_passed_count >= {min_rerun_passes} OR failed_pr_count >= {min_failed_prs}
+ HAVING {flaky_bar("rerun_passed_count", "failed_pr_count")}
ORDER BY (rerun_passed_count + failed_pr_count) DESC, failed_count DESC, last_seen_at DESC
- LIMIT {limit_plus_one}
+ LIMIT {{limit_plus_one}}
"""
-def _selector_from_nodeid(nodeid: str) -> str:
- """Best-effort runnable pytest selector for a span the CI reporter emitted before it stamped
- ``test.selector``. The nodeid folds the file/class boundary into '/' and drops '.py'
- ('posthog/api/test/test_x/TestX::test_y'); re-split on the convention that class segments are
- CamelCase and everything before them is the module file. Newer spans skip this — they carry the
- exact selector, built from JUnit's ``file`` where the boundary isn't guessed. Removable once every
- in-retention span carries ``test.selector`` (i.e. the emitter has been live longer than Traces
- retention).
- """
- class_path, sep, test_part = nodeid.partition("::")
- if not sep or "/" not in class_path:
- return nodeid
- segments = class_path.split("/")
- module_end = len(segments)
- while module_end > 1 and segments[module_end - 1][:1].isupper():
- module_end -= 1
- module = "/".join(segments[:module_end]) + ".py"
- return "::".join([module, *segments[module_end:], test_part])
-
-
def query_flaky_tests(
*,
curated: CuratedGitHubSource,
@@ -107,22 +70,14 @@ def query_flaky_tests(
if not repository:
return FlakyTestList(items=[], truncated=False, limit=limit)
- date_to_clause = "AND timestamp <= {date_to}" if date_to is not None else ""
- placeholders: dict[str, ast.Expr] = {
- "service_name": ast.Constant(value=_CI_SERVICE_NAME),
- "signal_outcomes": ast.Constant(value=_SIGNAL_OUTCOMES),
- "repository": ast.Constant(value=repository),
- "date_from": ast.Constant(value=date_from),
- "min_rerun_passes": ast.Constant(value=min_rerun_passes),
- "min_failed_prs": ast.Constant(value=min_failed_prs),
- # +1 so a full page tells us more tests qualified than returned.
- "limit_plus_one": ast.Constant(value=limit + 1),
- }
- if date_to is not None:
- placeholders["date_to"] = ast.Constant(value=date_to)
+ placeholders = scan_placeholders(repository=repository, date_from=date_from, date_to=date_to)
+ placeholders["min_rerun_passes"] = ast.Constant(value=min_rerun_passes)
+ placeholders["min_failed_prs"] = ast.Constant(value=min_failed_prs)
+ # +1 so a full page tells us more tests qualified than returned.
+ placeholders["limit_plus_one"] = ast.Constant(value=limit + 1)
response = curated.run(
- _SELECT.replace("__DATE_TO__", date_to_clause),
+ _SELECT.replace("__SPAN_SCAN__", span_scan(bounded=date_to is not None)),
query_type="engineering_analytics.flaky_tests",
placeholders=placeholders,
# trace_spans lives on the LOGS ClickHouse cluster, not the warehouse default.
@@ -134,7 +89,7 @@ def query_flaky_tests(
FlakyTestItem(
nodeid=nodeid,
# Prefer the emitter's exact selector; reconstruct from the nodeid for older spans.
- selector=selector or _selector_from_nodeid(nodeid),
+ selector=selector or selector_from_nodeid(nodeid),
rerun_passed_count=rerun_passed_count,
failed_count=failed_count,
failed_pr_count=failed_pr_count,
diff --git a/products/engineering_analytics/backend/logic/queries/team_ci_health.py b/products/engineering_analytics/backend/logic/queries/team_ci_health.py
new file mode 100644
index 000000000000..b87840077ef1
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/team_ci_health.py
@@ -0,0 +1,192 @@
+"""HogQL rollups of per-test CI spans by owning team.
+
+Ownership is stamped on the spans at emission time: the CI reporter resolves each test's
+file path against the repo's ownership map (``products/*/product.yaml`` + CODEOWNERS) and
+sets ``test.owner_team``, so no server-side ownership map exists. Spans without a stamp
+aggregate under the literal team ``'unowned'``, an honest first-class bucket that surfaces
+ownership gaps instead of dropping them.
+
+Teams are organizational owners of code surfaces; nothing here aggregates by author
+(SPEC §2). Both queries share the flaky-tests caveats: sub-threshold passing runs are not
+emitted, so every figure is an absolute count over signal spans, never a rate.
+
+Reads the ``posthog.trace_spans`` table on the LOGS ClickHouse cluster, not the warehouse.
+"""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from posthog.clickhouse.workload import Workload
+
+from products.engineering_analytics.backend.facade.contracts import (
+ TeamCIActivity,
+ TeamCIHealthItem,
+ TeamCIHealthList,
+ TeamTestSignal,
+)
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._test_spans import (
+ flaky_bar,
+ scan_placeholders,
+ selector_from_nodeid,
+ span_scan,
+)
+
+# The shared span scan, bounded and scanning [scan_from, date_to] in one pass; `is_current`
+# splits the current window from its equal-length prior twin.
+_SPAN_SCAN = span_scan(bounded=True)
+
+_ROSTER_SELECT = f"""
+ SELECT
+ owner_team,
+ countIf({flaky_bar("rerun_current", "failed_prs_current")}) AS flaky_test_count,
+ countIf({flaky_bar("rerun_prior", "failed_prs_prior")}) AS flaky_test_count_prior,
+ sum(failed_current) AS failed_count,
+ sum(failed_prior) AS failed_count_prior,
+ sum(rerun_current) AS rerun_passed_count,
+ sum(rerun_prior) AS rerun_passed_count_prior,
+ sum(xfail_current) AS xfailed_count,
+ sum(xfail_prior) AS xfailed_count_prior,
+ max(last_seen) AS last_seen_at
+ FROM (
+ SELECT
+ owner_team,
+ nodeid,
+ countIf(outcome = 'rerun_passed' AND is_current) AS rerun_current,
+ countIf(outcome = 'rerun_passed' AND NOT is_current) AS rerun_prior,
+ countIf(outcome IN ('failed', 'error') AND is_current) AS failed_current,
+ countIf(outcome IN ('failed', 'error') AND NOT is_current) AS failed_prior,
+ countIf(outcome = 'xfailed' AND is_current) AS xfail_current,
+ countIf(outcome = 'xfailed' AND NOT is_current) AS xfail_prior,
+ uniqIf(pr_number, outcome IN ('failed', 'error') AND pr_number != '' AND is_current) AS failed_prs_current,
+ uniqIf(pr_number, outcome IN ('failed', 'error') AND pr_number != '' AND NOT is_current) AS failed_prs_prior,
+ max(span_timestamp) AS last_seen
+ FROM ({_SPAN_SCAN})
+ GROUP BY owner_team, nodeid
+ )
+ GROUP BY owner_team
+ ORDER BY (flaky_test_count + failed_count) DESC, (flaky_test_count_prior + failed_count_prior) DESC, owner_team ASC
+ LIMIT {{limit_plus_one}}
+"""
+
+_TEST_SIGNAL_SELECT = f"""
+ SELECT
+ nodeid,
+ anyIf(selector, selector != '') AS selector,
+ countIf(is_current AND outcome != 'xfailed') AS signal_count,
+ countIf(NOT is_current AND outcome != 'xfailed') AS signal_count_prior,
+ max(span_timestamp) AS last_seen_at
+ FROM ({_SPAN_SCAN})
+ WHERE owner_team = {{owner_team}}
+ GROUP BY nodeid
+ HAVING signal_count > 0 OR signal_count_prior > 0
+ ORDER BY greatest(signal_count, signal_count_prior) DESC, signal_count DESC, nodeid ASC
+ LIMIT {{test_limit_plus_one}}
+"""
+
+
+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)
+ return scan_placeholders(
+ repository=curated.repository, date_from=date_from, scan_from=prior_from, date_to=resolved_to
+ )
+
+
+def query_team_ci_health(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ min_rerun_passes: int,
+ min_failed_prs: int,
+ limit: int,
+) -> TeamCIHealthList:
+ # Fail closed, same as flaky_tests: without a repository identity another connected
+ # repo's spans would leak into this roster.
+ if not curated.repository:
+ return TeamCIHealthList(items=[], truncated=False, limit=limit)
+
+ placeholders = _window_placeholders(curated=curated, date_from=date_from, date_to=date_to)
+ placeholders["min_rerun_passes"] = ast.Constant(value=min_rerun_passes)
+ placeholders["min_failed_prs"] = ast.Constant(value=min_failed_prs)
+ placeholders["limit_plus_one"] = ast.Constant(value=limit + 1)
+
+ response = curated.run(
+ _ROSTER_SELECT,
+ query_type="engineering_analytics.team_ci_health",
+ placeholders=placeholders,
+ workload=Workload.LOGS,
+ )
+ rows = response.results or []
+ return TeamCIHealthList(
+ items=[
+ TeamCIHealthItem(
+ owner_team=owner_team,
+ flaky_test_count=flaky_test_count,
+ flaky_test_count_prior=flaky_test_count_prior,
+ failed_count=failed_count,
+ failed_count_prior=failed_count_prior,
+ rerun_passed_count=rerun_passed_count,
+ rerun_passed_count_prior=rerun_passed_count_prior,
+ xfailed_count=xfailed_count,
+ xfailed_count_prior=xfailed_count_prior,
+ last_seen_at=last_seen_at,
+ )
+ for (
+ owner_team,
+ flaky_test_count,
+ flaky_test_count_prior,
+ failed_count,
+ failed_count_prior,
+ rerun_passed_count,
+ rerun_passed_count_prior,
+ xfailed_count,
+ xfailed_count_prior,
+ last_seen_at,
+ ) in rows[:limit]
+ ],
+ truncated=len(rows) > limit,
+ limit=limit,
+ )
+
+
+def query_team_ci_activity(
+ *,
+ curated: CuratedGitHubSource,
+ owner_team: str,
+ date_from: datetime,
+ date_to: datetime | None,
+ test_limit: int,
+) -> TeamCIActivity:
+ if not curated.repository:
+ return TeamCIActivity(owner_team=owner_team, tests=[], truncated_tests=False)
+
+ placeholders = _window_placeholders(curated=curated, date_from=date_from, date_to=date_to)
+ placeholders["owner_team"] = ast.Constant(value=owner_team)
+
+ tests_response = curated.run(
+ _TEST_SIGNAL_SELECT,
+ query_type="engineering_analytics.team_ci_activity_tests",
+ placeholders={**placeholders, "test_limit_plus_one": ast.Constant(value=test_limit + 1)},
+ workload=Workload.LOGS,
+ )
+ test_rows = tests_response.results or []
+ return TeamCIActivity(
+ owner_team=owner_team,
+ tests=[
+ TeamTestSignal(
+ nodeid=nodeid,
+ selector=selector or selector_from_nodeid(nodeid),
+ signal_count=signal_count,
+ signal_count_prior=signal_count_prior,
+ last_seen_at=last_seen_at,
+ )
+ for nodeid, selector, signal_count, signal_count_prior, last_seen_at in test_rows[:test_limit]
+ ],
+ truncated_tests=len(test_rows) > test_limit,
+ )
diff --git a/products/engineering_analytics/backend/logic/queries/team_merge_trend.py b/products/engineering_analytics/backend/logic/queries/team_merge_trend.py
new file mode 100644
index 000000000000..d07696ee3985
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/team_merge_trend.py
@@ -0,0 +1,74 @@
+"""Curated query: a team's daily time-to-merge trend via GitHub org team membership.
+
+Attributes merged PRs to a team through the ``team_members`` warehouse snapshot (PR author
+login → GitHub team slug), the one sanctioned place member data feeds a team surface. Only
+team-level aggregates leave this module (the daily median and average of the team's own
+merges): no per-member figures, no cross-team rankings (SPEC §2/§7). Bots are excluded per
+the default bot rule.
+
+The GitHub team slug and the ownership-map slug (``test.owner_team``) are two namespaces
+matched by exact slug. A team whose GitHub slug differs from its ownership slug gets no
+membership rows (an empty series), never another team's data. Time-to-merge is the coarse
+``open_to_merge_seconds`` (SPEC §7).
+"""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import TeamMergeTrend, TeamMergeTrendPoint
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
+
+_SELECT = """
+ SELECT
+ toStartOfDay(pr.merged_at) AS day,
+ median(pr.open_to_merge_seconds) AS median_seconds,
+ avg(pr.open_to_merge_seconds) AS average_seconds,
+ count() AS merged_count
+ FROM __PR_SOURCE__ AS pr
+ WHERE pr.merged_at IS NOT NULL
+ AND pr.merged_at >= {date_from}
+ AND pr.merged_at <= {date_to}
+ AND NOT pr.is_bot
+ AND pr.author_handle IN (SELECT member_handle FROM members)
+ GROUP BY day
+ ORDER BY day ASC
+"""
+
+
+def query_team_merge_trend(
+ *,
+ curated: CuratedGitHubSource,
+ owner_team: str,
+ date_from: datetime,
+ date_to: datetime | None,
+) -> TeamMergeTrend:
+ members_source = curated.members_source()
+ if members_source is None:
+ # The membership snapshot isn't synced, so there is no honest team attribution: return
+ # the flag instead of an empty series that implies the team merged nothing.
+ return TeamMergeTrend(owner_team=owner_team, has_membership_data=False, points=[])
+
+ sql = f"WITH members AS (SELECT member_handle FROM {members_source} WHERE team_slug = {{owner_team}}) {_SELECT}"
+ response = curated.run(
+ sql.replace("__PR_SOURCE__", curated.pr_source()),
+ query_type="engineering_analytics.team_merge_trend",
+ placeholders={
+ "owner_team": ast.Constant(value=owner_team),
+ "date_from": ast.Constant(value=date_from),
+ "date_to": ast.Constant(value=date_to or datetime.now(tz=date_from.tzinfo)),
+ },
+ )
+ return TeamMergeTrend(
+ owner_team=owner_team,
+ has_membership_data=True,
+ points=[
+ TeamMergeTrendPoint(
+ day=day,
+ median_seconds=opt_float(median_seconds),
+ average_seconds=opt_float(average_seconds),
+ merged_count=merged_count,
+ )
+ for (day, median_seconds, average_seconds, merged_count) in (response.results or [])
+ ],
+ )
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index fc394ddb15fd..6256274f6fd5 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -41,6 +41,10 @@ WORKFLOW_RUNS_SCHEMA = "workflow_runs"
# Job-level CI (queue time, per-job duration, runner tier). Optional — the source/sync lands
# separately, so reads must degrade gracefully (no jobs) rather than require it like the pair above.
WORKFLOW_JOBS_SCHEMA = "workflow_jobs"
+# GitHub org team membership (login → team slug), the author→team key behind team-level merge
+# timing. Optional and off by default at the source (needs the org Members:Read grant), so reads
+# must degrade gracefully (no membership data) exactly like workflow_jobs.
+TEAM_MEMBERS_SCHEMA = "team_members"
# Resolved names are interpolated into HogQL ``FROM`` clauses. Warehouse table names are
# always plain identifiers (the prefix is validated to ``[A-Za-z0-9_]`` at connect time and
@@ -57,6 +61,8 @@ class GitHubTables:
workflow_runs: str
# Optional: present only once the job-level source is synced; None means "no jobs data".
workflow_jobs: str | None = None
+ # Optional: present only once org team membership is synced; None means "no membership data".
+ team_members: str | None = None
# Used to scope cross-store reads such as CI traces to the selected source's repository.
repository: str = ""
@@ -105,11 +111,13 @@ def resolve_github_tables(
# backfilling) instead of degrading to PRs-without-CI. Relaxing this to a graceful
# PR-only mode (null CI columns) is a deliberate future change, not handled here.
if pull_requests and workflow_runs:
- # workflow_jobs is optional — included when synced, None otherwise (jobs degrade to empty).
+ # workflow_jobs / team_members are optional: included when synced, None otherwise
+ # (jobs degrade to empty, membership-keyed reads degrade to "no membership data").
return GitHubTables(
pull_requests=pull_requests,
workflow_runs=workflow_runs,
workflow_jobs=tables.get(WORKFLOW_JOBS_SCHEMA),
+ team_members=tables.get(TEAM_MEMBERS_SCHEMA),
repository=_source_repository(source),
)
if source_id is not None:
@@ -233,7 +241,7 @@ def _synced_table_names(*, team: Team, source: ExternalDataSource) -> dict[str,
team_id=team.pk,
source_id=source.id,
should_sync=True,
- name__in=(PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA),
+ name__in=(PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA, TEAM_MEMBERS_SCHEMA),
)
.exclude(deleted=True)
.select_related("table")
diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.py
index 7da2737084b2..621423b21ca2 100644
--- a/products/engineering_analytics/backend/logic/views/source_schema.py
+++ b/products/engineering_analytics/backend/logic/views/source_schema.py
@@ -78,3 +78,15 @@ WORKFLOW_JOBS_COLUMNS: dict[str, dict[str, str]] = {
"completed_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
"steps": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
}
+
+# Contract for the ``github_team_members`` warehouse source (org team membership). Member rows
+# are GitHub user objects with the parent team's identity injected by the source fan-out
+# (``team_id`` / ``team_slug`` / ``team_name``); ``login`` + ``team_slug`` are the join keys the
+# membership-based merge timing reads. Same Nullable discipline as above.
+TEAM_MEMBERS_COLUMNS: dict[str, dict[str, str]] = {
+ "id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
+ "login": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ "team_id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
+ "team_slug": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ "team_name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+}
diff --git a/products/engineering_analytics/backend/logic/views/team_members.py b/products/engineering_analytics/backend/logic/views/team_members.py
new file mode 100644
index 000000000000..4f6f5e172758
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/views/team_members.py
@@ -0,0 +1,22 @@
+"""Curated GitHub org team-membership query builder.
+
+Maps the raw ``team_members`` warehouse snapshot (GitHub member user objects with the
+parent team's identity injected by the source's fan-out) into the two columns the
+membership join needs: the member's login and the GitHub team slug. This is the only
+place membership columns are mapped; the table name is resolved per-team and passed in
+(see ``logic.sources``), never hardcoded.
+
+The snapshot lands every column ``Nullable`` (see ``source_schema.py``), so each read
+is ``ifNull``-guarded to keep the curated columns non-null strings. Rows without a login
+are dropped: an empty ``member_handle`` would match deleted-account PR authors.
+"""
+
+
+def build_query(table_name: str) -> str:
+ return f"""
+ SELECT
+ ifNull(login, '') AS member_handle,
+ ifNull(team_slug, '') AS team_slug
+ FROM {table_name}
+ WHERE ifNull(login, '') != ''
+ """
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 f4cfadd700a6..2178fe65b4a2 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -36,17 +36,23 @@ from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
from posthog.models import Team
from posthog.models.scoping import team_scope
from posthog.storage import object_storage
+from products.engineering_analytics.backend.logic.queries._test_spans import CI_SERVICE_NAME
from products.engineering_analytics.backend.logic.sources import (
PULL_REQUESTS_SCHEMA,
+ TEAM_MEMBERS_SCHEMA,
WORKFLOW_JOBS_SCHEMA,
WORKFLOW_RUNS_SCHEMA,
)
+from products.engineering_analytics.backend.logic.views.pull_requests import KNOWN_BOT_HANDLES
from products.engineering_analytics.backend.logic.views.source_schema import (
PULL_REQUESTS_COLUMNS,
+ TEAM_MEMBERS_COLUMNS,
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
@@ -196,11 +202,16 @@ def _fixture_anchor(prs: list[dict[str, Any]], runs: list[dict[str, Any]]) -> da
return newest + timedelta(hours=1)
+# Merged PRs re-spread across two weeks so the 14d merge-trend and cost-per-merge charts have a
+# point in every bucket.
+_MERGE_SPREAD_DAYS = 14
+
# Synthetic default-branch commit stream: the captured snapshot holds only ~a dozen master SHAs, which
# draws the master-health scatter as a near-empty chart. Deterministic (index arithmetic, no random),
# local-seed only; SHAs are prefixed "aa57e2" so they read as seeded in the UI.
_MASTER_WORKFLOWS = ("Backend CI", "Frontend CI", "Rust CI", "E2E Tests", "Lint", "Storybook")
-_MASTER_DAYS = 7
+# Co-windowed with the merge spread: a day with merges but no seeded job cost would chart as $0/merge.
+_MASTER_DAYS = _MERGE_SPREAD_DAYS
_MASTER_COMMITS_PER_DAY = 18
@@ -251,19 +262,20 @@ def _demo_master_commits(anchor: datetime) -> list[dict[str, Any]]:
def _spread_merges(prs: list[dict[str, Any]], anchor: datetime) -> None:
- # The snapshot captured recently-updated PRs, so their merge times all cluster on the capture day —
- # the cost-per-merge trend then collapses into a single bucket. Re-spread merged PRs evenly across
- # the seeded window (deterministic, index arithmetic) so the trend has a divisor in every bucket.
- span_hours = _MASTER_DAYS * 24
+ # The snapshot captured recently-updated PRs, so their merge times all cluster on the capture day
+ # and the cost-per-merge and time-to-merge trends collapse into a single bucket. Re-spread merged
+ # PRs evenly across the seeded window and derive created_at backwards from a realistic duration mix
+ # (mostly hours-to-two-days, an occasional week-long tail); clamping merged_at forward against the
+ # snapshot's created_at instead would pile every merge on the capture day at a constant duration.
+ span_hours = _MERGE_SPREAD_DAYS * 24
merged = [pr for pr in prs if pr.get("merged_at")]
for index, pr in enumerate(merged):
merged_at = anchor - timedelta(hours=(index * 11) % span_hours, minutes=(index * 13) % 60)
- created_raw = pr.get("created_at")
- if created_raw:
- created = datetime.fromisoformat(created_raw)
- if merged_at < created:
- merged_at = created + timedelta(hours=1)
+ open_hours = 3 + (index * 17) % 45 # 3h–2d for most PRs...
+ if index % 9 == 4:
+ open_hours += 24 * (2 + index % 5) # ...with a 2–6 day review tail on some
pr["merged_at"] = merged_at.strftime("%Y-%m-%dT%H:%M:%SZ")
+ pr["created_at"] = (merged_at - timedelta(hours=open_hours)).strftime("%Y-%m-%dT%H:%M:%SZ")
def _demo_multi_push(
@@ -320,6 +332,399 @@ def _demo_multi_push(
return demo_pr, demo_runs
+# Synthetic per-test CI spans for the flaky-test and team CI health surfaces (they read
+# posthog.trace_spans, not the warehouse). Each team gets a distinct trend shape so the
+# roster deltas, daily trend, and before/after slope all have something honest to show.
+# Deterministic (index arithmetic, no random); trace ids are prefixed 'engseed-' so
+# re-seeding can delete exactly its own rows.
+_SPAN_TRACE_PREFIX = "engseed"
+_SPAN_DAYS = 28 # 14-day current window + its equal-length prior twin
+
+# (owner_team, module_dir, [(TestClass, test_name, prior_daily, current_daily)]).
+# prior/current_daily are signal spans per day in each half of the window; 0 = quiet.
+# The roster is every distinct owner slug in the repo's ownership files (owners.yaml +
+# products/*/product.yaml, the same map the CI emitter stamps from) as of July 2026, so
+# the team surfaces demo against the real org. Module dirs are real test directories.
+_SPAN_TEAMS: list[tuple[str, str, list[tuple[str, str, int, int]]]] = [
+ (
+ "team-replay", # worsening: signal doubles in the current window
+ "posthog/session_recordings/test",
+ [
+ ("TestSessionRecordings", "test_snapshot_batching", 2, 5),
+ ("TestRecordingPlaylists", "test_playlist_counts_converge", 1, 3),
+ ("TestRetentionSweeper", "test_ttl_boundary_day", 0, 2),
+ ],
+ ),
+ (
+ "batch-exports", # high and flat: the standing offender
+ "products/batch_exports/backend/tests",
+ [
+ ("TestSnowflakeExport", "test_incremental_primary_key_resume", 4, 4),
+ ("TestBigQueryExport", "test_backfill_window_overlap", 3, 3),
+ ("TestTemporalWorkflows", "test_teardown_cancellation", 2, 3),
+ ("TestS3Export", "test_multipart_retry", 2, 2),
+ ],
+ ),
+ (
+ "team-ingestion", # improving: signal halves in the current window
+ "posthog/models/test",
+ [
+ ("TestPersonMerges", "test_concurrent_merge_ordering", 4, 1),
+ ("TestKafkaConsumer", "test_rebalance_offset_commit", 3, 1),
+ ],
+ ),
+ (
+ "conversations", # spiky: quiet prior, a current-window burst
+ "products/conversations/backend/api/tests",
+ [
+ ("TestTicketRouting", "test_assignment_race", 0, 4),
+ ],
+ ),
+ (
+ "team-experiments", # recovered: prior signal only, lands at zero current
+ "products/experiments/backend/test",
+ [
+ ("TestExperimentResults", "test_bayesian_interval_rounding", 3, 0),
+ ("TestFeatureFlagRollout", "test_variant_bucketing_stability", 2, 0),
+ ],
+ ),
+ (
+ "team-error-tracking", # brand new flake: current window only
+ "products/error_tracking/backend/tests",
+ [
+ ("TestIssueGrouping", "test_fingerprint_collision", 0, 3),
+ ],
+ ),
+ (
+ "team-data-tools", # mildly worsening
+ "posthog/hogql/test",
+ [
+ ("TestHogQLParser", "test_lambda_scope_resolution", 2, 3),
+ ("TestHogQLPrinter", "test_materialized_column_rewrite", 1, 1),
+ ],
+ ),
+ (
+ "team-workflows", # mildly worsening
+ "products/cdp/backend/test",
+ [
+ ("TestHogFunctions", "test_retry_backoff_jitter", 2, 3),
+ ("TestDestinationFilters", "test_event_property_globs", 1, 1),
+ ],
+ ),
+ (
+ "team-product-analytics", # mildly improving
+ "posthog/hogql_queries/insights/test",
+ [
+ ("TestTrendsQueryRunner", "test_interval_boundary_timezone", 3, 2),
+ ("TestFunnelCorrelation", "test_person_property_breakdown", 1, 1),
+ ],
+ ),
+ (
+ "team-platform-features", # mildly improving
+ "products/access_control/backend/tests",
+ [
+ ("TestAccessControl", "test_role_membership_cache_invalidation", 2, 1),
+ ("TestOrgInvites", "test_invite_expiry_race", 1, 1),
+ ],
+ ),
+ (
+ "team-ai-observability", # mildly improving
+ "products/ai_observability/backend/test",
+ [
+ ("TestGenerationCosts", "test_cost_property_rollup", 2, 1),
+ ("TestTraceIngestion", "test_span_attribute_truncation", 1, 1),
+ ],
+ ),
+ (
+ "team-surveys", # mildly improving
+ "products/surveys/backend/api/test",
+ [
+ ("TestSurveyTargeting", "test_adaptive_sampling_rate", 2, 1),
+ ],
+ ),
+ (
+ "team-warehouse-sources", # flat
+ "products/warehouse_sources/backend/tests",
+ [
+ ("TestStripeSource", "test_incremental_cursor_persistence", 2, 2),
+ ("TestSourceSchemaSync", "test_nullable_json_columns", 1, 1),
+ ],
+ ),
+ (
+ "team-analytics-platform", # flat
+ "products/dashboards/backend/test",
+ [
+ ("TestDashboardTiles", "test_tile_refresh_debounce", 2, 2),
+ ("TestAlertChecks", "test_threshold_hysteresis", 1, 1),
+ ],
+ ),
+ (
+ "team-web-analytics", # one flake fixed, one steady
+ "products/web_analytics/backend/test",
+ [
+ ("TestWebOverview", "test_preaggregated_table_parity", 2, 2),
+ ("TestChannelType", "test_utm_priority_order", 1, 0),
+ ],
+ ),
+ (
+ "team-feature-flags", # one flake fixed, one steady
+ "products/feature_flags/backend/test",
+ [
+ ("TestFlagMatching", "test_local_evaluation_consistency", 2, 2),
+ ("TestFlagDependencies", "test_cohort_flag_cycle", 1, 0),
+ ],
+ ),
+ (
+ "team-self-driving", # creeping up
+ "products/signals/backend/test",
+ [
+ ("TestSignalEmission", "test_dedupe_window_replay", 1, 2),
+ ("TestInboxRouting", "test_scout_finding_grouping", 0, 1),
+ ],
+ ),
+ (
+ "team-agents", # creeping up
+ "products/agent_platform/backend/tests",
+ [
+ ("TestAgentRuns", "test_tool_call_stream_resume", 1, 2),
+ ],
+ ),
+ (
+ "team-managed-warehouse", # creeping up
+ "products/data_warehouse/backend/tests",
+ [
+ ("TestSavedQueryMaterialization", "test_incremental_refresh_watermark", 1, 2),
+ ],
+ ),
+ (
+ "team-posthog-code", # creeping up
+ "products/tasks/backend/tests",
+ [
+ ("TestTaskSandbox", "test_worktree_cleanup_on_cancel", 1, 2),
+ ],
+ ),
+ (
+ "team-devex", # low and flat
+ "products/engineering_analytics/backend/tests",
+ [
+ ("TestCIViews", "test_workflow_health_window", 1, 1),
+ ],
+ ),
+ (
+ "clickhouse", # low and flat
+ "posthog/clickhouse/test",
+ [
+ ("TestSchemaMigrations", "test_replicated_table_settings", 1, 1),
+ ],
+ ),
+ (
+ "logs", # low and flat
+ "products/logs/backend/test",
+ [
+ ("TestLogsQuery", "test_attribute_map_filter", 1, 1),
+ ],
+ ),
+ (
+ "team-billing", # low and flat
+ "ee/billing/test",
+ [
+ ("TestQuotaLimiting", "test_overage_grace_window", 1, 1),
+ ],
+ ),
+ (
+ "team-data-modeling", # low and flat
+ "products/data_modeling/backend/tests",
+ [
+ ("TestSavedQueryDAG", "test_cyclic_dependency_rejection", 1, 1),
+ ],
+ ),
+ (
+ "team-data-stack", # low and flat
+ "posthog/dags/tests",
+ [
+ ("TestDagsterAssets", "test_partition_backfill_window", 1, 1),
+ ],
+ ),
+ (
+ "team-growth", # low and flat
+ "products/growth/backend/tests",
+ [
+ ("TestOnboardingFunnel", "test_activation_email_dedupe", 1, 1),
+ ],
+ ),
+ (
+ "team-ai-gateway", # recovered small
+ "services/llm-gateway/tests",
+ [
+ ("TestProviderFailover", "test_anthropic_fallback_order", 1, 0),
+ ],
+ ),
+ (
+ "team-ai-research", # recovered small
+ "ee/hogai/test",
+ [
+ ("TestMemoryCompaction", "test_context_window_eviction", 1, 0),
+ ],
+ ),
+ (
+ "team-mcp-analytics", # brand new, small
+ "products/mcp_analytics/backend/tests",
+ [
+ ("TestMcpToolEvents", "test_tool_call_attribution", 0, 1),
+ ],
+ ),
+ (
+ "", # unstamped spans: the honest 'unowned' bucket
+ "posthog/api/test",
+ [
+ ("TestSharedMiddleware", "test_csrf_exempt_paths", 2, 2),
+ ("TestLegacyEndpoints", "test_deprecated_capture_shim", 1, 1),
+ ],
+ ),
+]
+
+
+# Synthetic merged-PR stream: the captured snapshot holds only ~115 merges, which spreads to
+# well under one merge per team-day across the 30-team roster, too thin for the per-team
+# merge-timing chart (a day with fewer than 3 merges has median == average by definition, so
+# the two lines would always coincide). Real PostHog/posthog merges ~40 PRs a day, so the
+# stream also makes repo-wide merge volume honest. Deterministic; numbered from 90000 and
+# titled "seeded:" so rows read as seeded in the UI. Timing/durations come from _spread_merges,
+# which rewrites every merged PR's merged_at/created_at anyway.
+_DEMO_MERGES_PER_DAY = 40
+
+
+def _demo_merged_prs(prs: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ logins = sorted({(pr.get("user") or {}).get("login") or "" for pr in prs} - {""})
+ authors = [login for login in logins if not login.endswith("[bot]") and login not in KNOWN_BOT_HANDLES]
+ template_ts = next(pr["created_at"] for pr in prs if pr.get("created_at"))
+ rows: list[dict[str, Any]] = []
+ for index in range(_DEMO_MERGES_PER_DAY * _MERGE_SPREAD_DAYS):
+ number = 90_000 + index
+ rows.append(
+ {
+ "id": 9_910_000_000 + index,
+ "number": number,
+ "title": f"seeded: merged PR {number}",
+ "state": "closed",
+ "draft": False,
+ # Placeholder timestamps inside the fixture's range (so the rebase anchor is
+ # unchanged); _spread_merges rewrites created_at/merged_at deterministically.
+ "created_at": template_ts,
+ "updated_at": template_ts,
+ "merged_at": template_ts,
+ "closed_at": template_ts,
+ "user": {"login": authors[index % len(authors)], "avatar_url": ""},
+ "head": {"sha": f"seed{index:04d}" + "a" * 32, "ref": f"seed/pr-{number}"},
+ "base": {"ref": "master", "repo": {"full_name": SEED_REPOSITORY}},
+ "labels": [],
+ }
+ )
+ return rows
+
+
+# GitHub org team membership for the merge-trend join (PR author login → team slug). Fixture
+# authors are assigned deterministically across the roster teams (no random, stable between
+# runs); local-seed only, so the mapping is synthetic: it exists to light up the per-team
+# time-to-merge chart against real PR merge data.
+_GITHUB_TEAM_SLUGS = [slug for slug, _, _ in _SPAN_TEAMS if slug]
+
+
+def _team_membership_rows(prs: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ merged_counts: dict[str, int] = {}
+ for pr in prs:
+ login = (pr.get("user") or {}).get("login") or ""
+ if login:
+ merged_counts[login] = merged_counts.get(login, 0) + (1 if pr.get("merged_at") else 0)
+ # Deal authors across teams round-robin in merge-volume order, so every team gets a share of
+ # active mergers instead of hash luck leaving some team lines empty. Scattered extra
+ # memberships mirror how org teams really overlap and thicken each team's series enough that
+ # days see 3+ merges; below that, a day's median and average are mathematically identical
+ # and the trend's two lines would always coincide.
+ logins = sorted(merged_counts, key=lambda login: (-merged_counts[login], login))
+ team_count = len(_GITHUB_TEAM_SLUGS)
+ rows: list[dict[str, Any]] = []
+ for member_index, login in enumerate(logins):
+ primary = member_index % team_count
+ memberships = (primary, (member_index * 7 + 3) % team_count, (member_index * 13 + 11) % team_count)
+ for slot, team_index in enumerate(memberships):
+ if slot and team_index in memberships[:slot]:
+ continue
+ slug = _GITHUB_TEAM_SLUGS[team_index]
+ rows.append(
+ {
+ "id": 900_000 + member_index,
+ "login": login,
+ "team_id": team_index + 1,
+ "team_slug": slug,
+ "team_name": slug.removeprefix("team-").replace("-", " ").title(),
+ }
+ )
+ return rows
+
+
+def _seed_trace_spans(team: Team) -> int:
+ anchor = timezone.now().replace(microsecond=0)
+ rows: list[str] = []
+ span_index = 0
+ for owner_team, module_dir, tests in _SPAN_TEAMS:
+ for test_index, (test_class, test_name, prior_daily, current_daily) in enumerate(tests):
+ module = test_name
+ nodeid = f"{module_dir}/{module}/{test_class}::{test_name}"
+ selector = f"{module_dir}/{module}.py::{test_class}::{test_name}"
+ for day in range(_SPAN_DAYS):
+ is_current = day >= _SPAN_DAYS // 2
+ daily = current_daily if is_current else prior_daily
+ # ±1 wobble so trends read organic, never below zero.
+ daily = max(0, daily + ((day * 7 + test_index * 3) % 3) - 1)
+ for occurrence in range(daily):
+ span_index += 1
+ # Mix of outcomes: retries dominate, with failures (PR-attributed and
+ # master) and the occasional quarantined-but-failing xfail.
+ cycle = (day + occurrence + test_index) % 5
+ if cycle < 2:
+ outcome, pr, branch = "rerun_passed", f"{7000 + (day * 13 + occurrence * 7) % 400}", ""
+ elif cycle < 4:
+ outcome, pr, branch = "failed", f"{7000 + (day * 17 + occurrence * 11) % 400}", ""
+ elif cycle == 4 and test_index % 2 == 0:
+ outcome, pr, branch = "error", "", "master"
+ else:
+ outcome, pr, branch = "xfailed", "", "master"
+ branch = branch or f"feat/{(module_dir.split('/')[1] if '/' in module_dir else 'core')}-{pr}"
+ ts = (anchor - timedelta(days=_SPAN_DAYS - 1 - day, hours=(span_index * 5) % 23)).strftime(_TS_FMT)
+ attr_pairs = [f"'test.outcome__str', '{outcome}'", f"'test.selector__str', '{selector}'"]
+ if owner_team:
+ attr_pairs.append(f"'test.owner_team__str', '{owner_team}'")
+ resource_pairs = [f"'ci.repository', '{SEED_REPOSITORY}'", f"'ci.branch', '{branch}'"]
+ if pr:
+ resource_pairs.append(f"'ci.pr_number', '{pr}'")
+ rows.append(
+ f"('{_SPAN_TRACE_PREFIX}-{span_index:06d}', {team.pk}, "
+ f"'{_SPAN_TRACE_PREFIX}-trace-{span_index}', 'span-{span_index}', 'parent', "
+ f"'{nodeid}', 1, '{ts}', '{ts}', '{ts}', 0, '{CI_SERVICE_NAME}', "
+ f"map({', '.join(attr_pairs)}), map({', '.join(resource_pairs)}))"
+ )
+
+ # Local dev has no traces provisioning (prod creates these on the LOGS cluster via HCL);
+ # both DDLs are CREATE TABLE IF NOT EXISTS, so this is a no-op on a stack that has them.
+ sync_execute(TRACE_SPANS_TABLE_SQL())
+ sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
+
+ # Replace only this seed's spans; a real traces table on the same dev stack is untouched.
+ # ALTER DELETE (not lightweight DELETE): the table has projections, which reject the latter.
+ sync_execute(
+ f"ALTER TABLE trace_spans DELETE WHERE team_id = %(team_id)s AND trace_id LIKE '{_SPAN_TRACE_PREFIX}-%%' "
+ "SETTINGS mutations_sync = 1",
+ {"team_id": team.pk},
+ )
+ sync_execute(
+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "
+ "timestamp, end_time, observed_timestamp, status_code, service_name, attributes_map_str, "
+ "resource_attributes) VALUES " + ",".join(rows)
+ )
+ return len(rows)
+
+
def _warehouse_endpoint() -> str:
# ClickHouse runs in docker, so a localhost object-storage endpoint must be
# rewritten to the docker host (same approach as the demo data generator).
@@ -368,6 +773,8 @@ class Command(BaseCommand):
prs = self._load_fixture(options["fixture_dir"], "github_pull_requests.json")
runs = self._load_fixture(options["fixture_dir"], "github_workflow_runs.json")
+ # Synthetic merged-PR stream so per-team merge timing has realistic daily volume.
+ prs.extend(_demo_merged_prs(prs))
# Append a synthetic multi-push PR (the fixture has none rich enough to show the progression).
demo_pr, demo_runs = _demo_multi_push(prs, runs)
prs.append(demo_pr)
@@ -405,6 +812,18 @@ class Command(BaseCommand):
self._upsert_schema_table(
team, source, credential, prefix, WORKFLOW_JOBS_SCHEMA, WORKFLOW_JOBS_COLUMNS, jobs
)
+ # Synthetic author→team membership backing the per-team time-to-merge trend.
+ self._upsert_schema_table(
+ team, source, credential, prefix, TEAM_MEMBERS_SCHEMA, TEAM_MEMBERS_COLUMNS, _team_membership_rows(prs)
+ )
+
+ # Per-test CI spans back the flaky-test leaderboard and the team CI health surfaces.
+ # Best-effort: a dev stack without the traces table still gets the warehouse seed.
+ try:
+ span_count = _seed_trace_spans(team)
+ self.stdout.write(f"Seeded {span_count} per-test CI spans into trace_spans (flaky/team surfaces).")
+ except Exception as exc:
+ self.stdout.write(self.style.WARNING(f"Skipped trace_spans seed (traces table unavailable?): {exc}"))
self.stdout.write(
self.style.SUCCESS(
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 54b48ee4d0cf..349901234a01 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -43,6 +43,12 @@ from products.engineering_analytics.backend.facade.contracts import (
RepoRef,
RunCost,
RunFailureLogs,
+ TeamCIActivity,
+ TeamCIHealthItem,
+ TeamCIHealthList,
+ TeamMergeTrend,
+ TeamMergeTrendPoint,
+ TeamTestSignal,
TimeToGreenBucket,
WorkflowCost,
WorkflowHealthBucket,
@@ -455,6 +461,119 @@ class FlakyTestListSerializer(DataclassSerializer):
}
+class TeamCIHealthItemSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = TeamCIHealthItem
+ extra_kwargs = {
+ "owner_team": {
+ "help_text": "Owning team slug (the CODEOWNERS handle minus '@PostHog/', e.g. 'team-replay'), "
+ "or the literal 'unowned' for tests whose spans carry no ownership stamp.",
+ },
+ "flaky_test_count": {
+ "help_text": "Owned tests meeting the flaky-leaderboard bar in the window (passed on retry "
+ "or failed on enough distinct PRs). Compare with flaky_test_count_prior for the delta.",
+ },
+ "flaky_test_count_prior": {
+ "help_text": "Same count over the equal-length window immediately before date_from.",
+ },
+ "failed_count": {
+ "help_text": "Signal spans on owned tests with final outcome 'failed' or 'error' in the "
+ "window. An absolute count, not a rate: fast passing runs are not emitted.",
+ },
+ "failed_count_prior": {"help_text": "Same count over the prior window."},
+ "rerun_passed_count": {
+ "help_text": "Spans on owned tests that failed, then passed on an automatic retry, the "
+ "strongest flaky signal. Only rerun-enabled CI lanes emit it.",
+ },
+ "rerun_passed_count_prior": {"help_text": "Same count over the prior window."},
+ "xfailed_count": {
+ "help_text": "Spans on owned tests that failed while quarantined (xfail): masked in CI "
+ "but still flaky.",
+ },
+ "xfailed_count_prior": {"help_text": "Same count over the prior window."},
+ "last_seen_at": {"help_text": "Most recent signal span across the team's owned tests, either window."},
+ }
+
+
+class TeamCIHealthListSerializer(DataclassSerializer):
+ items = TeamCIHealthItemSerializer(
+ many=True,
+ help_text="Owning teams ranked by current flaky + failure signal, heaviest first, capped at `limit`. "
+ "Teams are organizational owners of code surfaces; this never aggregates by author.",
+ )
+
+ class Meta:
+ dataclass = TeamCIHealthList
+ extra_kwargs = {
+ "truncated": {"help_text": "True when more teams had signal than the cap."},
+ "limit": {"help_text": "Maximum number of teams returned in `items`."},
+ }
+
+
+class TeamTestSignalSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = TeamTestSignal
+ extra_kwargs = {
+ "nodeid": {"help_text": "Reconstructed pytest nodeid (the CI span name), a stable grouping key."},
+ "selector": {"help_text": "Runnable pytest selector; exact when the CI reporter emitted it."},
+ "signal_count": {
+ "help_text": "Failed + error + pass-on-retry spans in the current window (xfail excluded).",
+ },
+ "signal_count_prior": {"help_text": "Same count over the equal-length window before date_from."},
+ "last_seen_at": {"help_text": "Most recent signal span for this test, either window."},
+ }
+
+
+class TeamCIActivitySerializer(DataclassSerializer):
+ tests = TeamTestSignalSerializer(
+ many=True,
+ help_text="The team's owned tests with signal in either window, ranked by the stronger window's count "
+ "(the current-vs-prior pairs behind a before/after comparison).",
+ )
+
+ class Meta:
+ dataclass = TeamCIActivity
+ extra_kwargs = {
+ "owner_team": {"help_text": "The team slug this activity is scoped to, or 'unowned'."},
+ "truncated_tests": {"help_text": "True when more owned tests had signal than the test cap."},
+ }
+
+
+class TeamMergeTrendPointSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = TeamMergeTrendPoint
+ extra_kwargs = {
+ "day": {"help_text": "Start of the day bucket (team timezone), keyed on merged_at."},
+ "median_seconds": {
+ "help_text": "Median open→merge seconds of the PRs this team's members merged that day; "
+ "null on a day the team merged nothing.",
+ },
+ "average_seconds": {
+ "help_text": "Average open→merge seconds over the same merges; diverges above the median "
+ "when a few long-running PRs drag the mean. Null on a day the team merged nothing.",
+ },
+ "merged_count": {"help_text": "Merged PRs behind that day's median and average."},
+ }
+
+
+class TeamMergeTrendSerializer(DataclassSerializer):
+ points = TeamMergeTrendPointSerializer(
+ many=True,
+ help_text="Daily median and average open→merge over the PRs this team's members merged, ascending "
+ "by day. Coarse timing (open→merge combines draft and review time); bots excluded.",
+ )
+
+ class Meta:
+ dataclass = TeamMergeTrend
+ extra_kwargs = {
+ "owner_team": {"help_text": "The team slug this trend is scoped to."},
+ "has_membership_data": {
+ "help_text": "False when the GitHub source has no team_members snapshot synced: the trend "
+ "then has no honest team attribution and `points` is empty.",
+ },
+ }
+
+
class BrokenTestRowSerializer(DataclassSerializer):
class Meta:
dataclass = BrokenTestRow
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index 412c33277b69..35250f221372 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -50,6 +50,9 @@ from products.engineering_analytics.backend.presentation.serializers import (
QuarantineRequestSerializer,
RepoOverviewSerializer,
RunFailureLogsSerializer,
+ TeamCIActivitySerializer,
+ TeamCIHealthListSerializer,
+ TeamMergeTrendSerializer,
WorkflowCostSerializer,
WorkflowHealthItemSerializer,
WorkflowJobAggregateSerializer,
@@ -931,6 +934,187 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
return _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")
return Response(FlakyTestListSerializer(instance=result).data)
+ @extend_schema(
+ operation_id="engineering_analytics_team_ci_health",
+ parameters=[
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
+ "may span at most 30 days. An equal-length prior window is scanned for the *_prior twins; "
+ "near the 30-day ceiling that prior window can reach past Traces retention, deflating "
+ "*_prior counts and overstating deltas.",
+ ),
+ _DATE_TO,
+ OpenApiParameter(
+ name="min_rerun_passes",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A test counts as flaky once it passed on retry at least this many times in the "
+ "window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.",
+ ),
+ OpenApiParameter(
+ name="min_failed_prs",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A test counts as flaky once it failed on at least this many distinct pull "
+ "requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.",
+ ),
+ OpenApiParameter(
+ name="limit",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Maximum number of teams to return (1-200). Defaults to 100.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: TeamCIHealthListSerializer,
+ 400: OpenApiResponse(
+ description="Invalid date, threshold, limit, or source_id, or a window longer than 30 days."
+ ),
+ },
+ description=(
+ "Per-owning-team rollup of the CI test surfaces each team owns: flaky-test count, failure and "
+ "pass-on-retry span counts, each with 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 "
+ "(products/*/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team "
+ "'unowned'. Teams are organizational owners of code surfaces, never authors. " + FLAKY_TEST_SIGNAL_CAVEAT
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def team_ci_health(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.list_team_ci_health(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ min_rerun_passes=_optional_int_param(request, "min_rerun_passes"),
+ min_failed_prs=_optional_int_param(request, "min_failed_prs"),
+ limit=_optional_int_param(request, "limit"),
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")
+ return Response(TeamCIHealthListSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_team_ci_activity",
+ parameters=[
+ OpenApiParameter(
+ name="owner_team",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Owning team slug to scope to (as returned by team_ci_health), e.g. 'team-replay', "
+ "or the literal 'unowned' for tests with no ownership stamp.",
+ ),
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
+ "may span at most 30 days. An equal-length prior window feeds the *_prior twins; near the "
+ "30-day ceiling that prior window can reach past Traces retention, deflating *_prior counts.",
+ ),
+ _DATE_TO,
+ OpenApiParameter(
+ name="test_limit",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Maximum number of per-test signal rows to return (1-100). Defaults to 25.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: TeamCIActivitySerializer,
+ 400: OpenApiResponse(
+ description="Missing owner_team, invalid date, test_limit, or source_id, or a window longer "
+ "than 30 days."
+ ),
+ },
+ description=(
+ "One owning team's CI test activity: per-test current-vs-prior signal pairs (the before/after "
+ "comparison) over the window and its equal-length prior twin. Signal = failed + error + "
+ "pass-on-retry spans on the team's owned tests. " + FLAKY_TEST_SIGNAL_CAVEAT
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def team_ci_activity(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_team_ci_activity(
+ team=self.team,
+ owner_team=request.query_params.get("owner_team") or "",
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ test_limit=_optional_int_param(request, "test_limit"),
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid owner_team, date, test_limit, or source_id")
+ return Response(TeamCIActivitySerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_team_merge_trend",
+ parameters=[
+ OpenApiParameter(
+ name="owner_team",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Team slug to scope to (as returned by team_ci_health), matched against the "
+ "GitHub org team slug of the source's team_members snapshot. The literal 'unowned' names "
+ "an ownership gap, not an org team, and has no merge trend.",
+ ),
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
+ "may span at most 30 days.",
+ ),
+ _DATE_TO,
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: TeamMergeTrendSerializer,
+ 400: OpenApiResponse(
+ description="Missing owner_team, invalid date or source_id, or a window longer than 30 days."
+ ),
+ },
+ description=(
+ "One team's daily time-to-merge trend: the median and average open→merge seconds over the PRs "
+ "the team's members merged each day (PR author login → GitHub org team membership). Team-level "
+ "aggregates only, never per-member figures or cross-team rankings. Timing is the coarse "
+ "open→merge (draft + review time combined); bots are excluded. Requires the GitHub source's "
+ "team_members snapshot; has_membership_data is false without it."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def team_merge_trend(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_team_merge_trend(
+ team=self.team,
+ owner_team=request.query_params.get("owner_team") or "",
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid owner_team, date, or source_id")
+ return Response(TeamMergeTrendSerializer(instance=result).data)
+
@extend_schema(
operation_id="engineering_analytics_broken_tests",
parameters=[_SOURCE_ID],
diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.py
index 2eca1806eb69..a1fe32776477 100644
--- a/products/engineering_analytics/backend/tests/test_flaky_tests.py
+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py
@@ -9,7 +9,7 @@ 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.queries.flaky_tests import _selector_from_nodeid
+from products.engineering_analytics.backend.logic.queries._test_spans import selector_from_nodeid
from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data
from products.warehouse_sources.backend.facade.models import ExternalDataSource
@@ -221,4 +221,4 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):
],
)
def test_selector_from_nodeid(nodeid: str, expected: str) -> None:
- assert _selector_from_nodeid(nodeid) == expected
+ assert selector_from_nodeid(nodeid) == expected
diff --git a/products/engineering_analytics/backend/tests/test_team_ci_health.py b/products/engineering_analytics/backend/tests/test_team_ci_health.py
new file mode 100644
index 000000000000..43cb86523922
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_team_ci_health.py
@@ -0,0 +1,155 @@
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+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.tests.test_views import connect_github_source_without_data
+
+T_REPLAY_PRS = "products/replay/backend/tests/test_snap/TestSnap::test_prs"
+T_REPLAY_RERUN = "products/replay/backend/tests/test_playlist/TestPlaylist::test_rerun"
+T_EXPORTS_RECOVERED = "products/batch_exports/backend/tests/test_snowflake/TestSnowflake::test_recovered"
+T_UNOWNED = "posthog/api/test/test_shared/TestShared::test_unowned"
+T_FOREIGN = "posthog/api/test/test_foreign/TestForeign::test_other_service"
+
+
+class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):
+ # The two-window split, per-(team, nodeid) qualification bar, and unowned bucketing all
+ # live in the HogQL rollup, so regressions only surface against real seeded trace_spans
+ # rows, same setup pattern as TestFlakyTestsAPI.
+
+ CLASS_DATA_LEVEL_SETUP = True
+
+ current_a: datetime
+ current_b: datetime
+
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ connect_github_source_without_data(cls.team, prefix="teams", repository="PostHog/posthog")
+ sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
+ sync_execute("DROP TABLE IF EXISTS trace_spans")
+ sync_execute(TRACE_SPANS_TABLE_SQL())
+ sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
+
+ now = datetime.now(UTC).replace(microsecond=0)
+ # Default window is -14d: current spans sit safely inside it, prior spans safely
+ # inside the equal-length twin [-28d, -14d).
+ cls.current_a = now - timedelta(days=2)
+ cls.current_b = now - timedelta(days=1)
+ prior = now - timedelta(days=20)
+
+ rows = [
+ # team-replay test 1 qualifies current via 3 distinct failed PRs (prior has only 1 PR,
+ # below the bar); one current xfail must count separately and stay out of slope signal.
+ cls._span(1, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", pr="101"),
+ cls._span(2, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", pr="102"),
+ cls._span(3, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", pr="103"),
+ cls._span(4, T_REPLAY_PRS, "xfailed", ts=cls.current_b, owner="team-replay"),
+ cls._span(5, T_REPLAY_PRS, "failed", ts=prior, owner="team-replay", pr="101"),
+ # team-replay test 2 qualifies in both windows via pass-on-retry.
+ cls._span(6, T_REPLAY_RERUN, "rerun_passed", ts=cls.current_b, owner="team-replay", pr="201"),
+ cls._span(7, T_REPLAY_RERUN, "rerun_passed", ts=prior, owner="team-replay", pr="202"),
+ cls._span(8, T_REPLAY_RERUN, "rerun_passed", ts=prior, owner="team-replay", pr="203"),
+ # batch-exports recovered: qualifies prior only (3 distinct PRs), zero current signal.
+ cls._span(9, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", pr="301"),
+ cls._span(10, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", pr="302"),
+ cls._span(11, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", pr="303"),
+ # No owner stamp: buckets under the literal 'unowned'.
+ cls._span(12, T_UNOWNED, "rerun_passed", ts=cls.current_b, owner="", pr="401"),
+ # A non-CI service must never reach the roster (the scan is fenced by service_name).
+ cls._span(13, T_FOREIGN, "rerun_passed", ts=cls.current_b, owner="ghost-team", pr="501", service="other"),
+ ]
+ sync_execute(
+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "
+ "timestamp, end_time, observed_timestamp, status_code, service_name, attributes_map_str, "
+ "resource_attributes) VALUES " + ",".join(rows)
+ )
+
+ @classmethod
+ def tearDownClass(cls):
+ sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
+ sync_execute("DROP TABLE IF EXISTS trace_spans")
+ sync_execute(TRACE_SPANS_TABLE_SQL())
+ sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
+ super().tearDownClass()
+
+ @classmethod
+ def _span(
+ cls,
+ i: int,
+ name: str,
+ outcome: str,
+ *,
+ ts: datetime,
+ owner: str,
+ pr: str = "",
+ service: str = "ci-backend",
+ ) -> str:
+ attr_pairs = [f"'test.outcome__str', '{outcome}'"]
+ if owner:
+ attr_pairs.append(f"'test.owner_team__str', '{owner}'")
+ resource_pairs = [f"'ci.repository', 'PostHog/posthog'"]
+ if pr:
+ resource_pairs.append(f"'ci.pr_number', '{pr}'")
+ stamp = ts.strftime("%Y-%m-%d %H:%M:%S")
+ return (
+ f"('uuid-{i}', {cls.team.id}, 'trace-{i}', 'span-{i}', 'parent', '{name}', 1, "
+ f"'{stamp}', '{stamp}', '{stamp}', 0, '{service}', map({', '.join(attr_pairs)}), "
+ f"map({', '.join(resource_pairs)}))"
+ )
+
+ def _get(self, endpoint: str, **params: str) -> dict:
+ response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/{endpoint}/", params)
+ assert response.status_code == status.HTTP_200_OK, response.content
+ return response.json()
+
+ def test_roster_splits_windows_qualifies_and_buckets_unowned(self):
+ data = self._get("team_ci_health")
+
+ assert [item["owner_team"] for item in data["items"]] == ["team-replay", "unowned", "batch-exports"]
+ replay, unowned, exports = data["items"]
+
+ # Current window: both replay tests qualify; prior: only the rerun test does.
+ assert replay["flaky_test_count"] == 2
+ assert replay["flaky_test_count_prior"] == 1
+ assert replay["failed_count"] == 3
+ assert replay["failed_count_prior"] == 1
+ assert replay["rerun_passed_count"] == 1
+ assert replay["rerun_passed_count_prior"] == 2
+ assert replay["xfailed_count"] == 1
+ assert replay["xfailed_count_prior"] == 0
+
+ assert unowned["flaky_test_count"] == 1
+ assert unowned["rerun_passed_count"] == 1
+
+ # Recovered team: all signal in the prior window, none current.
+ assert exports["flaky_test_count"] == 0
+ assert exports["flaky_test_count_prior"] == 1
+ assert exports["failed_count"] == 0
+ assert exports["failed_count_prior"] == 3
+
+ # The foreign-service span's team must not appear at all.
+ assert not data["truncated"]
+
+ def test_activity_scopes_to_team_and_pairs_windows(self):
+ data = self._get("team_ci_activity", owner_team="team-replay")
+
+ assert data["owner_team"] == "team-replay"
+ # Before/after pairs: ranked by the stronger window, xfail excluded from signal.
+ assert [(t["nodeid"], t["signal_count"], t["signal_count_prior"]) for t in data["tests"]] == [
+ (T_REPLAY_PRS, 3, 1),
+ (T_REPLAY_RERUN, 1, 2),
+ ]
+ assert not data["truncated_tests"]
+
+ def test_activity_for_unknown_team_is_empty(self):
+ data = self._get("team_ci_activity", owner_team="team-nonexistent")
+ assert data["tests"] == []
+
+ def test_activity_requires_owner_team(self):
+ response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/team_ci_activity/")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/engineering_analytics/backend/tests/test_team_merge_trend.py b/products/engineering_analytics/backend/tests/test_team_merge_trend.py
new file mode 100644
index 000000000000..d3a9fa69d90f
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_team_merge_trend.py
@@ -0,0 +1,93 @@
+from datetime import UTC, datetime
+
+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin
+
+from rest_framework import status
+
+from posthog.models.team import Team
+
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries.team_merge_trend import query_team_merge_trend
+from products.engineering_analytics.backend.logic.sources import GitHubTables
+from products.engineering_analytics.backend.logic.views.source_schema import PULL_REQUESTS_COLUMNS, TEAM_MEMBERS_COLUMNS
+from products.engineering_analytics.backend.tests.test_views import (
+ _pr_row,
+ connect_github_source_without_data,
+ create_github_warehouse_table,
+)
+
+
+def _member_row(member_id: int, login: str, team_slug: str) -> dict:
+ return {
+ "id": member_id,
+ "login": login,
+ "team_id": 1,
+ "team_slug": team_slug,
+ "team_name": team_slug,
+ }
+
+
+class TestTeamMergeTrendAPI(ClickhouseTestMixin, APIBaseTest):
+ def test_degrades_without_membership_snapshot_and_requires_owner_team(self):
+ # The source resolves (pull_requests + workflow_runs) but has no team_members schema:
+ # the endpoint must answer has_membership_data=false instead of querying a missing table.
+ connect_github_source_without_data(self.team, prefix="mt", repository="PostHog/posthog")
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/engineering_analytics/team_merge_trend/",
+ {"owner_team": "team-replay"},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json() == {"owner_team": "team-replay", "has_membership_data": False, "points": []}
+
+ missing = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/team_merge_trend/")
+ assert missing.status_code == status.HTTP_400_BAD_REQUEST
+
+
+class TestTeamMergeTrendQuery(ClickhouseTestMixin, BaseTest):
+ def _curated(self, team: Team, pr_rows: list[dict], member_rows: list[dict]) -> CuratedGitHubSource:
+ pr_table = create_github_warehouse_table(self, "github_pull_requests", PULL_REQUESTS_COLUMNS, pr_rows)
+ members_table = create_github_warehouse_table(self, "github_team_members", TEAM_MEMBERS_COLUMNS, member_rows)
+ return CuratedGitHubSource(
+ team=team,
+ tables=GitHubTables(pull_requests=pr_table, workflow_runs="unused", team_members=members_table),
+ )
+
+ def test_membership_join_bot_exclusion_and_window(self):
+ # Guards the freshly written HogQL: the daily median/average must cover exactly the
+ # slug's members' merges, bots and non-members must stay out, and the window must
+ # bound merged_at.
+ curated = self._curated(
+ self.team,
+ pr_rows=[
+ # 2026-01-12, alice (team-replay): 2h + 4h + 30h merges, a skew that separates
+ # the median (4h) from the average (12h).
+ _pr_row(1, "alice", "closed", 0, "2026-01-12 08:00:00", merged_at="2026-01-12 10:00:00"),
+ _pr_row(2, "alice", "closed", 0, "2026-01-12 08:00:00", merged_at="2026-01-12 12:00:00"),
+ _pr_row(3, "alice", "closed", 0, "2026-01-11 08:00:00", merged_at="2026-01-12 14:00:00"),
+ # Same day: a non-member and a bot merge too; neither may move the team's numbers.
+ _pr_row(4, "bob", "closed", 0, "2026-01-11 10:00:00", merged_at="2026-01-12 10:00:00"),
+ _pr_row(5, "dependabot[bot]", "closed", 0, "2026-01-12 09:00:00", merged_at="2026-01-12 10:00:00"),
+ # 2026-01-14: only the non-member merges, so no team row for the day.
+ _pr_row(6, "bob", "closed", 0, "2026-01-14 00:00:00", merged_at="2026-01-14 10:00:00"),
+ # Outside the window / never merged: excluded entirely.
+ _pr_row(7, "alice", "closed", 0, "2026-01-30 10:00:00", merged_at="2026-02-01 10:00:00"),
+ _pr_row(8, "alice", "open", 0, "2026-01-11 10:00:00"),
+ ],
+ member_rows=[
+ _member_row(1, "alice", "team-replay"),
+ _member_row(2, "bob", "team-ingestion"),
+ ],
+ )
+
+ result = query_team_merge_trend(
+ curated=curated,
+ owner_team="team-replay",
+ date_from=datetime(2026, 1, 10, tzinfo=UTC),
+ date_to=datetime(2026, 1, 20, tzinfo=UTC),
+ )
+
+ assert result.has_membership_data is True
+ assert [point.day.date().isoformat() for point in result.points] == ["2026-01-12"]
+ (point,) = result.points
+ assert (point.median_seconds, point.average_seconds, point.merged_count) == (14400.0, 43200.0, 3)
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index 07106aa930b4..e73414ba9e7d 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -203,32 +203,37 @@ class TestListGithubSourcesAccessControl(BaseTest):
assert {source.id for source in visible} == {str(mine.id), str(theirs.id)}
+def create_github_warehouse_table(test: BaseTest, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:
+ # Returns the real table name (prefixed), which the builder is then told to read,
+ # proving build_query honors the resolved name instead of a hardcoded one. Skips the
+ # calling test when object storage is unreachable so the suite runs without the dev stack.
+ df = pd.DataFrame(rows, columns=list(columns.keys()))
+ tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False)
+ df.to_csv(tmp.name, index=False)
+ tmp.close()
+ test.addCleanup(Path(tmp.name).unlink, missing_ok=True)
+ try:
+ table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
+ csv_path=Path(tmp.name),
+ table_name=base_name,
+ table_columns=columns,
+ test_bucket=TEST_BUCKET,
+ team=test.team,
+ source_prefix=GITHUB_SOURCE_PREFIX,
+ )
+ except PermissionError as err:
+ test.skipTest(f"object storage unavailable: {err}")
+ test.addCleanup(cleanup)
+ return table.name
+
+
class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
"""The curated query builders, exercised as inline subqueries over real
warehouse tables. Skips when object storage is unreachable so the suite still
runs without the dev stack."""
def _create_table(self, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:
- # Returns the real table name (prefixed), which the builder is then told to read —
- # proving build_query honors the resolved name instead of a hardcoded one.
- df = pd.DataFrame(rows, columns=list(columns.keys()))
- tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False)
- df.to_csv(tmp.name, index=False)
- tmp.close()
- self.addCleanup(Path(tmp.name).unlink, missing_ok=True)
- try:
- table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
- csv_path=Path(tmp.name),
- table_name=base_name,
- table_columns=columns,
- test_bucket=TEST_BUCKET,
- team=self.team,
- source_prefix=GITHUB_SOURCE_PREFIX,
- )
- except PermissionError as err:
- self.skipTest(f"object storage unavailable: {err}")
- self.addCleanup(cleanup)
- return table.name
+ return create_github_warehouse_table(self, base_name, columns, rows)
def _select(self, sql: str) -> list[tuple]:
return execute_hogql_query(query=sql, team=self.team, query_type="engineering_analytics.test").results
diff --git a/products/engineering_analytics/frontend/components/MetricTile.tsx b/products/engineering_analytics/frontend/components/MetricTile.tsx
index 57817b6bb266..000705a765b2 100644
--- a/products/engineering_analytics/frontend/components/MetricTile.tsx
+++ b/products/engineering_analytics/frontend/components/MetricTile.tsx
@@ -9,6 +9,7 @@ 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 {
@@ -67,6 +68,30 @@ export function DeltaBadge({
)
}
+/** Current count + delta vs the prior window; a zero prior with current signal reads "new". */
+export function CountWithDelta({
+ current,
+ prior,
+ goodWhenDown = true,
+}: {
+ current: number
+ prior: number
+ goodWhenDown?: boolean
+}): 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 > 0 ? (
+ <DeltaBadge value={percentChange(current, prior)} goodWhenDown={goodWhenDown} />
+ ) : current > 0 ? (
+ <Tooltip title="No signal in the previous window. This is new.">
+ <span className="text-xs font-semibold whitespace-nowrap text-danger">new</span>
+ </Tooltip>
+ ) : null}
+ </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/PullRequestTable.tsx b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
index ecdfc23c31cf..704d774d8a3f 100644
--- a/products/engineering_analytics/frontend/components/PullRequestTable.tsx
+++ b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
@@ -2,19 +2,19 @@
// level (SPEC §2): the handle links to the author's PR list (a filter for finding work), never to a
// per-author metric or ranking. Hidden on the author page itself, where every row is the same author.
-import { combineUrl, router } from 'kea-router'
+import { combineUrl } from 'kea-router'
import { ReactNode } from 'react'
import { LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { newInternalTab } from 'lib/utils/newInternalTab'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { compactAgeLabel, compactHoursLabel } from '../lib/format'
import { githubPrUrl } from '../lib/github'
import { pushRoundFromSample } from '../lib/pushRounds'
+import { rowNavigationProps } from '../lib/rowNavigation'
import { PullRequestRow, prKeyOf } from '../scenes/engineeringAnalyticsLogic'
import { BillableBadge } from './BillableBadge'
import { CIStatusTag } from './CIStatusTag'
@@ -217,29 +217,7 @@ export function PullRequestTable({
dataSource={rows}
rowKey={prKeyOf}
loading={loading}
- onRow={(row) => {
- const detailUrl = detailUrlOf(row, sourceId)
- return {
- // Inner links (#id → GitHub, author → author page) keep their own behavior.
- onClick: (e: React.MouseEvent) => {
- if ((e.target as HTMLElement).closest('a, button')) {
- return
- }
- if (e.metaKey || e.ctrlKey) {
- e.preventDefault()
- newInternalTab(detailUrl)
- } else {
- router.actions.push(detailUrl)
- }
- },
- onAuxClick: (e: React.MouseEvent) => {
- if (e.button === 1 && !(e.target as HTMLElement).closest('a, button')) {
- e.preventDefault()
- newInternalTab(detailUrl)
- }
- },
- }
- }}
+ onRow={(row) => rowNavigationProps(detailUrlOf(row, sourceId))}
useURLForSorting={false}
defaultSorting={showCreated ? { columnKey: 'created', order: -1 } : null}
pagination={{ pageSize }}
diff --git a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
index 0c32fba5ff33..6f5b6096a087 100644
--- a/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
+++ b/products/engineering_analytics/frontend/components/WorkflowHealthTable.tsx
@@ -9,11 +9,11 @@ import { LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui
import { TZLabel } from 'lib/components/TZLabel'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyDuration } from 'lib/utils/durations'
-import { newInternalTab } from 'lib/utils/newInternalTab'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
+import { rowNavigationProps } from '../lib/rowNavigation'
import { withScope } from '../lib/scope'
import { WorkflowHealthRow, workflowFailureSeries } from '../scenes/engineeringAnalyticsLogic'
import { BillableBadge } from './BillableBadge'
@@ -301,29 +301,7 @@ export function WorkflowHealthTable({
rowKey={(row) => `${row.repoOwner}/${row.repoName}:${row.workflowName}`}
// De-emphasize workflows with nothing settled — no pass/fail signal to read.
rowClassName={(row) => cn('cursor-pointer', row.successRate === null && 'opacity-60')}
- onRow={(row) => {
- const url = rowUrl(row)
- return {
- // Inner links (the workflow name) keep their own behavior.
- onClick: (e: React.MouseEvent) => {
- if ((e.target as HTMLElement).closest('a, button')) {
- return
- }
- if (e.metaKey || e.ctrlKey) {
- e.preventDefault()
- newInternalTab(url)
- } else {
- router.actions.push(url)
- }
- },
- onAuxClick: (e: React.MouseEvent) => {
- if (e.button === 1 && !(e.target as HTMLElement).closest('a, button')) {
- e.preventDefault()
- newInternalTab(url)
- }
- },
- }
- }}
+ onRow={(row) => rowNavigationProps(rowUrl(row))}
loading={loading}
useURLForSorting={false}
defaultSorting={defaultSorting}
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index a219e37a4246..ed2ef1765f8f 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -904,6 +904,86 @@ export interface GitHubSourceApi {
prefix: string
}
+export interface TeamTestSignalApi {
+ /** Reconstructed pytest nodeid (the CI span name), a stable grouping key. */
+ nodeid: string
+ /** Runnable pytest selector; exact when the CI reporter emitted it. */
+ selector: string
+ /** Failed + error + pass-on-retry spans in the current window (xfail excluded). */
+ signal_count: number
+ /** Same count over the equal-length window before date_from. */
+ signal_count_prior: number
+ /** Most recent signal span for this test, either window. */
+ last_seen_at: string
+}
+
+export interface TeamCIActivityApi {
+ /** The team's owned tests with signal in either window, ranked by the stronger window's count (the current-vs-prior pairs behind a before/after comparison). */
+ tests: TeamTestSignalApi[]
+ /** The team slug this activity is scoped to, or 'unowned'. */
+ owner_team: string
+ /** True when more owned tests had signal than the test cap. */
+ truncated_tests: boolean
+}
+
+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. */
+ owner_team: string
+ /** Owned tests meeting the flaky-leaderboard bar in the window (passed on retry or failed on enough distinct PRs). Compare with flaky_test_count_prior for the delta. */
+ flaky_test_count: number
+ /** Same count over the equal-length window immediately before date_from. */
+ flaky_test_count_prior: number
+ /** Signal spans on owned tests with final outcome 'failed' or 'error' in the window. An absolute count, not a rate: fast passing runs are not emitted. */
+ failed_count: number
+ /** Same count over the prior window. */
+ failed_count_prior: number
+ /** Spans on owned tests that failed, then passed on an automatic retry, the strongest flaky signal. Only rerun-enabled CI lanes emit it. */
+ rerun_passed_count: number
+ /** Same count over the prior window. */
+ rerun_passed_count_prior: number
+ /** Spans on owned tests that failed while quarantined (xfail): masked in CI but still flaky. */
+ xfailed_count: number
+ /** Same count over the prior window. */
+ xfailed_count_prior: number
+ /** Most recent signal span across the team's owned tests, either window. */
+ last_seen_at: string
+}
+
+export interface TeamCIHealthListApi {
+ /** Owning teams ranked by current flaky + failure signal, heaviest first, capped at `limit`. Teams are organizational owners of code surfaces; this never aggregates by author. */
+ items: TeamCIHealthItemApi[]
+ /** True when more teams had signal than the cap. */
+ truncated: boolean
+ /** Maximum number of teams returned in `items`. */
+ limit: number
+}
+
+export interface TeamMergeTrendPointApi {
+ /** Start of the day bucket (team timezone), keyed on merged_at. */
+ day: string
+ /**
+ * Median open→merge seconds of the PRs this team's members merged that day; null on a day the team merged nothing.
+ * @nullable
+ */
+ median_seconds: number | null
+ /**
+ * Average open→merge seconds over the same merges; diverges above the median when a few long-running PRs drag the mean. Null on a day the team merged nothing.
+ * @nullable
+ */
+ average_seconds: number | null
+ /** Merged PRs behind that day's median and average. */
+ merged_count: number
+}
+
+export interface TeamMergeTrendApi {
+ /** Daily median and average open→merge over the PRs this team's members merged, ascending by day. Coarse timing (open→merge combines draft and review time); bots excluded. */
+ points: TeamMergeTrendPointApi[]
+ /** The team slug this trend is scoped to. */
+ owner_team: string
+ /** False when the GitHub source has no team_members snapshot synced: the trend then has no honest team attribution and `points` is empty. */
+ has_membership_data: boolean
+}
+
export interface WorkflowHealthBucketApi {
/** Bucket start, aligned to the item's granularity (top of hour, midnight, or Monday). */
bucket_start: string
@@ -1296,6 +1376,75 @@ export type EngineeringAnalyticsRunFailureLogsParams = {
source_id?: string
}
+export type EngineeringAnalyticsTeamCiActivityParams = {
+ /**
+ * Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window may span at most 30 days. An equal-length prior window feeds the *_prior twins; near the 30-day ceiling that prior window can reach past Traces retention, deflating *_prior counts.
+ */
+ date_from?: string
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Owning team slug to scope to (as returned by team_ci_health), e.g. 'team-replay', or the literal 'unowned' for tests with no ownership stamp.
+ */
+ 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.
+ */
+ source_id?: string
+ /**
+ * Maximum number of per-test signal rows to return (1-100). Defaults to 25.
+ */
+ test_limit?: number
+}
+
+export type EngineeringAnalyticsTeamCiHealthParams = {
+ /**
+ * Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window may span at most 30 days. An equal-length prior window is scanned for the *_prior twins; near the 30-day ceiling that prior window can reach past Traces retention, deflating *_prior counts and overstating deltas.
+ */
+ date_from?: string
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Maximum number of teams to return (1-200). Defaults to 100.
+ */
+ limit?: number
+ /**
+ * A test counts as flaky once it failed on at least this many distinct pull requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.
+ */
+ min_failed_prs?: number
+ /**
+ * A test counts as flaky once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.
+ */
+ min_rerun_passes?: number
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+}
+
+export type EngineeringAnalyticsTeamMergeTrendParams = {
+ /**
+ * Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window may span at most 30 days.
+ */
+ date_from?: string
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Team slug to scope to (as returned by team_ci_health), matched against the GitHub org team slug of the source's team_members snapshot. The literal 'unowned' names an ownership gap, not an org team, and has no merge trend.
+ */
+ 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.
+ */
+ source_id?: string
+}
+
export type EngineeringAnalyticsWorkflowHealthParams = {
/**
* Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index d8cf55fdcf0e..78d9c3c29727 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -31,6 +31,9 @@ import type {
EngineeringAnalyticsRepoRunActivityParams,
EngineeringAnalyticsResolveBranchParams,
EngineeringAnalyticsRunFailureLogsParams,
+ EngineeringAnalyticsTeamCiActivityParams,
+ EngineeringAnalyticsTeamCiHealthParams,
+ EngineeringAnalyticsTeamMergeTrendParams,
EngineeringAnalyticsWorkflowHealthParams,
EngineeringAnalyticsWorkflowJobsParams,
EngineeringAnalyticsWorkflowRunActivityParams,
@@ -48,6 +51,9 @@ import type {
QuarantineRequestResultApi,
RepoOverviewApi,
RunFailureLogsApi,
+ TeamCIActivityApi,
+ TeamCIHealthListApi,
+ TeamMergeTrendApi,
WorkflowCostApi,
WorkflowHealthItemApi,
WorkflowJobAggregateApi,
@@ -648,6 +654,105 @@ export const engineeringAnalyticsSources = async (
})
}
+export const getEngineeringAnalyticsTeamCiActivityUrl = (
+ projectId: string,
+ params: EngineeringAnalyticsTeamCiActivityParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/team_ci_activity/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/team_ci_activity/`
+}
+
+/**
+ * One owning team's CI test activity: per-test current-vs-prior signal pairs (the before/after comparison) over the window and its equal-length prior twin. Signal = failed + error + pass-on-retry spans on the team's owned tests. All figures are absolute counts, never rates: fast passing runs are not emitted, so denominators are biased. Pass-on-retry counts only flow from CI lanes running with reruns enabled; in other lanes a flake surfaces as a plain failure, which the distinct-PR count catches.
+ */
+export const engineeringAnalyticsTeamCiActivity = async (
+ projectId: string,
+ params: EngineeringAnalyticsTeamCiActivityParams,
+ options?: RequestInit
+): Promise<TeamCIActivityApi> => {
+ return apiMutator<TeamCIActivityApi>(getEngineeringAnalyticsTeamCiActivityUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getEngineeringAnalyticsTeamCiHealthUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsTeamCiHealthParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/team_ci_health/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/team_ci_health/`
+}
+
+/**
+ * Per-owning-team rollup of the CI test surfaces each team owns: flaky-test count, failure and pass-on-retry span counts, each with 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 (products/*\/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team 'unowned'. Teams are organizational owners of code surfaces, never authors. All figures are absolute counts, never rates: fast passing runs are not emitted, so denominators are biased. Pass-on-retry counts only flow from CI lanes running with reruns enabled; in other lanes a flake surfaces as a plain failure, which the distinct-PR count catches.
+ */
+export const engineeringAnalyticsTeamCiHealth = async (
+ projectId: string,
+ params?: EngineeringAnalyticsTeamCiHealthParams,
+ options?: RequestInit
+): Promise<TeamCIHealthListApi> => {
+ return apiMutator<TeamCIHealthListApi>(getEngineeringAnalyticsTeamCiHealthUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getEngineeringAnalyticsTeamMergeTrendUrl = (
+ projectId: string,
+ params: EngineeringAnalyticsTeamMergeTrendParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/team_merge_trend/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/team_merge_trend/`
+}
+
+/**
+ * One team's daily time-to-merge trend: the median and average open→merge seconds over the PRs the team's members merged each day (PR author login → GitHub org team membership). Team-level aggregates only, never per-member figures or cross-team rankings. Timing is the coarse open→merge (draft + review time combined); bots are excluded. Requires the GitHub source's team_members snapshot; has_membership_data is false without it.
+ */
+export const engineeringAnalyticsTeamMergeTrend = async (
+ projectId: string,
+ params: EngineeringAnalyticsTeamMergeTrendParams,
+ options?: RequestInit
+): Promise<TeamMergeTrendApi> => {
+ return apiMutator<TeamMergeTrendApi>(getEngineeringAnalyticsTeamMergeTrendUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsWorkflowHealthUrl = (
projectId: string,
params?: EngineeringAnalyticsWorkflowHealthParams
diff --git a/products/engineering_analytics/frontend/lib/rowNavigation.ts b/products/engineering_analytics/frontend/lib/rowNavigation.ts
new file mode 100644
index 000000000000..39e7d096c371
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/rowNavigation.ts
@@ -0,0 +1,31 @@
+import { router } from 'kea-router'
+import type { MouseEvent } from 'react'
+
+import { newInternalTab } from 'lib/utils/newInternalTab'
+
+/** Row-level navigation for tables whose rows are links: click routes, cmd/ctrl and middle
+ * click open an internal tab, and inner links/buttons keep their own behavior. */
+export function rowNavigationProps(url: string): {
+ onClick: (e: MouseEvent) => void
+ onAuxClick: (e: MouseEvent) => void
+} {
+ return {
+ onClick: (e: MouseEvent) => {
+ if ((e.target as HTMLElement).closest('a, button')) {
+ return
+ }
+ if (e.metaKey || e.ctrlKey) {
+ e.preventDefault()
+ newInternalTab(url)
+ } else {
+ router.actions.push(url)
+ }
+ },
+ onAuxClick: (e: MouseEvent) => {
+ if (e.button === 1 && !(e.target as HTMLElement).closest('a, button')) {
+ e.preventDefault()
+ newInternalTab(url)
+ }
+ },
+ }
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
index d232ce5eaeb2..05295a462d57 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
@@ -16,6 +16,7 @@ import {
VIEW_DESCRIPTIONS,
engineeringAnalyticsSceneLogic,
} from './engineeringAnalyticsSceneLogic'
+import { EngineeringAnalyticsTeams } from './EngineeringAnalyticsTeams'
import { EngineeringAnalyticsTestHealth } from './EngineeringAnalyticsTestHealth'
import { EngineeringAnalyticsWorkflows } from './EngineeringAnalyticsWorkflows'
import { RepoOverviewScene } from './RepoOverviewScene'
@@ -55,6 +56,13 @@ export function EngineeringAnalyticsScene(): JSX.Element {
link: combineUrl(urls.engineeringAnalyticsWorkflows(), linkParams).url,
'data-attr': 'engineering-analytics-workflows-tab',
},
+ {
+ key: 'teams',
+ label: 'Teams',
+ content: <EngineeringAnalyticsTeams />,
+ link: combineUrl(urls.engineeringAnalyticsTeams(), linkParams).url,
+ 'data-attr': 'engineering-analytics-teams-tab',
+ },
{
key: 'test-health',
label: 'Test health',
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx
new file mode 100644
index 000000000000..29342d532836
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.tsx
@@ -0,0 +1,168 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPeople } from '@posthog/icons'
+import { LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { TimeSeriesLineChart, useChartTheme } from '@posthog/quill-charts'
+
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { TZLabel } from 'lib/components/TZLabel'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { SceneExport } from 'scenes/sceneTypes'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { EntityHeader } from '../components/EntityHeader'
+import { CountWithDelta } from '../components/MetricTile'
+import { Section } from '../components/Section'
+import { compactHoursLabel } from '../lib/format'
+import { TeamDetailLogicProps, TeamTestSignalRow, teamDetailLogic } from './teamDetailLogic'
+import { TEAMS_WINDOW_DATE_OPTIONS, TEAMS_WINDOW_LABELS, UNOWNED_TEAM, isTeamsWindow } from './teamsLogic'
+
+export const scene: SceneExport<TeamDetailLogicProps> = {
+ component: EngineeringAnalyticsTeamScene,
+ logic: teamDetailLogic,
+ paramsToProps: ({ params: { ownerTeam }, searchParams: { source, window } }) => ({
+ ownerTeam: decodeURIComponent(ownerTeam ?? ''),
+ sourceId: source ?? null,
+ window: isTeamsWindow(window) ? window : null,
+ }),
+}
+
+export function EngineeringAnalyticsTeamScene(): JSX.Element {
+ const { activity, activityLoading, mergeTrend, mergeTrendLoading, mergeTrendSeries, window, ownerTeam } =
+ useValues(teamDetailLogic)
+ const { setWindow } = useActions(teamDetailLogic)
+ const { timezone } = useValues(teamLogic)
+ 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>
+ ),
+ },
+ {
+ 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: labels.current,
+ key: 'signalCount',
+ width: 140,
+ align: 'right',
+ sorter: (a, b) => a.signalCount - b.signalCount,
+ render: (_, row) => <CountWithDelta current={row.signalCount} prior={row.signalCountPrior} />,
+ },
+ {
+ title: 'Last seen',
+ key: 'lastSeenAt',
+ width: 110,
+ align: 'right',
+ render: (_, row) => (
+ <span className="text-xs whitespace-nowrap text-secondary">
+ <TZLabel time={row.lastSeenAt} />
+ </span>
+ ),
+ },
+ ]
+
+ return (
+ <SceneContent>
+ <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>
+
+ {!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>
+ )}
+
+ <Section id="team-tests" title="Owned tests with signal" busy={activityLoading}>
+ <LemonTable
+ data-attr="engineering-analytics-team-tests-table"
+ size="small"
+ columns={testColumns}
+ dataSource={activity?.tests ?? []}
+ rowKey={(row) => row.nodeid}
+ loading={activityLoading}
+ pagination={{ pageSize: 25 }}
+ useURLForSorting={false}
+ emptyState="No owned tests with signal in this window."
+ 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.
+ </div>
+ )}
+ </Section>
+ </SceneContent>
+ )
+}
+
+export default EngineeringAnalyticsTeamScene
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx
new file mode 100644
index 000000000000..19a401c89e72
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx
@@ -0,0 +1,137 @@
+import { useActions, 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 { CountWithDelta } from '../components/MetricTile'
+import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
+import { rowNavigationProps } from '../lib/rowNavigation'
+import {
+ TEAMS_WINDOW_DATE_OPTIONS,
+ TeamCIHealthRow,
+ TeamsWindow,
+ UNOWNED_TEAM,
+ isTeamsWindow,
+ 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
+}
+
+export function EngineeringAnalyticsTeams(): JSX.Element {
+ const { teams, teamsLoading, teamsWindow, sourceId } = useValues(teamsLogic)
+ const { setTeamsWindow } = useActions(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)}
+ className="font-semibold"
+ data-attr="eng-analytics-team-link"
+ >
+ Unowned
+ </Link>
+ <Tooltip title="Tests whose CI spans carry no ownership stamp. An ownership gap to close, not a real team.">
+ <LemonTag type="warning" size="small">
+ ownership gap
+ </LemonTag>
+ </Tooltip>
+ </div>
+ ) : (
+ <Link
+ to={detailUrlOf(row.ownerTeam, teamsWindow, sourceId)}
+ className="font-mono text-xs font-semibold"
+ data-attr="eng-analytics-team-link"
+ >
+ {row.ownerTeam}
+ </Link>
+ ),
+ },
+ {
+ title: 'Flaky tests',
+ key: 'flakyTestCount',
+ width: 140,
+ align: 'right',
+ tooltip:
+ 'Owned tests meeting the flaky-leaderboard bar in this window (passed on retry, or failed across several distinct PRs), vs the previous window.',
+ sorter: (a, b) => a.flakyTestCount - b.flakyTestCount,
+ render: (_, row) => <CountWithDelta current={row.flakyTestCount} prior={row.flakyTestCountPrior} />,
+ },
+ {
+ title: 'Failures',
+ key: 'failedCount',
+ width: 130,
+ align: 'right',
+ tooltip:
+ 'Failed or errored runs on owned tests. Absolute counts, not rates: passing runs are mostly not recorded.',
+ sorter: (a, b) => a.failedCount - b.failedCount,
+ render: (_, row) => <CountWithDelta current={row.failedCount} prior={row.failedCountPrior} />,
+ },
+ {
+ title: 'Pass on retry',
+ key: 'rerunPassedCount',
+ width: 130,
+ align: 'right',
+ tooltip: 'Failed, then passed on an automatic retry. The strongest flaky signal.',
+ sorter: (a, b) => a.rerunPassedCount - b.rerunPassedCount,
+ render: (_, row) => <CountWithDelta current={row.rerunPassedCount} prior={row.rerunPassedCountPrior} />,
+ },
+ ]
+
+ 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 change vs the previous
+ window. Ownership comes from the repo's ownership map, never from authorship.
+ </p>
+ </div>
+ <DateFilter
+ dateFrom={teamsWindow}
+ onChange={(from) => isTeamsWindow(from) && setTeamsWindow(from)}
+ dateOptions={TEAMS_WINDOW_DATE_OPTIONS}
+ size="small"
+ />
+ </div>
+ <LemonTable
+ data-attr="engineering-analytics-teams-table"
+ size="small"
+ columns={columns}
+ dataSource={teams?.rows ?? []}
+ rowKey={(row) => row.ownerTeam}
+ rowClassName="cursor-pointer"
+ onRow={(row) => rowNavigationProps(detailUrlOf(row.ownerTeam, teamsWindow, sourceId))}
+ loading={teamsLoading}
+ pagination={{ pageSize: 25 }}
+ useURLForSorting={false}
+ emptyState="No team-attributed CI signal in this window. 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.
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
index b9791a22e2b0..f9842c2acc6c 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
@@ -4,14 +4,15 @@ import { sceneLogic } from '~/scenes/sceneLogic'
import type { engineeringAnalyticsSceneLogicType } from './engineeringAnalyticsSceneLogicType'
-/** The root scene's views: the repo hub landing, the PR list page, the workflow list page, and test health. */
-export type EngineeringAnalyticsView = 'hub' | 'pull-requests' | 'workflows' | 'test-health'
+/** The root scene's views: the repo hub landing, the PR list page, the workflow list page, test health, and teams. */
+export type EngineeringAnalyticsView = 'hub' | 'pull-requests' | 'workflows' | 'test-health' | 'teams'
export const VIEW_DESCRIPTIONS: Record<EngineeringAnalyticsView, string> = {
hub: 'CI health, pull requests, workflows, and cost for the connected repo.',
'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': 'Flaky tests under quarantine: what is masked, who owns it, and when it expires.',
+ teams: 'CI test surfaces rolled up by owning team: flaky signal and failures, with prior-window deltas.',
}
const SCENE_KEY_TO_VIEW: Record<string, EngineeringAnalyticsView> = {
@@ -19,6 +20,7 @@ const SCENE_KEY_TO_VIEW: Record<string, EngineeringAnalyticsView> = {
engineeringAnalyticsPullRequestList: 'pull-requests',
engineeringAnalyticsWorkflows: 'workflows',
engineeringAnalyticsTestHealth: 'test-health',
+ engineeringAnalyticsTeams: 'teams',
}
export const engineeringAnalyticsSceneLogic = kea<engineeringAnalyticsSceneLogicType>([
diff --git a/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts b/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts
new file mode 100644
index 000000000000..9df793da5001
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/teamDetailLogic.ts
@@ -0,0 +1,155 @@
+import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+import { Dayjs, dayjs } from 'lib/dayjs'
+
+import { engineeringAnalyticsTeamCiActivity, engineeringAnalyticsTeamMergeTrend } from '../generated/api'
+import type { teamDetailLogicType } from './teamDetailLogicType'
+import { DEFAULT_TEAMS_WINDOW, TeamsWindow, UNOWNED_TEAM } from './teamsLogic'
+
+const projectId = (): string => String(ApiConfig.getCurrentProjectId())
+
+export interface TeamDetailLogicProps {
+ ownerTeam: string
+ sourceId: string | null
+ window: TeamsWindow | null
+}
+
+export interface TeamTestSignalRow {
+ nodeid: string
+ selector: string
+ signalCount: number
+ signalCountPrior: number
+ lastSeenAt: string
+}
+
+export interface TeamActivityData {
+ tests: TeamTestSignalRow[]
+ truncatedTests: boolean
+}
+
+export interface TeamMergePoint {
+ day: string
+ medianSeconds: number | null
+ averageSeconds: number | null
+}
+
+export interface TeamMergeTrendData {
+ hasMembershipData: boolean
+ points: TeamMergePoint[]
+}
+
+export const teamDetailLogic = kea<teamDetailLogicType>([
+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'teamDetailLogic']),
+ props({} as TeamDetailLogicProps),
+ key((props) => `${props.ownerTeam}@${props.sourceId ?? ''}`),
+ actions({
+ setWindow: (window: TeamsWindow) => ({ window }),
+ }),
+ reducers(({ props }) => ({
+ window: [(props.window ?? DEFAULT_TEAMS_WINDOW) as TeamsWindow, { setWindow: (_, { window }) => window }],
+ })),
+ loaders(({ props, values }) => ({
+ activity: [
+ null as TeamActivityData | null,
+ {
+ loadActivity: async (): Promise<TeamActivityData> => {
+ const data = await engineeringAnalyticsTeamCiActivity(projectId(), {
+ owner_team: props.ownerTeam,
+ date_from: values.window,
+ source_id: props.sourceId ?? undefined,
+ })
+ return {
+ tests: data.tests.map((t) => ({
+ nodeid: t.nodeid,
+ selector: t.selector,
+ signalCount: t.signal_count,
+ signalCountPrior: t.signal_count_prior,
+ lastSeenAt: t.last_seen_at,
+ })),
+ truncatedTests: data.truncated_tests,
+ }
+ },
+ },
+ ],
+ mergeTrend: [
+ null as TeamMergeTrendData | null,
+ {
+ loadMergeTrend: async (): Promise<TeamMergeTrendData | null> => {
+ // 'unowned' is an ownership gap, not an org team; a membership join has no meaning there.
+ if (props.ownerTeam === UNOWNED_TEAM) {
+ return null
+ }
+ const data = await engineeringAnalyticsTeamMergeTrend(projectId(), {
+ owner_team: props.ownerTeam,
+ date_from: values.window,
+ source_id: props.sourceId ?? undefined,
+ })
+ return {
+ hasMembershipData: data.has_membership_data,
+ points: data.points.map((p) => ({
+ day: p.day,
+ medianSeconds: p.median_seconds ?? null,
+ averageSeconds: p.average_seconds ?? null,
+ })),
+ }
+ },
+ },
+ ],
+ })),
+ selectors({
+ ownerTeam: [(_, p) => [p.ownerTeam], (ownerTeam: string) => ownerTeam],
+ /** Quill-ready daily series on the backend's own day buckets. Gaps carry the last values
+ * forward: a day without merges means "nothing merged", not instant merges, so
+ * zero-filling would draw a false dip. Null when nothing merged in the window. */
+ mergeTrendSeries: [
+ (s) => [s.mergeTrend],
+ (
+ mergeTrend: TeamMergeTrendData | null
+ ): { labels: string[]; median: number[]; average: number[] } | null => {
+ if (!mergeTrend?.hasMembershipData) {
+ return null
+ }
+ const labels: string[] = []
+ const median: number[] = []
+ const average: number[] = []
+ let lastDay: Dayjs | null = null
+ let lastMedian = 0
+ let lastAverage = 0
+ for (const point of mergeTrend.points) {
+ const day = dayjs(point.day)
+ if (lastDay) {
+ for (let gap: Dayjs = lastDay.add(1, 'day'); gap.isBefore(day); gap = gap.add(1, 'day')) {
+ labels.push(gap.toISOString())
+ median.push(lastMedian)
+ average.push(lastAverage)
+ }
+ }
+ const medianValue: number | null = point.medianSeconds ?? (lastDay ? lastMedian : null)
+ const averageValue: number | null = point.averageSeconds ?? (lastDay ? lastAverage : null)
+ if (medianValue === null || averageValue === null) {
+ continue // Leading trim: no data yet to carry forward.
+ }
+ labels.push(day.toISOString())
+ median.push(medianValue)
+ average.push(averageValue)
+ lastDay = day
+ lastMedian = medianValue
+ lastAverage = averageValue
+ }
+ return labels.length ? { labels, median, average } : null
+ },
+ ],
+ }),
+ listeners(({ actions }) => ({
+ setWindow: () => {
+ actions.loadActivity()
+ actions.loadMergeTrend()
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadActivity()
+ actions.loadMergeTrend()
+ }),
+])
diff --git a/products/engineering_analytics/frontend/scenes/teamsLogic.ts b/products/engineering_analytics/frontend/scenes/teamsLogic.ts
new file mode 100644
index 000000000000..aeb32a97af48
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/teamsLogic.ts
@@ -0,0 +1,96 @@
+import { actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+import { dateMapping } from 'lib/utils/dateFilters'
+
+import { engineeringAnalyticsTeamCiHealth } from '../generated/api'
+import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
+import type { teamsLogicType } from './teamsLogicType'
+
+const projectId = (): string => String(ApiConfig.getCurrentProjectId())
+
+export type TeamsWindow = '-24h' | '-7d' | '-14d' | '-30d'
+
+export const DEFAULT_TEAMS_WINDOW: TeamsWindow = '-14d'
+
+export const TEAMS_WINDOW_LABELS: Record<TeamsWindow, { prior: string; current: string }> = {
+ '-24h': { prior: 'Previous 24 hours', current: 'Last 24 hours' },
+ '-7d': { prior: 'Previous 7 days', current: 'Last 7 days' },
+ '-14d': { prior: 'Previous 14 days', current: 'Last 14 days' },
+ '-30d': { prior: 'Previous 30 days', current: 'Last 30 days' },
+}
+
+export function isTeamsWindow(value: unknown): value is TeamsWindow {
+ return typeof value === 'string' && value in TEAMS_WINDOW_LABELS
+}
+
+// date_from presets the team endpoints accept (max 30d; an equal-length prior twin is scanned).
+export const TEAMS_WINDOW_DATE_OPTIONS = dateMapping.filter(({ values }) => isTeamsWindow(values[0]))
+
+export const UNOWNED_TEAM = 'unowned'
+
+export interface TeamCIHealthRow {
+ ownerTeam: string
+ flakyTestCount: number
+ flakyTestCountPrior: number
+ failedCount: number
+ failedCountPrior: number
+ rerunPassedCount: number
+ rerunPassedCountPrior: number
+}
+
+export interface TeamsData {
+ rows: TeamCIHealthRow[]
+ truncated: boolean
+ limit: number
+}
+
+export const teamsLogic = kea<teamsLogicType>([
+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'teamsLogic']),
+ connect(() => ({
+ 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,
+ 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,
+ failedCount: it.failed_count,
+ failedCountPrior: it.failed_count_prior,
+ rerunPassedCount: it.rerun_passed_count,
+ rerunPassedCountPrior: it.rerun_passed_count_prior,
+ })
+ ),
+ truncated: data.truncated,
+ limit: data.limit,
+ }
+ },
+ },
+ ],
+ })),
+ listeners(({ actions }) => ({
+ setTeamsWindow: () => actions.loadTeams(),
+ setSourceId: () => actions.loadTeams(),
+ })),
+ afterMount(({ actions }) => {
+ actions.loadTeams()
+ }),
+])
diff --git a/products/engineering_analytics/manifest.tsx b/products/engineering_analytics/manifest.tsx
index 585184bb0bb3..308a8b7f87ee 100644
--- a/products/engineering_analytics/manifest.tsx
+++ b/products/engineering_analytics/manifest.tsx
@@ -49,6 +49,14 @@ export const manifest: ProductManifest = {
description: "One author's pull requests — a filtered view for finding work, not a ranking.",
iconType: 'health',
},
+ EngineeringAnalyticsTeam: {
+ import: () => import('./frontend/scenes/EngineeringAnalyticsTeamScene'),
+ projectBased: true,
+ name: 'Team CI health',
+ layout: 'app-container',
+ description: "One owning team's merge timing and the before/after signal on its owned tests.",
+ iconType: 'health',
+ },
},
// Detail paths follow GitHub's REST-API shape (repos/:owner/:repo/pull-requests/:n, .../actions/runs/:id)
// — a repos/ prefix that keeps them clear of the tab routes and readable collection nouns. Cross-repo
@@ -59,6 +67,8 @@ export const manifest: ProductManifest = {
'/engineering-analytics/pull-requests': ['EngineeringAnalytics', 'engineeringAnalyticsPullRequestList'],
'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],
'/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],
+ '/engineering-analytics/teams': ['EngineeringAnalytics', 'engineeringAnalyticsTeams'],
+ '/engineering-analytics/teams/:ownerTeam': ['EngineeringAnalyticsTeam', 'engineeringAnalyticsTeam'],
'/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number': [
'EngineeringAnalyticsPullRequest',
'engineeringAnalyticsPullRequest',
@@ -86,6 +96,9 @@ export const manifest: ProductManifest = {
engineeringAnalyticsPullRequestList: (): string => '/engineering-analytics/pull-requests',
engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',
engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',
+ engineeringAnalyticsTeams: (): string => '/engineering-analytics/teams',
+ engineeringAnalyticsTeam: (ownerTeam: string): string =>
+ `/engineering-analytics/teams/${encodeURIComponent(ownerTeam)}`,
engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>
`/engineering-analytics/repos/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/pull-requests/${number}`,
engineeringAnalyticsWorkflowRun: (repoOwner: string, repoName: string, runId: number | string): string =>
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index fab9b9e6b7ce..0229a2ce4b0c 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -167,6 +167,34 @@ tools:
github_workflow_jobs), which you can query directly with SQL or save as SQL insights and subscriptions when
the named tools don't fit (timestamps land as strings; parse with parseDateTimeBestEffort).
feature_flag: engineering-analytics
+ engineering-analytics-team-ci-activity:
+ operation: engineering_analytics_team_ci_activity
+ enabled: false
+ engineering-analytics-team-ci-health:
+ operation: engineering_analytics_team_ci_health
+ enabled: true
+ scopes:
+ - engineering_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: Team CI health roster
+ description: >
+ Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d,
+ maximum 30 days): flaky-test count (same qualification bar as the flaky-test leaderboard), failed/error span
+ count, and pass-on-retry count, each with 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
+ (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team 'unowned' (a
+ nonempty 'unowned' row means ownership gaps, not a real team). 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
+ enabled: false
engineering-analytics-workflow-jobs:
operation: engineering_analytics_workflow_jobs
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index c28e54140844..24bc0016663a 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2696,6 +2696,21 @@
},
"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): flaky-test count (same qualification bar as the flaky-test leaderboard), failed/error span count, and pass-on-retry count, each with 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 (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team). 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",
+ "title": "Team CI health roster",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "engineering-analytics"
+ },
"engineering-analytics-workflow-jobs": {
"description": "The jobs of a single workflow run attempt, each with its status, conclusion, wall-clock duration_seconds, runner tier (runner_provider / runner_label), and estimated_cost_usd. Use this to see where a run spent its time and money job-by-job, or to find the slow or expensive job in a run. Scoped to one run_attempt (the latest unless you pass run_attempt) so a re-run's attempts don't merge. estimated_cost_usd is null for free GitHub-hosted, non-Linux, or unfinished jobs. Returns an empty list when the job-level source isn't synced yet.",
"category": "Engineering analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index b1aacf73e3fc..629374ff95d7 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2739,6 +2739,21 @@
},
"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): flaky-test count (same qualification bar as the flaky-test leaderboard), failed/error span count, and pass-on-retry count, each with 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 (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team). 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",
+ "title": "Team CI health roster",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "engineering-analytics"
+ },
"engineering-analytics-workflow-jobs": {
"description": "The jobs of a single workflow run attempt, each with its status, conclusion, wall-clock duration_seconds, runner tier (runner_provider / runner_label), and estimated_cost_usd. Use this to see where a run spent its time and money job-by-job, or to find the slow or expensive job in a run. Scoped to one run_attempt (the latest unless you pass run_attempt) so a re-run's attempts don't merge. estimated_cost_usd is null for free GitHub-hosted, non-Linux, or unfinished jobs. Returns an empty list when the job-level source isn't synced yet.",
"category": "Engineering analytics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9b334b592384..964b3650afab 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -61693,6 +61693,86 @@ export namespace Schemas {
readonly events_retention_enforced: boolean;
}
+ export interface TeamTestSignal {
+ /** Reconstructed pytest nodeid (the CI span name), a stable grouping key. */
+ nodeid: string;
+ /** Runnable pytest selector; exact when the CI reporter emitted it. */
+ selector: string;
+ /** Failed + error + pass-on-retry spans in the current window (xfail excluded). */
+ signal_count: number;
+ /** Same count over the equal-length window before date_from. */
+ signal_count_prior: number;
+ /** Most recent signal span for this test, either window. */
+ last_seen_at: string;
+ }
+
+ export interface TeamCIActivity {
+ /** The team's owned tests with signal in either window, ranked by the stronger window's count (the current-vs-prior pairs behind a before/after comparison). */
+ tests: TeamTestSignal[];
+ /** The team slug this activity is scoped to, or 'unowned'. */
+ owner_team: string;
+ /** True when more owned tests had signal than the test cap. */
+ truncated_tests: boolean;
+ }
+
+ 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. */
+ owner_team: string;
+ /** Owned tests meeting the flaky-leaderboard bar in the window (passed on retry or failed on enough distinct PRs). Compare with flaky_test_count_prior for the delta. */
+ flaky_test_count: number;
+ /** Same count over the equal-length window immediately before date_from. */
+ flaky_test_count_prior: number;
+ /** Signal spans on owned tests with final outcome 'failed' or 'error' in the window. An absolute count, not a rate: fast passing runs are not emitted. */
+ failed_count: number;
+ /** Same count over the prior window. */
+ failed_count_prior: number;
+ /** Spans on owned tests that failed, then passed on an automatic retry, the strongest flaky signal. Only rerun-enabled CI lanes emit it. */
+ rerun_passed_count: number;
+ /** Same count over the prior window. */
+ rerun_passed_count_prior: number;
+ /** Spans on owned tests that failed while quarantined (xfail): masked in CI but still flaky. */
+ xfailed_count: number;
+ /** Same count over the prior window. */
+ xfailed_count_prior: number;
+ /** Most recent signal span across the team's owned tests, either window. */
+ last_seen_at: string;
+ }
+
+ export interface TeamCIHealthList {
+ /** Owning teams ranked by current flaky + failure signal, heaviest first, capped at `limit`. Teams are organizational owners of code surfaces; this never aggregates by author. */
+ items: TeamCIHealthItem[];
+ /** True when more teams had signal than the cap. */
+ truncated: boolean;
+ /** Maximum number of teams returned in `items`. */
+ limit: number;
+ }
+
+ export interface TeamMergeTrendPoint {
+ /** Start of the day bucket (team timezone), keyed on merged_at. */
+ day: string;
+ /**
+ * Median open→merge seconds of the PRs this team's members merged that day; null on a day the team merged nothing.
+ * @nullable
+ */
+ median_seconds: number | null;
+ /**
+ * Average open→merge seconds over the same merges; diverges above the median when a few long-running PRs drag the mean. Null on a day the team merged nothing.
+ * @nullable
+ */
+ average_seconds: number | null;
+ /** Merged PRs behind that day's median and average. */
+ merged_count: number;
+ }
+
+ export interface TeamMergeTrend {
+ /** Daily median and average open→merge over the PRs this team's members merged, ascending by day. Coarse timing (open→merge combines draft and review time); bots excluded. */
+ points: TeamMergeTrendPoint[];
+ /** The team slug this trend is scoped to. */
+ owner_team: string;
+ /** False when the GitHub source has no team_members snapshot synced: the trend then has no honest team attribution and `points` is empty. */
+ has_membership_data: boolean;
+ }
+
export type TestHogRequestConditionsItem = { [key: string]: unknown };
export interface TestHogRequest {
@@ -72301,6 +72381,75 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsTeamCiActivityParams = {
+ /**
+ * Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window may span at most 30 days. An equal-length prior window feeds the *_prior twins; near the 30-day ceiling that prior window can reach past Traces retention, deflating *_prior counts.
+ */
+ date_from?: string;
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Owning team slug to scope to (as returned by team_ci_health), e.g. 'team-replay', or the literal 'unowned' for tests with no ownership stamp.
+ */
+ 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.
+ */
+ source_id?: string;
+ /**
+ * Maximum number of per-test signal rows to return (1-100). Defaults to 25.
+ */
+ test_limit?: number;
+ };
+
+ export type EngineeringAnalyticsTeamCiHealthParams = {
+ /**
+ * Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window may span at most 30 days. An equal-length prior window is scanned for the *_prior twins; near the 30-day ceiling that prior window can reach past Traces retention, deflating *_prior counts and overstating deltas.
+ */
+ date_from?: string;
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Maximum number of teams to return (1-200). Defaults to 100.
+ */
+ limit?: number;
+ /**
+ * A test counts as flaky once it failed on at least this many distinct pull requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.
+ */
+ min_failed_prs?: number;
+ /**
+ * A test counts as flaky once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.
+ */
+ min_rerun_passes?: number;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ };
+
+ export type EngineeringAnalyticsTeamMergeTrendParams = {
+ /**
+ * Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window may span at most 30 days.
+ */
+ date_from?: string;
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Team slug to scope to (as returned by team_ci_health), matched against the GitHub org team slug of the source's team_members snapshot. The literal 'unowned' names an ownership gap, not an org team, and has no merge trend.
+ */
+ 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.
+ */
+ source_id?: string;
+ };
+
export type EngineeringAnalyticsWorkflowHealthParams = {
/**
* Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 058ddcece493..59f25cca43c8 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 11 enabled ops
+ * PostHog API - MCP 12 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -188,6 +188,46 @@ export const EngineeringAnalyticsSourcesParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Per-owning-team rollup of the CI test surfaces each team owns: flaky-test count, failure and pass-on-retry span counts, each with 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 (products/*\/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team 'unowned'. Teams are organizational owners of code surfaces, never authors. All figures are absolute counts, never rates: fast passing runs are not emitted, so denominators are biased. Pass-on-retry counts only flow from CI lanes running with reruns enabled; in other lanes a flake surfaces as a plain failure, which the distinct-PR count catches.
+ */
+export const EngineeringAnalyticsTeamCiHealthParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const EngineeringAnalyticsTeamCiHealthQueryParams = /* @__PURE__ */ zod.object({
+ date_from: zod
+ .string()
+ .optional()
+ .describe(
+ "Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window may span at most 30 days. An equal-length prior window is scanned for the *_prior twins; near the 30-day ceiling that prior window can reach past Traces retention, deflating *_prior counts and overstating deltas."
+ ),
+ date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),
+ limit: zod.number().optional().describe('Maximum number of teams to return (1-200). Defaults to 100.'),
+ min_failed_prs: zod
+ .number()
+ .optional()
+ .describe(
+ 'A test counts as flaky once it failed on at least this many distinct pull requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.'
+ ),
+ min_rerun_passes: zod
+ .number()
+ .optional()
+ .describe(
+ 'A test counts as flaky once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.'
+ ),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
+})
+
/**
* Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed by hour/day/week to fit the window. p50/p95 are over successful runs only, so cancelled (superseded) and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, or to attributed pull-request runs via `run_scope=pull_request`. Use this for 'is CI getting slower' and 'which workflow is the long pole'; compare two windows to get a trend.
*/
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index e4753a83ebb2..0647984767a5 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -10,6 +10,7 @@ import {
EngineeringAnalyticsPrLifecycleQueryParams,
EngineeringAnalyticsPullRequestsQueryParams,
EngineeringAnalyticsRunFailureLogsQueryParams,
+ EngineeringAnalyticsTeamCiHealthQueryParams,
EngineeringAnalyticsWorkflowHealthQueryParams,
EngineeringAnalyticsWorkflowJobsQueryParams,
EngineeringAnalyticsWorkflowRunnerCostsQueryParams,
@@ -148,6 +149,32 @@ const engineeringAnalyticsSources = (): ToolBase<
},
})
+const EngineeringAnalyticsTeamCiHealthSchema = EngineeringAnalyticsTeamCiHealthQueryParams
+
+const engineeringAnalyticsTeamCiHealth = (): ToolBase<
+ typeof EngineeringAnalyticsTeamCiHealthSchema,
+ WithPostHogUrl<Schemas.TeamCIHealthList>
+> => ({
+ name: 'engineering-analytics-team-ci-health',
+ schema: EngineeringAnalyticsTeamCiHealthSchema,
+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsTeamCiHealthSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.TeamCIHealthList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/team_ci_health/`,
+ query: {
+ date_from: params.date_from,
+ date_to: params.date_to,
+ limit: params.limit,
+ min_failed_prs: params.min_failed_prs,
+ min_rerun_passes: params.min_rerun_passes,
+ source_id: params.source_id,
+ },
+ })
+ return await withPostHogUrl(context, result, '/engineering-analytics')
+ },
+})
+
const EngineeringAnalyticsWorkflowJobsSchema = EngineeringAnalyticsWorkflowJobsQueryParams
const engineeringAnalyticsWorkflowJobs = (): ToolBase<
@@ -280,6 +307,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'engineering-analytics-pr-cost': engineeringAnalyticsPrCost,
'engineering-analytics-run-failure-logs': engineeringAnalyticsRunFailureLogs,
'engineering-analytics-sources': engineeringAnalyticsSources,
+ 'engineering-analytics-team-ci-health': engineeringAnalyticsTeamCiHealth,
'engineering-analytics-workflow-jobs': engineeringAnalyticsWorkflowJobs,
'engineering-analytics-workflow-runner-costs': engineeringAnalyticsWorkflowRunnerCosts,
'pr-lifecycle': prLifecycle,