:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(engineering-analytics): add team and author detail to friction (#106009)
Julian Bez248c1f099e38
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 58c0d5f8b131..5ffbea87b09b 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -24,6 +24,7 @@ from posthog.models.team import Teamfrom products.engineering_analytics.backend import logicfrom products.engineering_analytics.backend.facade.contracts import (+ AuthorFrictionDetail,AuthorFrictionList,BranchPRMatch,BrokenTestsResult,@@ -42,6 +43,7 @@ from products.engineering_analytics.backend.facade.contracts import (MergedPullRequest,PRCostSummary,PRLifecycle,+ PullRequestFrictionDetail,PullRequestList,PullRequestTimelines,QuarantineFile,@@ -296,6 +298,34 @@ def get_author_friction()+def get_author_friction_detail(+ *,+ team: Team,+ author: str,+ source_id: str | None = None,+ repo: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> AuthorFrictionDetail:+ """One author's friction next to their teams, and the pull requests that added the most of it."""+ return logic.build_author_friction_detail(+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), author=author+ )+++def get_pull_request_friction(+ *,+ team: Team,+ pr_number: int,+ repo: str,+ source_id: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> PullRequestFrictionDetail:+ """One merged pull request's friction as a multiple of the typical pull request, with the counts behind it."""+ return logic.build_pull_request_friction(+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), repo=repo, number=pr_number+ )++def get_delivery_summary(*,team: Team,diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 9e2c152dfd89..a4adeaf8a806 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -1789,6 +1789,74 @@ class AuthorFriction:rank: intrank_low: intrank_high: int+ # The author's GitHub teams, empty when the membership table is not synced.+ teams: list[str] = field(default_factory=list)+++@dataclass(frozen=True)+class TeamFriction:+ """A team's median member friction. Shown only above a floor of scored members, so one or two people+ never read as a team's figure (SPEC §2)."""++ github_team: str+ median_score: float+ scored_author_count: int+++@dataclass(frozen=True)+class PullRequestFrictionItem:+ """One pull request's friction, as a multiple of the typical pull request in the repository."""++ number: int+ repo_owner: str+ repo_name: str+ title: str+ score: float+ groups: list[FrictionGroupShare]+++@dataclass(frozen=True)+class AuthorFrictionDetail:+ available: bool+ window_days: int+ ranked_author_count: int+ has_membership_data: bool+ # None when the author has fewer merged pull requests than a score needs.+ author: AuthorFriction | None+ pr_count: int+ # The author's teams without the author, each only above the floor of other scored members.+ teams: list[TeamFriction]+ pull_requests: list[PullRequestFrictionItem]+++@dataclass(frozen=True)+class PullRequestFrictionBreakdown:+ """One merged pull request's friction, and the counts from the per-PR friction view behind it."""++ score: float+ groups: list[FrictionGroupShare]+ flake_red_count: int+ master_red_count: int+ unknown_red_count: int+ own_red_count: int+ futile_rerun_count: int+ push_count: int+ # CI running time of each push, oldest first.+ ci_wait_seconds: list[float]+ # None when the pull request's ready-for-review moment or first approval is not observed.+ first_approval_wait_seconds: float | None+ pushes_after_approval: int | None+ # None when the pull request never entered the merge queue.+ queue_seconds: float | None+ kickout_count: int | None+++@dataclass(frozen=True)+class PullRequestFrictionDetail:+ available: bool+ window_days: int+ # None when the pull request did not merge in the window, or a bot authored it.+ pull_request: PullRequestFrictionBreakdown | None@dataclass(frozen=True)@@ -1801,6 +1869,8 @@ class AuthorFrictionList:github_team: str | Nonehas_membership_data: boolitems: list[AuthorFriction]+ # Every team above the floor of scored members, most friction first.+ teams: list[TeamFriction] = field(default_factory=list)@dataclass(frozen=True)diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 038b325d3695..839754d3a6f0 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -28,7 +28,11 @@ from products.engineering_analytics.backend.logic.delivery_scope import (SummaryScope as SummaryScope,)from products.engineering_analytics.backend.logic.dora import build_dora_overview as build_dora_overview-from products.engineering_analytics.backend.logic.friction import build_author_friction as build_author_friction+from products.engineering_analytics.backend.logic.friction import (+ build_author_friction as build_author_friction,+ build_author_friction_detail as build_author_friction_detail,+ build_pull_request_friction as build_pull_request_friction,+)from products.engineering_analytics.backend.logic.github_teams import (build_github_team_roster as build_github_team_roster,)diff --git a/products/engineering_analytics/backend/logic/friction.py b/products/engineering_analytics/backend/logic/friction.pyindex 50b12539fba5..b33da5087ed6 100644--- a/products/engineering_analytics/backend/logic/friction.py+++ b/products/engineering_analytics/backend/logic/friction.py@@ -28,9 +28,14 @@ from posthog.dataclasses import frozenfrom products.engineering_analytics.backend.facade.contracts import (AuthorFriction,+ AuthorFrictionDetail,AuthorFrictionList,FrictionGroup,FrictionGroupShare,+ PullRequestFrictionBreakdown,+ PullRequestFrictionDetail,+ PullRequestFrictionItem,+ TeamFriction,)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.views import pr_friction@@ -51,6 +56,11 @@ QUEUE_FREE_SECONDS = 30 * 60APPROVAL_WAIT_REFERENCE_HOURS = 8APPROVAL_SLOW_HOURS = 24BOOTSTRAP_ROUNDS = 20+# A team list shows a team's median only above this many scored members. Next to one author, the team+# baseline needs this many others besides the author (SPEC §2 noise floor).+MIN_TEAM_AUTHORS = 3+MIN_OTHER_TEAM_AUTHORS = 2+TOP_PULL_REQUESTS = 5_BOOTSTRAP_SEED = 20260924@@ -59,6 +69,8 @@ class PullRequestFriction:"""One row of the per-PR friction view."""number: int+ repo_owner: str+ repo_name: strauthor: strauthor_avatar_url: strpush_count: int@@ -189,6 +201,13 @@ class _RankBand:high: int+@frozen+class _PullRequestScore:+ pr: PullRequestFriction+ score: float+ groups: dict[FrictionGroup, float]++class FrictionScorer:"""Scores every author with at least ``MIN_PULL_REQUESTS`` pull requests against each other."""@@ -196,6 +215,7 @@ class FrictionScorer:by_author: dict[str, list[PullRequestFriction]] = {}for pr in pull_requests:by_author.setdefault(pr.author, []).append(pr)+ self._by_author = by_authorself._authors = sorted(author for author, prs in by_author.items() if len(prs) >= MIN_PULL_REQUESTS)self._avatars = {author: next((pr.author_avatar_url for pr in reversed(prs) if pr.author_avatar_url), "")@@ -207,15 +227,24 @@ class FrictionScorer:author: [[metric.value(pr) for pr in by_author[author]] for metric in METRICS] for author in self._authors}- def _score(self, values: dict[str, list[list[float | None]]]) -> list[_AuthorScore]:- present = {+ @staticmethod+ def _present(values: dict[str, list[list[float | None]]]) -> dict[str, list[list[float]]]:+ return {author: [[v for v in metric_values if v is not None] for metric_values in author_values]for author, author_values in values.items()}++ @staticmethod+ def _pooled(present: dict[str, list[list[float]]]) -> list[float]:pooled = []for m in range(len(METRICS)):everything = [v for author_values in present.values() for v in author_values[m]]pooled.append(statistics.fmean(everything) if everything else 0.0)+ return pooled++ def _score(self, values: dict[str, list[list[float | None]]]) -> list[_AuthorScore]:+ present = self._present(values)+ pooled = self._pooled(present)shrunk = {author: [(sum(author_values[m]) + SHRINKAGE * pooled[m]) / (len(author_values[m]) + SHRINKAGE)@@ -260,7 +289,30 @@ class FrictionScorer:bands[author] = _RankBand(low=math.floor(deciles[0]), high=math.ceil(deciles[-1]))return bands- def score(self) -> list[AuthorFriction]:+ def pull_request_scores(self, author: str) -> list[_PullRequestScore]:+ """Each of the author's pull requests as a multiple of the typical pull request, with the group split.++ The typical pull request pools every pull request in the window, not only those of scored authors,+ so a repository where nobody has enough pull requests to score still has a baseline."""+ everyone = {+ author: [[metric.value(pr) for pr in prs] for metric in METRICS] for author, prs in self._by_author.items()+ }+ pooled = self._pooled(self._present(everyone))+ weight_in_use = sum(w for m, w in enumerate(self._weights) if pooled[m] > 0)+ scored: list[_PullRequestScore] = []+ for pr in self._by_author.get(author, []):+ groups = dict.fromkeys(GROUP_WEIGHTS, 0.0)+ for m, metric in enumerate(METRICS):+ value = metric.value(pr)+ if value is not None and pooled[m] > 0:+ groups[metric.group] += self._weights[m] / weight_in_use * value / pooled[m]+ scored.append(_PullRequestScore(pr=pr, score=sum(groups.values()), groups=groups))+ return scored++ def pr_count(self, author: str) -> int:+ return len(self._by_author.get(author, []))++ def score(self, teams_by_author: dict[str, list[str]] | None = None) -> list[AuthorFriction]:"""Every scored author, most friction first."""if not self._authors:return []@@ -278,6 +330,7 @@ class FrictionScorer:rank=ranks[s.author],rank_low=min(bands[s.author].low, ranks[s.author]),rank_high=max(bands[s.author].high, ranks[s.author]),+ teams=sorted((teams_by_author or {}).get(s.author.lower(), [])),)for s in scores),@@ -293,8 +346,12 @@ _FRICTION_SELECT = f"""WHERE NOT is_bot AND author != '' AND __REPO__"""-_TEAM_MEMBERS_SELECT = """- SELECT DISTINCT member_handle FROM __MEMBERS_SOURCE__ AS m WHERE team_slug = {team}+_MEMBERSHIPS_SELECT = """+ SELECT DISTINCT team_slug, member_handle FROM __MEMBERS_SOURCE__ AS m WHERE team_slug != '' AND member_handle != ''+"""++_TITLES_SELECT = """+ SELECT number, title FROM __PR_SOURCE__ AS pr WHERE number IN {numbers}"""@@ -327,6 +384,8 @@ def _query_pull_requests(curated: CuratedGitHubSource) -> list[PullRequestFrictireturn [PullRequestFriction(number=int(number),+ repo_owner=repo_owner or "",+ repo_name=repo_name or "",author=author,author_avatar_url=avatar_url or "",push_count=int(push_count),@@ -343,8 +402,8 @@ def _query_pull_requests(curated: CuratedGitHubSource) -> list[PullRequestFricti)for (number,- _repo_owner,- _repo_name,+ repo_owner,+ repo_name,author,avatar_url,push_count,@@ -362,23 +421,63 @@ def _query_pull_requests(curated: CuratedGitHubSource) -> list[PullRequestFricti]-def _query_team_members(curated: CuratedGitHubSource, github_team: str) -> set[str] | None:+def _query_memberships(curated: CuratedGitHubSource) -> dict[str, set[str]] | None:+ """Members by GitHub team, or None when the membership table is not synced."""members_source = curated.members_source()if members_source is None:return None+ rows = curated.run_paged(+ _MEMBERSHIPS_SELECT.replace("__MEMBERS_SOURCE__", members_source),+ page_key=(("team_slug", 0), ("member_handle", 1)),+ query_type="engineering_analytics.author_friction_memberships",+ placeholders={},+ )+ members: dict[str, set[str]] = {}+ # GitHub logins are case-insensitive and the snapshots do not agree on casing, so members and authors+ # match on the lowercased login, like the roster read.+ for team_slug, member_handle in rows:+ members.setdefault(team_slug, set()).add(member_handle.lower())+ return members+++def _query_titles(curated: CuratedGitHubSource, numbers: list[int]) -> dict[int, str]:+ if not numbers:+ return {}response = curated.run(- _TEAM_MEMBERS_SELECT.replace("__MEMBERS_SOURCE__", members_source),- query_type="engineering_analytics.author_friction_team_members",- placeholders={"team": ast.Constant(value=github_team)},+ _TITLES_SELECT.replace("__PR_SOURCE__", curated.pr_source()),+ query_type="engineering_analytics.author_friction_titles",+ placeholders={"numbers": ast.Constant(value=numbers)},)- return {handle for (handle,) in response.results or []}+ return {int(number): title or "" for number, title in response.results or []}+++def _teams_by_author(members: dict[str, set[str]]) -> dict[str, list[str]]:+ teams: dict[str, list[str]] = {}+ for team, handles in members.items():+ for handle in handles:+ teams.setdefault(handle, []).append(team)+ return teams+++def _team_friction(+ items: list[AuthorFriction], members: dict[str, set[str]], *, leave_out: str | None = None, floor: int+) -> list[TeamFriction]:+ left_out = leave_out.lower() if leave_out else None+ score_by_author = {item.author.lower(): item.score for item in items if item.author.lower() != left_out}+ teams = []+ for team, handles in members.items():+ scores = [score_by_author[handle] for handle in handles if handle in score_by_author]+ if len(scores) >= floor:+ teams.append(+ TeamFriction(github_team=team, median_score=statistics.median(scores), scored_author_count=len(scores))+ )+ return sorted(teams, key=lambda team: (-team.median_score, team.github_team))def build_author_friction(*, curated: CuratedGitHubSource, github_team: str | None = None) -> AuthorFrictionList:"""Every author's friction over the view's window, most first. A team keeps the repository-widescores and ranks and lists only its members, so a member's figures read the same on every page."""window_days = pr_friction.FRICTION_WINDOW.days- has_membership_data = curated.members_source() is not Nonepull_requests = _query_pull_requests(curated)if pull_requests is None:return AuthorFrictionList(@@ -386,19 +485,114 @@ def build_author_friction(*, curated: CuratedGitHubSource, github_team: str | Nowindow_days=window_days,ranked_author_count=0,github_team=github_team,- has_membership_data=has_membership_data,+ has_membership_data=curated.members_source() is not None,items=[],)- items = FrictionScorer(pull_requests).score()+ members = _query_memberships(curated)+ items = FrictionScorer(pull_requests).score(_teams_by_author(members or {}))ranked_author_count = len(items)+ teams = _team_friction(items, members or {}, floor=MIN_TEAM_AUTHORS)if github_team:- members = _query_team_members(curated, github_team) or set()- items = [item for item in items if item.author in members]+ team_members = (members or {}).get(github_team, set())+ items = [item for item in items if item.author.lower() in team_members]return AuthorFrictionList(available=True,window_days=window_days,ranked_author_count=ranked_author_count,github_team=github_team,- has_membership_data=has_membership_data,+ has_membership_data=members is not None,items=items,+ teams=teams,+ )+++def build_author_friction_detail(*, curated: CuratedGitHubSource, author: str) -> AuthorFrictionDetail:+ """One author's friction next to their teams, and the pull requests that added the most of it."""+ author = author.strip()+ if not author:+ raise ValueError("author is required")+ window_days = pr_friction.FRICTION_WINDOW.days+ pull_requests = _query_pull_requests(curated)+ if pull_requests is None:+ return AuthorFrictionDetail(+ available=False,+ window_days=window_days,+ ranked_author_count=0,+ has_membership_data=curated.members_source() is not None,+ author=None,+ pr_count=0,+ teams=[],+ pull_requests=[],+ )+ # GitHub logins are case-insensitive, so a typed URL finds the author under the casing the rows store.+ author = next((pr.author for pr in pull_requests if pr.author.lower() == author.lower()), author)+ members = _query_memberships(curated)+ scorer = FrictionScorer(pull_requests)+ items = scorer.score(_teams_by_author(members or {}))+ own_teams = {team: handles for team, handles in (members or {}).items() if author.lower() in handles}+ top = sorted(scorer.pull_request_scores(author), key=lambda scored: (-scored.score, -scored.pr.number))+ top = top[:TOP_PULL_REQUESTS]+ titles = _query_titles(curated, [scored.pr.number for scored in top])+ return AuthorFrictionDetail(+ available=True,+ window_days=window_days,+ ranked_author_count=len(items),+ has_membership_data=members is not None,+ author=next((item for item in items if item.author == author), None),+ pr_count=scorer.pr_count(author),+ teams=_team_friction(items, own_teams, leave_out=author, floor=MIN_OTHER_TEAM_AUTHORS),+ pull_requests=[+ PullRequestFrictionItem(+ number=scored.pr.number,+ repo_owner=scored.pr.repo_owner,+ repo_name=scored.pr.repo_name,+ title=titles.get(scored.pr.number, ""),+ score=scored.score,+ groups=[FrictionGroupShare(group=group, score=value) for group, value in scored.groups.items()],+ )+ for scored in top+ ],+ )+++def build_pull_request_friction(*, curated: CuratedGitHubSource, repo: str, number: int) -> PullRequestFrictionDetail:+ """One pull request's friction as a multiple of the typical pull request, with the counts behind it.++ The score needs the whole repository as its baseline, so the read scores every pull request in the+ window, the same way the author page does."""+ window_days = pr_friction.FRICTION_WINDOW.days+ pull_requests = _query_pull_requests(curated)+ if pull_requests is None:+ return PullRequestFrictionDetail(available=False, window_days=window_days, pull_request=None)+ # The source can fall back to another repository when ``repo`` matches none of its repositories, so+ # the number alone could pick a different repository's pull request.+ pr = next(+ (+ pr+ for pr in pull_requests+ if pr.number == number and f"{pr.repo_owner}/{pr.repo_name}".casefold() == repo.casefold()+ ),+ None,+ )+ if pr is None:+ return PullRequestFrictionDetail(available=True, window_days=window_days, pull_request=None)+ scored = next(s for s in FrictionScorer(pull_requests).pull_request_scores(pr.author) if s.pr is pr)+ return PullRequestFrictionDetail(+ available=True,+ window_days=window_days,+ pull_request=PullRequestFrictionBreakdown(+ score=scored.score,+ groups=[FrictionGroupShare(group=group, score=value) for group, value in scored.groups.items()],+ flake_red_count=pr.flake_red_count,+ master_red_count=pr.master_red_count,+ unknown_red_count=pr.unknown_red_count,+ own_red_count=pr.own_red_count,+ futile_rerun_count=pr.futile_rerun_count,+ push_count=pr.push_count,+ ci_wait_seconds=list(pr.ci_wait_seconds),+ first_approval_wait_seconds=pr.first_approval_wait_seconds,+ pushes_after_approval=pr.pushes_after_approval,+ queue_seconds=pr.queue_seconds,+ kickout_count=pr.kickout_count,+ ),)diff --git a/products/engineering_analytics/backend/presentation/serializers/friction.py b/products/engineering_analytics/backend/presentation/serializers/friction.pyindex 194c628bfd4d..42d6fb86fe7a 100644--- a/products/engineering_analytics/backend/presentation/serializers/friction.py+++ b/products/engineering_analytics/backend/presentation/serializers/friction.py@@ -4,8 +4,13 @@ from rest_framework_dataclasses.serializers import DataclassSerializerfrom products.engineering_analytics.backend.facade.contracts import (AuthorFriction,+ AuthorFrictionDetail,AuthorFrictionList,FrictionGroupShare,+ PullRequestFrictionBreakdown,+ PullRequestFrictionDetail,+ PullRequestFrictionItem,+ TeamFriction,)@@ -43,11 +48,42 @@ class AuthorFrictionSerializer(DataclassSerializer):"help_text": "High end of the rank band: the 90th percentile rank over the same resamples, and ""never below rank."},+ "teams": {"help_text": "The author's GitHub teams. Empty when the membership table isn't synced."},+ }+++class TeamFrictionSerializer(DataclassSerializer):+ class Meta:+ dataclass = TeamFriction+ extra_kwargs = {+ "github_team": {"help_text": "GitHub team slug."},+ "median_score": {"help_text": "The median friction of the team's scored members, in 'x typical' units."},+ "scored_author_count": {+ "help_text": "Members with enough merged pull requests to score. A team shows only above a floor, "+ "so one or two people never read as a team's figure."+ },+ }+++class PullRequestFrictionItemSerializer(DataclassSerializer):+ groups = FrictionGroupShareSerializer(many=True, help_text="The pull request's friction split by kind.")++ class Meta:+ dataclass = PullRequestFrictionItem+ extra_kwargs = {+ "number": {"help_text": "Pull request number."},+ "repo_owner": {"help_text": "Repository owner."},+ "repo_name": {"help_text": "Repository name."},+ "title": {"help_text": "Pull request title, empty when the snapshot has none."},+ "score": {"help_text": "Friction as a multiple of the typical pull request in the repository."},}class AuthorFrictionListSerializer(DataclassSerializer):items = AuthorFrictionSerializer(many=True, help_text="Authors by friction, most first.")+ teams = TeamFrictionSerializer(+ many=True, help_text="Teams with at least 3 scored members, by median member friction, most first."+ )class Meta:dataclass = AuthorFrictionList@@ -66,3 +102,71 @@ class AuthorFrictionListSerializer(DataclassSerializer):"help_text": "False when the team membership table isn't synced, so a team filter matches nobody."},}+++class AuthorFrictionDetailSerializer(DataclassSerializer):+ author = AuthorFrictionSerializer(+ allow_null=True, help_text="The author's score and rank. Null below 3 merged pull requests in the window."+ )+ teams = TeamFrictionSerializer(+ many=True,+ help_text="The author's teams without the author, each only with at least 2 other scored members.",+ )+ pull_requests = PullRequestFrictionItemSerializer(+ many=True, help_text="The author's pull requests that added the most friction, most first."+ )++ class Meta:+ dataclass = AuthorFrictionDetail+ extra_kwargs = {+ "available": {+ "help_text": "False when the per-PR friction view does not exist yet: it needs a GitHub source "+ "with workflow runs, workflow jobs and pull requests synced."+ },+ "window_days": {"help_text": "Pull requests merged in this many days before the view last refreshed."},+ "ranked_author_count": {"help_text": "Authors ranked in the repository: the denominator of rank."},+ "has_membership_data": {"help_text": "False when the team membership table isn't synced."},+ "pr_count": {"help_text": "The author's merged pull requests in the window."},+ }+++class PullRequestFrictionBreakdownSerializer(DataclassSerializer):+ groups = FrictionGroupShareSerializer(many=True, help_text="The pull request's friction split by kind.")++ class Meta:+ dataclass = PullRequestFrictionBreakdown+ extra_kwargs = {+ "score": {"help_text": "Friction as a multiple of the typical pull request in the repository."},+ "flake_red_count": {"help_text": "Red stretches that a re-run of the same commit turned green."},+ "master_red_count": {+ "help_text": "Red stretches where the same job failed on the default branch within 12 hours."+ },+ "unknown_red_count": {"help_text": "Red stretches with no provable cause."},+ "own_red_count": {"help_text": "Red stretches that a later push fixed."},+ "futile_rerun_count": {"help_text": "Re-runs that failed again."},+ "push_count": {"help_text": "Pushes that triggered CI."},+ "ci_wait_seconds": {"help_text": "CI running time of each push, oldest first."},+ "first_approval_wait_seconds": {+ "help_text": "From ready for review to the first approval. Null when either is not observed."+ },+ "pushes_after_approval": {"help_text": "Pushes after the first approval. Null without an approval."},+ "queue_seconds": {"help_text": "Time in the merge queue. Null when the pull request never entered it."},+ "kickout_count": {"help_text": "Times the merge queue removed the pull request. Null without queue data."},+ }+++class PullRequestFrictionDetailSerializer(DataclassSerializer):+ pull_request = PullRequestFrictionBreakdownSerializer(+ allow_null=True,+ help_text="Null when the pull request did not merge in the window, or a bot authored it.",+ )++ class Meta:+ dataclass = PullRequestFrictionDetail+ extra_kwargs = {+ "available": {+ "help_text": "False when the per-PR friction view does not exist yet: it needs a GitHub source "+ "with workflow runs, workflow jobs and pull requests synced."+ },+ "window_days": {"help_text": "Pull requests merged in this many days before the view last refreshed."},+ }diff --git a/products/engineering_analytics/backend/presentation/views/friction.py b/products/engineering_analytics/backend/presentation/views/friction.pyindex c2c1ecce4be5..532bf87d2458 100644--- a/products/engineering_analytics/backend/presentation/views/friction.py+++ b/products/engineering_analytics/backend/presentation/views/friction.py@@ -2,16 +2,22 @@from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema+from rest_framework import statusfrom rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom products.engineering_analytics.backend.facade import api-from products.engineering_analytics.backend.presentation.serializers.friction import AuthorFrictionListSerializer+from products.engineering_analytics.backend.presentation.serializers.friction import (+ AuthorFrictionDetailSerializer,+ AuthorFrictionListSerializer,+ PullRequestFrictionDetailSerializer,+)from products.engineering_analytics.backend.presentation.views._base import (_SOURCE_ID,EngineeringAnalyticsViewSetBase,_bad_request,+ _require_int_param,)_GITHUB_TEAM = OpenApiParameter(@@ -23,6 +29,14 @@ _GITHUB_TEAM = OpenApiParameter("repository-wide.",)+_AUTHOR = OpenApiParameter(+ name="author",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=True,+ description="GitHub login of the author to show.",+)+_REPO = OpenApiParameter(name="repo",type=OpenApiTypes.STR,@@ -32,8 +46,25 @@ _REPO = OpenApiParameter()+_PR_NUMBER = OpenApiParameter(+ name="pr_number",+ type=OpenApiTypes.INT,+ location=OpenApiParameter.QUERY,+ required=True,+ description="Pull request number to show.",+)++_PR_REPO = OpenApiParameter(+ name="repo",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=True,+ description="'owner/name' repository the pull request belongs to.",+)++class FrictionActionsMixin(EngineeringAnalyticsViewSetBase):- READ_ACTIONS = ["author_friction"]+ READ_ACTIONS = ["author_friction", "author_friction_detail", "pull_request_friction"]@extend_schema(operation_id="engineering_analytics_author_friction",@@ -62,3 +93,63 @@ class FrictionActionsMixin(EngineeringAnalyticsViewSetBase):except ValueError as exc:return _bad_request(exc, fallback="Invalid source_id or repo")return Response(AuthorFrictionListSerializer(instance=friction).data)++ @extend_schema(+ operation_id="engineering_analytics_author_friction_detail",+ parameters=[_AUTHOR, _SOURCE_ID, _REPO],+ responses={+ 200: AuthorFrictionDetailSerializer,+ 400: OpenApiResponse(description="Missing author, or invalid source_id or repo."),+ },+ description=(+ "One author's friction over pull requests merged in the last 30 days, next to the median of each of "+ "the author's teams, and the author's pull requests that added the most friction. Bots are excluded."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def author_friction_detail(self, request: Request, **kwargs) -> Response:+ author = request.query_params.get("author")+ if not author:+ return Response({"detail": "author is required"}, status=status.HTTP_400_BAD_REQUEST)+ try:+ detail = api.get_author_friction_detail(+ team=self.team,+ author=author,+ source_id=request.query_params.get("source_id") or None,+ repo=request.query_params.get("repo") or None,+ user_access_control=self.user_access_control,+ )+ except ValueError as exc:+ return _bad_request(exc, fallback="Invalid author, source_id or repo")+ return Response(AuthorFrictionDetailSerializer(instance=detail).data)++ @extend_schema(+ operation_id="engineering_analytics_pull_request_friction",+ parameters=[_PR_NUMBER, _PR_REPO, _SOURCE_ID],+ responses={+ 200: PullRequestFrictionDetailSerializer,+ 400: OpenApiResponse(description="Missing pr_number or repo, or invalid source_id."),+ },+ description=(+ "One merged pull request's friction as a multiple of the typical pull request, with the counts behind "+ "it: red CI by cause, re-runs that failed again, CI time per push, the wait for the first approval, "+ "merge-queue time and kickouts, and rework. Covers pull requests merged in the last 30 days."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def pull_request_friction(self, request: Request, **kwargs) -> Response:+ repo = request.query_params.get("repo")+ try:+ pr_number = _require_int_param(request, "pr_number")+ if not repo:+ raise ValueError("repo is required")+ detail = api.get_pull_request_friction(+ team=self.team,+ pr_number=pr_number,+ repo=repo,+ 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 repo or source_id")+ return Response(PullRequestFrictionDetailSerializer(instance=detail).data)diff --git a/products/engineering_analytics/backend/tests/test_friction.py b/products/engineering_analytics/backend/tests/test_friction.pyindex 16d6f3bf89da..0ef3bc8021cc 100644--- a/products/engineering_analytics/backend/tests/test_friction.py+++ b/products/engineering_analytics/backend/tests/test_friction.py@@ -16,8 +16,13 @@ from products.engineering_analytics.backend.logic.friction import (FrictionScorer,PullRequestFriction,build_author_friction,+ build_author_friction_detail,+ build_pull_request_friction,)+# "Typical" differs in case from the author login, as the membership snapshot can.+_MEMBERS = {"pair": ["typical", "calm"], "everyone": ["blocked", "Typical", "calm", "newcomer"]}+def _pr(author: str, number: int, **friction: Any) -> PullRequestFriction:values: dict[str, Any] = {@@ -34,7 +39,9 @@ def _pr(author: str, number: int, **friction: Any) -> PullRequestFriction:"kickout_count": 0,**friction,}- return PullRequestFriction(number=number, author=author, author_avatar_url="", **values)+ return PullRequestFriction(+ number=number, repo_owner="PostHog", repo_name="posthog", author=author, author_avatar_url="", **values+ )def _population() -> list[PullRequestFriction]:@@ -59,8 +66,8 @@ def _population() -> list[PullRequestFriction]:def _row(pr: PullRequestFriction) -> tuple:return (pr.number,- "PostHog",- "posthog",+ pr.repo_owner,+ pr.repo_name,pr.author,pr.author_avatar_url,pr.push_count,@@ -83,7 +90,7 @@ class _Curated:repository = "PostHog/posthog"source_id = "0192f000-0000-7000-8000-000000000001"- def __init__(self, rows: list[tuple] | None, members: list[str] | None) -> None:+ def __init__(self, rows: list[tuple] | None, members: dict[str, list[str]] | None) -> None:self._rows = rowsself._members = membersself.friction_placeholders: dict[str, Any] = {}@@ -91,14 +98,19 @@ class _Curated:def members_source(self) -> str | None:return None if self._members is None else "(SELECT 1)"- def run_paged(self, sql: str, **kwargs: Any) -> list[tuple]:+ def pr_source(self) -> str:+ return "(SELECT 1)"++ def run_paged(self, sql: str, *, query_type: str, **kwargs: Any) -> list[tuple]:+ if query_type == "engineering_analytics.author_friction_memberships":+ return [(team, handle) for team, handles in (self._members or {}).items() for handle in handles]self.friction_placeholders = kwargs["placeholders"]if self._rows is None:raise QueryError("Unknown table `engineering_analytics_pr_friction`.")return self._rows- def run(self, sql: str, **kwargs: Any) -> SimpleNamespace:- return SimpleNamespace(results=[(member,) for member in self._members or []])+ def run(self, sql: str, *, placeholders: dict[str, Any], **kwargs: Any) -> SimpleNamespace:+ return SimpleNamespace(results=[(number, f"PR {number}") for number in placeholders["numbers"].value])class TestFrictionScore(SimpleTestCase):@@ -125,28 +137,28 @@ class TestFrictionScore(SimpleTestCase):@parameterized.expand([- ("no_view_yet", None, ["typical"], None, False, []),- ("whole_repository", _population(), None, None, True, [("blocked", 1), ("typical", 2), ("calm", 3)]),+ ("no_view_yet", None, None, False, [], []),(- "team_keeps_repository_ranks",+ "whole_repository",_population(),- ["typical", "calm"],- "team-devex",+ None,True,- [("typical", 2), ("calm", 3)],+ [("blocked", 1), ("typical", 2), ("calm", 3)],+ ["everyone"],),+ ("team_keeps_repository_ranks", _population(), "pair", True, [("typical", 2), ("calm", 3)], ["everyone"]),])def test_read(self,_name: str,prs: list[PullRequestFriction] | None,- members: list[str] | None,github_team: str | None,available: bool,expected: list[tuple[str, int]],+ expected_teams: list[str],) -> None:- curated = _Curated([_row(pr) for pr in prs] if prs is not None else None, members)+ curated = _Curated([_row(pr) for pr in prs] if prs is not None else None, _MEMBERS)friction = build_author_friction(curated=curated, github_team=github_team) # type: ignore[arg-type]@@ -154,3 +166,60 @@ class TestFrictionScore(SimpleTestCase):assert [(item.author, item.rank) for item in friction.items] == expected# The view unions every source of the team, so the read must keep to its own.assert curated.friction_placeholders["source_id"].value == curated.source_id+ # A pair of scored members is below the team floor, so only the larger team shows.+ assert [team.github_team for team in friction.teams] == expected_teams++ @parameterized.expand(+ [+ ("scored_author", "typical", 2, ["everyone"], [205, 204, 203, 202, 201]),+ ("login_in_other_case", "TYPICAL", 2, ["everyone"], [205, 204, 203, 202, 201]),+ ("below_the_minimum", "newcomer", None, ["everyone"], [401, 400]),+ ]+ )+ def test_detail(self, _name: str, author: str, rank: int | None, teams: list[str], numbers: list[int]) -> None:+ curated = _Curated([_row(pr) for pr in _population()], _MEMBERS)++ detail = build_author_friction_detail(curated=curated, author=author) # type: ignore[arg-type]++ assert (detail.author.rank if detail.author else None) == rank+ # The author stays out of their own team baseline, so "pair" drops below two other members.+ assert [team.github_team for team in detail.teams] == teams+ assert [(pr.number, pr.title) for pr in detail.pull_requests] == [(n, f"PR {n}") for n in numbers]++ @parameterized.expand(+ [+ ("merged_in_window", _population(), "PostHog/posthog", 305, True, (2, 2)),+ ("not_in_window", _population(), "PostHog/posthog", 999, True, None),+ ("same_number_in_another_repository", _population(), "PostHog/posthog.com", 305, True, None),+ ("no_view_yet", None, "PostHog/posthog", 305, False, None),+ ]+ )+ def test_pull_request(+ self,+ _name: str,+ prs: list[PullRequestFriction] | None,+ repo: str,+ number: int,+ available: bool,+ counts: tuple[int, int] | None,+ ) -> None:+ curated = _Curated([_row(pr) for pr in prs] if prs is not None else None, _MEMBERS)++ detail = build_pull_request_friction(curated=curated, repo=repo, number=number) # type: ignore[arg-type]++ assert detail.available is available+ breakdown = detail.pull_request+ assert (None if breakdown is None else (breakdown.master_red_count, breakdown.kickout_count)) == counts+ if breakdown is not None:+ # The PR page and the author page's top list must agree on a pull request's score.+ author_page = build_author_friction_detail(curated=curated, author="blocked") # type: ignore[arg-type]+ listed = next(pr for pr in author_page.pull_requests if pr.number == number)+ assert breakdown.score == pytest.approx(listed.score)++ def test_pull_request_scores_when_nobody_has_enough_pull_requests(self) -> None:+ curated = _Curated([_row(_pr("newcomer", 700, master_red_count=2)), _row(_pr("other", 701))], _MEMBERS)++ detail = build_pull_request_friction(curated=curated, repo="PostHog/posthog", number=700) # type: ignore[arg-type]++ assert detail.pull_request is not None+ assert detail.pull_request.score > 1diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex adbbb42f06c6..11b3243f68cd 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -602,6 +602,8 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):("pr_runs_repo_missing", "pr_runs", {"pr_number": "10"}),("pr_cost_repo_missing", "pr_cost", {"pr_number": "10"}),("workflow_jobs_run_id_invalid", "workflow_jobs", {"run_id": "nope"}),+ ("author_friction_detail_author_missing", "author_friction_detail", {}),+ ("pull_request_friction_repo_missing", "pull_request_friction", {"pr_number": "10"}),])def test_bad_params_400(self, _name: str, action: str, params: dict[str, str]) -> None:diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 0d2a6f00eb7e..0f21903c2098 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -51,11 +51,24 @@ export interface AuthorFrictionApi {rank_low: number/** High end of the rank band: the 90th percentile rank over the same resamples, and never below rank. */rank_high: number+ /** The author's GitHub teams. Empty when the membership table isn't synced. */+ teams?: string[]+}++export interface TeamFrictionApi {+ /** GitHub team slug. */+ github_team: string+ /** The median friction of the team's scored members, in 'x typical' units. */+ median_score: number+ /** Members with enough merged pull requests to score. A team shows only above a floor, so one or two people never read as a team's figure. */+ scored_author_count: number}export interface AuthorFrictionListApi {/** Authors by friction, most first. */items: AuthorFrictionApi[]+ /** Teams with at least 3 scored members, by median member friction, most first. */+ teams: TeamFrictionApi[]/** False when the per-PR friction view does not exist yet: it needs a GitHub source with workflow runs, workflow jobs and pull requests synced. */available: boolean/** Pull requests merged in this many days before the view last refreshed. */@@ -71,6 +84,40 @@ export interface AuthorFrictionListApi {has_membership_data: boolean}+export interface PullRequestFrictionItemApi {+ /** The pull request's friction split by kind. */+ groups: FrictionGroupShareApi[]+ /** Pull request number. */+ number: number+ /** Repository owner. */+ repo_owner: string+ /** Repository name. */+ repo_name: string+ /** Pull request title, empty when the snapshot has none. */+ title: string+ /** Friction as a multiple of the typical pull request in the repository. */+ score: number+}++export interface AuthorFrictionDetailApi {+ /** The author's score and rank. Null below 3 merged pull requests in the window. */+ author: AuthorFrictionApi | null+ /** The author's teams without the author, each only with at least 2 other scored members. */+ teams: TeamFrictionApi[]+ /** The author's pull requests that added the most friction, most first. */+ pull_requests: PullRequestFrictionItemApi[]+ /** False when the per-PR friction view does not exist yet: it needs a GitHub source with workflow runs, workflow jobs and pull requests synced. */+ available: boolean+ /** Pull requests merged in this many days before the view last refreshed. */+ window_days: number+ /** Authors ranked in the repository: the denominator of rank. */+ ranked_author_count: number+ /** False when the team membership table isn't synced. */+ has_membership_data: boolean+ /** The author's merged pull requests in the window. */+ pr_count: number+}+export interface WorkflowCostApi {/** GitHub Actions workflow name this cost is for. */workflow_name: string@@ -1036,6 +1083,56 @@ export interface WorkflowRunDetailApi {is_merge_queue: boolean}+export interface PullRequestFrictionBreakdownApi {+ /** The pull request's friction split by kind. */+ groups: FrictionGroupShareApi[]+ /** Friction as a multiple of the typical pull request in the repository. */+ score: number+ /** Red stretches that a re-run of the same commit turned green. */+ flake_red_count: number+ /** Red stretches where the same job failed on the default branch within 12 hours. */+ master_red_count: number+ /** Red stretches with no provable cause. */+ unknown_red_count: number+ /** Red stretches that a later push fixed. */+ own_red_count: number+ /** Re-runs that failed again. */+ futile_rerun_count: number+ /** Pushes that triggered CI. */+ push_count: number+ /** CI running time of each push, oldest first. */+ ci_wait_seconds: number[]+ /**+ * From ready for review to the first approval. Null when either is not observed.+ * @nullable+ */+ first_approval_wait_seconds: number | null+ /**+ * Pushes after the first approval. Null without an approval.+ * @nullable+ */+ pushes_after_approval: number | null+ /**+ * Time in the merge queue. Null when the pull request never entered it.+ * @nullable+ */+ queue_seconds: number | null+ /**+ * Times the merge queue removed the pull request. Null without queue data.+ * @nullable+ */+ kickout_count: number | null+}++export interface PullRequestFrictionDetailApi {+ /** Null when the pull request did not merge in the window, or a bot authored it. */+ pull_request: PullRequestFrictionBreakdownApi | null+ /** False when the per-PR friction view does not exist yet: it needs a GitHub source with workflow runs, workflow jobs and pull requests synced. */+ available: boolean+ /** Pull requests merged in this many days before the view last refreshed. */+ window_days: number+}+export interface PRTimelinePushApi {/** The pushed head commit. */head_sha: string@@ -2170,6 +2267,21 @@ export type EngineeringAnalyticsAuthorFrictionParams = {source_id?: string}+export type EngineeringAnalyticsAuthorFrictionDetailParams = {+ /**+ * GitHub login of the author to show.+ */+ author: string+ /**+ * 'owner/name' repository, when the selected source syncs several.+ */+ repo?: 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 EngineeringAnalyticsAuthorWorkflowCostsParams = {/*** GitHub handle whose CI spend to break down.@@ -2483,6 +2595,21 @@ export type EngineeringAnalyticsPrRunsParams = {source_id?: string}+export type EngineeringAnalyticsPullRequestFrictionParams = {+ /**+ * Pull request number to show.+ */+ pr_number: number+ /**+ * 'owner/name' repository the pull request belongs to.+ */+ repo: 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 EngineeringAnalyticsPullRequestTimelinesParams = {/*** GitHub login: scope the read to this author's pull requests. Pass exactly one scope.diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex f74c2163cee6..cc1ff35e5bec 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ AuthorFrictionDetailApi,AuthorFrictionListApi,BranchPRMatchApi,BrokenTestsResultApi,@@ -20,6 +21,7 @@ import type {DeliveryComparisonApi,DeliverySummaryApi,DoraOverviewApi,+ EngineeringAnalyticsAuthorFrictionDetailParams,EngineeringAnalyticsAuthorFrictionParams,EngineeringAnalyticsAuthorWorkflowCostsParams,EngineeringAnalyticsBrokenTestsParams,@@ -35,6 +37,7 @@ import type {EngineeringAnalyticsPrCostParams,EngineeringAnalyticsPrLifecycleParams,EngineeringAnalyticsPrRunsParams,+ EngineeringAnalyticsPullRequestFrictionParams,EngineeringAnalyticsPullRequestTimelinesParams,EngineeringAnalyticsPullRequestsParams,EngineeringAnalyticsQuarantineParams,@@ -57,6 +60,7 @@ import type {MasterFailureGroupApi,PRCostSummaryApi,PRLifecycleApi,+ PullRequestFrictionDetailApi,PullRequestListApi,PullRequestTimelinesApi,QuarantineFileApi,@@ -110,6 +114,39 @@ export const engineeringAnalyticsAuthorFriction = async (})}+export const getEngineeringAnalyticsAuthorFrictionDetailUrl = (+ projectId: string,+ params: EngineeringAnalyticsAuthorFrictionDetailParams+) => {+ 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/author_friction_detail/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/author_friction_detail/`+}++/**+ * One author's friction over pull requests merged in the last 30 days, next to the median of each of the author's teams, and the author's pull requests that added the most friction. Bots are excluded.+ */+export const engineeringAnalyticsAuthorFrictionDetail = async (+ projectId: string,+ params: EngineeringAnalyticsAuthorFrictionDetailParams,+ options?: RequestInit+): Promise<AuthorFrictionDetailApi> => {+ return apiMutator<AuthorFrictionDetailApi>(getEngineeringAnalyticsAuthorFrictionDetailUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsAuthorWorkflowCostsUrl = (projectId: string,params: EngineeringAnalyticsAuthorWorkflowCostsParams@@ -606,6 +643,39 @@ export const engineeringAnalyticsPrRuns = async (})}+export const getEngineeringAnalyticsPullRequestFrictionUrl = (+ projectId: string,+ params: EngineeringAnalyticsPullRequestFrictionParams+) => {+ 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/pull_request_friction/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/pull_request_friction/`+}++/**+ * One merged pull request's friction as a multiple of the typical pull request, with the counts behind it: red CI by cause, re-runs that failed again, CI time per push, the wait for the first approval, merge-queue time and kickouts, and rework. Covers pull requests merged in the last 30 days.+ */+export const engineeringAnalyticsPullRequestFriction = async (+ projectId: string,+ params: EngineeringAnalyticsPullRequestFrictionParams,+ options?: RequestInit+): Promise<PullRequestFrictionDetailApi> => {+ return apiMutator<PullRequestFrictionDetailApi>(getEngineeringAnalyticsPullRequestFrictionUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsPullRequestTimelinesUrl = (projectId: string,params?: EngineeringAnalyticsPullRequestTimelinesParamsdiff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex 65458aeaac56..164ac1229193 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -12,6 +12,9 @@ tools:engineering-analytics-author-friction:operation: engineering_analytics_author_frictionenabled: false+ engineering-analytics-author-friction-detail:+ operation: engineering_analytics_author_friction_detail+ enabled: falseengineering-analytics-author-workflow-costs:operation: engineering_analytics_author_workflow_costsenabled: false@@ -168,6 +171,9 @@ tools:engineering-analytics-pr-runs:operation: engineering_analytics_pr_runsenabled: false+ engineering-analytics-pull-request-friction:+ operation: engineering_analytics_pull_request_friction+ enabled: falseengineering-analytics-pull-request-timelines:operation: engineering_analytics_pull_request_timelinesenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 65d1902b666f..1661f9563c33 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11554,11 +11554,58 @@ export namespace Schemas {rank_low: number;/** High end of the rank band: the 90th percentile rank over the same resamples, and never below rank. */rank_high: number;+ /** The author's GitHub teams. Empty when the membership table isn't synced. */+ teams?: string[];+ }++ export interface TeamFriction {+ /** GitHub team slug. */+ github_team: string;+ /** The median friction of the team's scored members, in 'x typical' units. */+ median_score: number;+ /** Members with enough merged pull requests to score. A team shows only above a floor, so one or two people never read as a team's figure. */+ scored_author_count: number;+ }++ export interface PullRequestFrictionItem {+ /** The pull request's friction split by kind. */+ groups: FrictionGroupShare[];+ /** Pull request number. */+ number: number;+ /** Repository owner. */+ repo_owner: string;+ /** Repository name. */+ repo_name: string;+ /** Pull request title, empty when the snapshot has none. */+ title: string;+ /** Friction as a multiple of the typical pull request in the repository. */+ score: number;+ }++ export interface AuthorFrictionDetail {+ /** The author's score and rank. Null below 3 merged pull requests in the window. */+ author: AuthorFriction | null;+ /** The author's teams without the author, each only with at least 2 other scored members. */+ teams: TeamFriction[];+ /** The author's pull requests that added the most friction, most first. */+ pull_requests: PullRequestFrictionItem[];+ /** False when the per-PR friction view does not exist yet: it needs a GitHub source with workflow runs, workflow jobs and pull requests synced. */+ available: boolean;+ /** Pull requests merged in this many days before the view last refreshed. */+ window_days: number;+ /** Authors ranked in the repository: the denominator of rank. */+ ranked_author_count: number;+ /** False when the team membership table isn't synced. */+ has_membership_data: boolean;+ /** The author's merged pull requests in the window. */+ pr_count: number;}export interface AuthorFrictionList {/** Authors by friction, most first. */items: AuthorFriction[];+ /** Teams with at least 3 scored members, by median member friction, most first. */+ teams: TeamFriction[];/** False when the per-PR friction view does not exist yet: it needs a GitHub source with workflow runs, workflow jobs and pull requests synced. */available: boolean;/** Pull requests merged in this many days before the view last refreshed. */@@ -81173,6 +81220,56 @@ export namespace Schemas {readonly comments: readonly PullRequestComment[];}+ export interface PullRequestFrictionBreakdown {+ /** The pull request's friction split by kind. */+ groups: FrictionGroupShare[];+ /** Friction as a multiple of the typical pull request in the repository. */+ score: number;+ /** Red stretches that a re-run of the same commit turned green. */+ flake_red_count: number;+ /** Red stretches where the same job failed on the default branch within 12 hours. */+ master_red_count: number;+ /** Red stretches with no provable cause. */+ unknown_red_count: number;+ /** Red stretches that a later push fixed. */+ own_red_count: number;+ /** Re-runs that failed again. */+ futile_rerun_count: number;+ /** Pushes that triggered CI. */+ push_count: number;+ /** CI running time of each push, oldest first. */+ ci_wait_seconds: number[];+ /**+ * From ready for review to the first approval. Null when either is not observed.+ * @nullable+ */+ first_approval_wait_seconds: number | null;+ /**+ * Pushes after the first approval. Null without an approval.+ * @nullable+ */+ pushes_after_approval: number | null;+ /**+ * Time in the merge queue. Null when the pull request never entered it.+ * @nullable+ */+ queue_seconds: number | null;+ /**+ * Times the merge queue removed the pull request. Null without queue data.+ * @nullable+ */+ kickout_count: number | null;+ }++ export interface PullRequestFrictionDetail {+ /** Null when the pull request did not merge in the window, or a bot authored it. */+ pull_request: PullRequestFrictionBreakdown | null;+ /** False when the per-PR friction view does not exist yet: it needs a GitHub source with workflow runs, workflow jobs and pull requests synced. */+ available: boolean;+ /** Pull requests merged in this many days before the view last refreshed. */+ window_days: number;+ }+export interface PushCISample {/** Head commit SHA of this push (CI round). */head_sha: string;@@ -108154,6 +108251,21 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsAuthorFrictionDetailParams = {+ /**+ * GitHub login of the author to show.+ */+ author: string;+ /**+ * 'owner/name' repository, when the selected source syncs several.+ */+ repo?: 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 EngineeringAnalyticsAuthorWorkflowCostsParams = {/*** GitHub handle whose CI spend to break down.@@ -108467,6 +108579,21 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsPullRequestFrictionParams = {+ /**+ * Pull request number to show.+ */+ pr_number: number;+ /**+ * 'owner/name' repository the pull request belongs to.+ */+ repo: 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 EngineeringAnalyticsPullRequestTimelinesParams = {/*** GitHub login: scope the read to this author's pull requests. Pass exactly one scope.