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(engineering-analytics): score author friction (#105975)

Julian Bez5574db45fc36
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 541f6c2f23ba..b58a2ec02243 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -655,6 +655,7 @@ SPECTACULAR_SETTINGS = {
"CITestRunnerEnum": "products.engineering_analytics.backend.facade.contracts.CITestRunner",
"PRTimelineSegmentKindEnum": "products.engineering_analytics.backend.facade.contracts.PRTimelineSegmentKind",
"DeliveryScopeKindEnum": "products.engineering_analytics.backend.facade.contracts.DeliveryScopeKind",
+ "FrictionGroupEnum": "products.engineering_analytics.backend.facade.contracts.FrictionGroup",
"UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES",
"DesktopAccessReasonEnum": "products.tasks.backend.facade.contracts.DESKTOP_ACCESS_REASON_SCHEMA_VALUES",
"LifecycleStatusEnum": "products.notebooks.backend.widget_models.WIDGET_LIFECYCLE_STATUS_CHOICES",
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 21d7e8a93d90..73b1415013a1 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -15,7 +15,7 @@ The goal is Signals for PostHog Desktop (README → "The goal"): Signal detectio
- Rating developers' performance, ever. Such rankings exist only to compare people.
- No read ranks, scores or compares people by what they produce or how fast they deliver: no leaderboards of merged pull requests, lines or lead time, no "who is slower", and no scorecard of an author's flaky tests. Another author's delivery figures come back only when the person asking named that author.
- - Friction is not performance. A read may score and order the friction developers meet: red CI they did not cause, re-runs that failed again, merge-queue kickouts, review waits and rework. The purpose is to find the people the dev loop costs most. A friction figure is a mean per pull request of what happened to the author, so shipping more or faster does not raise it. The pull request count only decides whether an author gets a score and how far a short record is pulled toward the typical author. Friction reads one fixed 30-day window of merged pull requests on every page, whatever the date picker says, so a pull request's score is the same on its own page and in its author's list. The per-pull-request inputs are defined once in `logic/views/pr_friction.py`.
+ - Friction is not performance. A read may score and order the friction developers meet: red CI they did not cause, re-runs that failed again, merge-queue kickouts, review waits and rework. The purpose is to find the people the dev loop costs most. A friction figure is a mean per pull request of what happened to the author, so shipping more or faster does not raise it. The pull request count only decides whether an author gets a score and how far a short record is pulled toward the typical author. Friction reads one fixed 30-day window of merged pull requests on every page, whatever the date picker says, so a pull request's score is the same on its own page and in its author's list. The inputs are defined once in `logic/friction.py`.
- The author-scoped _page_ is allowed: one author's pull requests, CI cost, delivery timing and lead time, each figure next to the same figure over the whole repository. It answers "is my friction unusual here", never "who is slower". It is reached from the author links on PR rows, and a colleague's page may be opened directly for a deliberate comparison.
- The author's own team is the standing baseline next to the repository: the ready-to-merge time also sits next to the aggregate of the team the author works in, on the author page and on the pull request page. When the rule below cannot settle on one of the author's teams, each of those teams gets its own row. A team row is always an aggregate, never a member.
- A team figure is shown only when at least two other authors contribute a value to it in the window. Below that the median is one or two pull requests, which reads as a team's pace and is not one. Two keeps a real three-person team readable. This is a noise floor, not a privacy floor: every author page opens by name, and each pull request's own time is on its page, so the median discloses nothing that is not already shown.
@@ -170,7 +170,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **CI Signals use immutable evidence.** Flaky checks require job rows from `github_workflow_jobs` showing a failed attempt followed by a successful later attempt for the same `(run_id, job)`. The run snapshot alone cannot prove this transition. Broken-default-branch detection reads GitHub's reported default branch from the PR snapshot's `base.repo`, the only full repository object in the tables this product reads (`query_default_branches` documents why the runs snapshot cannot answer it). A repo with no PR rows resolves nothing and is skipped: `repo_overview`'s master/main run-volume guess stays a display approximation, because a P1 needs GitHub's report, not inference. Detection gates on the canonical pass rate above. Duration comparisons require enough successful samples because the percentiles exclude failed and cancelled runs. All three conditions carry a week-stable `source_id`, and the coordinator records each emitted key in `SignalEmissionRecord` so an hourly sweep doesn't re-emit the same standing condition within its week. For broken-default-branch that means one signal per week per workflow, accepting that a distinct second breakage of the same workflow inside one week dedupes into the first rather than minting a signal (and a ledger row) per completed run.
- **HogQL only for analytics data.** No raw ClickHouse.
- **No product Postgres DB.** Analytics data lives in the warehouse / ClickHouse; any product-config model goes on the main DB as a team-scoped model (`TeamScopedRootMixin`), never a separate DB.
-- **No developer performance rankings; individual comparison is allowed.** The surveillance risk is a performance scorecard: output or speed turned into an ordered population of people. It is not an engineer inspecting their own friction, and not a comparison with a colleague they already know. Author figures may therefore be read one author at a time, and compared deliberately with another author, a GitHub team, or the repository. The product must not rank, sort, score or enumerate authors by delivery performance (throughput, lead time, time to merge), and a team view must never break a delivery aggregate down into a per-member ranking. Friction is outside that rule (§2): the per-PR friction view carries each pull request's author next to the friction it met, so a read over it may score and order that friction. The delivery reads (`delivery_summary`, `pull_request_timelines`) take exactly one scope (one author, one GitHub team, or one pull request, defined once in `logic/delivery_scope.py`) and give repository context. `delivery_comparison` gives explicit comparison context: one author's ready-to-merge medians next to the aggregate of the relevant teams and the repository, and next to another author's figures when the person asking named that author. It does not discover, order or return a population of authors. Review pace differs a lot between teams, so the repository median alone cannot say whether an author's wait is normal for the work they do. The read picks the teams from the author's own memberships by one fixed rule, defined once in the logic layer: the teams the pull request in focus asked to review, else the team asked by the most of the author's pull requests, counting each pull request once per team and only requests made in the window, else every team the author is in. Each picked team gets its own row, and teams are never pooled. What a pull request asked comes from its immutable `review_requested` issue events, never from the pull request snapshot, which drops a request once the team reviews. Without those events the rule falls through to every team the author is in. A team scope matches authors through the `team_members` snapshot and matches nothing when it isn't synced. The team page passes its owning team straight through as that scope: an ownership file's team name is already the GitHub org team slug, which `hogli owners:lint --live` validates against the org on every ownership change, so no mapping sits between the two vocabularies. The author page is reached from PR-row author links, and a colleague's page may be opened directly; `author_workflow_costs` and the delivery reads stay UI-only (MCP `enabled: false`).
+- **No developer performance rankings; individual comparison is allowed.** The surveillance risk is a performance scorecard: output or speed turned into an ordered population of people. It is not an engineer inspecting their own friction, and not a comparison with a colleague they already know. Author figures may therefore be read one author at a time, and compared deliberately with another author, a GitHub team, or the repository. The product must not rank, sort, score or enumerate authors by delivery performance (throughput, lead time, time to merge), and a team view must never break a delivery aggregate down into a per-member ranking. Friction is outside that rule (§2): `author_friction` scores and orders the friction authors meet over the per-PR friction view, and a team list shows its members' friction with their repository-wide ranks. The delivery reads (`delivery_summary`, `pull_request_timelines`) take exactly one scope (one author, one GitHub team, or one pull request, defined once in `logic/delivery_scope.py`) and give repository context. `delivery_comparison` gives explicit comparison context: one author's ready-to-merge medians next to the aggregate of the relevant teams and the repository, and next to another author's figures when the person asking named that author. It does not discover, order or return a population of authors. Review pace differs a lot between teams, so the repository median alone cannot say whether an author's wait is normal for the work they do. The read picks the teams from the author's own memberships by one fixed rule, defined once in the logic layer: the teams the pull request in focus asked to review, else the team asked by the most of the author's pull requests, counting each pull request once per team and only requests made in the window, else every team the author is in. Each picked team gets its own row, and teams are never pooled. What a pull request asked comes from its immutable `review_requested` issue events, never from the pull request snapshot, which drops a request once the team reviews. Without those events the rule falls through to every team the author is in. A team scope matches authors through the `team_members` snapshot and matches nothing when it isn't synced. The team page passes its owning team straight through as that scope: an ownership file's team name is already the GitHub org team slug, which `hogli owners:lint --live` validates against the org on every ownership change, so no mapping sits between the two vocabularies. The author page is reached from PR-row author links, and a colleague's page may be opened directly; `author_workflow_costs`, `author_friction` and the delivery reads stay UI-only (MCP `enabled: false`).
- **A pull request timeline is replayed from immutable timestamps, defined once in `logic/pr_timeline.py`.** Run and job attempts, reviews and merge-queue gate runs become change points, and the state between two points follows one precedence: merge queue, out of the queue (open PRs, Trunk's current state), red checks, running checks, review state. A commit's state per workflow is its latest started attempt, ordered by start, attempt and run id, so two runs that start in the same second always resolve the same way. A red stretch is labelled by what turned it green (a re-run of the same commit, the same job failing on the default branch within 12 hours, a later push), which is evidence about the cause, not proof of it. Every merge-queue state collapses into one span because the warehouse keeps no queue history. An author or team list reads CI from 30 days before the window at the earliest, so an older open pull request's timeline starts there. A single pull request replays its full CI history, while its merge-queue evidence uses the shared seven-day gate lookback.
- **Bot detection, defined once:** `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist; per-team config deferred.
- **Bots and drafts excluded by default** in throughput / cycle-time reads; first-class in bot-impact analysis, so never strip them at the substrate.
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index dfd999a7bc2c..58c0d5f8b131 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 Team
from products.engineering_analytics.backend import logic
from products.engineering_analytics.backend.facade.contracts import (
+ AuthorFrictionList,
BranchPRMatch,
BrokenTestsResult,
CICardSummary,
@@ -279,6 +280,22 @@ def list_author_workflow_costs(
)
+def get_author_friction(
+ *,
+ team: Team,
+ github_team: str | None = None,
+ source_id: str | None = None,
+ repo: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> AuthorFrictionList:
+ """Every author's friction over the last 30 days, most first. ``github_team`` lists only its members,
+ with their repository-wide scores and ranks."""
+ return logic.build_author_friction(
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
+ github_team=github_team.strip() if github_team and github_team.strip() else None,
+ )
+
+
def get_delivery_summary(
*,
team: Team,
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 830484e1b531..9e2c152dfd89 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -1756,6 +1756,53 @@ class TeamReadyToMergeMedians:
medians: ReadyToMergeMedians | None
+class FrictionGroup(StrEnum):
+ """The kinds of friction an author meets, each a share of the friction score."""
+
+ CI = "ci"
+ REVIEW = "review"
+ QUEUE = "queue"
+ REWORK = "rework"
+
+
+@dataclass(frozen=True)
+class FrictionGroupShare:
+ group: FrictionGroup
+ # This group's part of the author's score, in the same "× typical" unit. The parts add up to the score.
+ score: float
+
+
+@dataclass(frozen=True)
+class AuthorFriction:
+ """What the dev loop put one author through, as a multiple of the typical author (1.0).
+
+ Friction counts only what happened to the author, never how much or how fast they ship (SPEC §2).
+ ``rank`` orders experiences, and ``rank_low``..``rank_high`` is the band it stays in when the author's
+ pull requests are resampled, so a reader sees how settled a position is.
+ """
+
+ author: str
+ avatar_url: str
+ score: float
+ groups: list[FrictionGroupShare]
+ pr_count: int
+ rank: int
+ rank_low: int
+ rank_high: int
+
+
+@dataclass(frozen=True)
+class AuthorFrictionList:
+ # False when the team has no per-PR friction view yet (it needs runs, jobs and pull requests synced).
+ available: bool
+ window_days: int
+ # Authors scored in the repository. A team list keeps their ranks, so this is the ranks' denominator.
+ ranked_author_count: int
+ github_team: str | None
+ has_membership_data: bool
+ items: list[AuthorFriction]
+
+
@dataclass(frozen=True)
class DeliveryComparison:
"""How long an author's pull requests take from ready to merged, next to their team's and the
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 8a5c1bf74e78..038b325d3695 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -28,6 +28,7 @@ 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.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.py
new file mode 100644
index 000000000000..50b12539fba5
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/friction.py
@@ -0,0 +1,404 @@
+"""Friction scores: how much the dev loop put each author through, as a multiple of the typical author.
+
+A friction score counts only what happened to the author: failures they did not cause and re-runs that
+failed again, waits on reviewers, the merge queue, and their own rework. It is a mean per pull request, so
+shipping more or faster does not raise it (SPEC §2).
+
+Every figure comes from the per-PR friction view (``views/pr_friction.py``). Each metric applies a curve
+to each pull request, then an author's value is the mean over their pull requests, pulled toward the
+repository mean with ``SHRINKAGE`` pseudo pull requests so that a handful of pull requests cannot put an
+author at either end. Each value divides by the typical author's value, and the weights add the ratios
+into one score where 1.0 is typical.
+
+The weights are a choice, not a fit to this data: a simulation showed that equal weights inside judged
+pain groups rank authors about as well as the true weights would, and paired comparisons of friction set
+the group weights. Change them only with a new round of those comparisons.
+"""
+
+import math
+import random
+import statistics
+from collections.abc import Callable
+from dataclasses import dataclass
+
+from posthog.hogql import ast
+from posthog.hogql.errors import QueryError
+
+from posthog.dataclasses import frozen
+
+from products.engineering_analytics.backend.facade.contracts import (
+ AuthorFriction,
+ AuthorFrictionList,
+ FrictionGroup,
+ FrictionGroupShare,
+)
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.views import pr_friction
+
+SHRINKAGE = 5
+MIN_PULL_REQUESTS = 3
+# Causes the author did not create cost a triage tax on top of the wait itself.
+EXTERNAL_CAUSE_MULTIPLIER = 1.5
+GROUP_WEIGHTS: dict[FrictionGroup, float] = {
+ FrictionGroup.QUEUE: 40,
+ FrictionGroup.REVIEW: 25,
+ FrictionGroup.CI: 20,
+ FrictionGroup.REWORK: 15,
+}
+# CI time below this per push, and merge-queue time below its own threshold, is the normal cost of a push.
+CI_WAIT_FREE_SECONDS = 10 * 60
+QUEUE_FREE_SECONDS = 30 * 60
+APPROVAL_WAIT_REFERENCE_HOURS = 8
+APPROVAL_SLOW_HOURS = 24
+BOOTSTRAP_ROUNDS = 20
+_BOOTSTRAP_SEED = 20260924
+
+
+@dataclass(frozen=True, kw_only=True)
+class PullRequestFriction:
+ """One row of the per-PR friction view."""
+
+ number: int
+ author: str
+ author_avatar_url: str
+ push_count: int
+ flake_red_count: int
+ master_red_count: int
+ unknown_red_count: int
+ own_red_count: int
+ futile_rerun_count: int
+ ci_wait_seconds: tuple[float, ...]
+ first_approval_wait_seconds: float | None
+ pushes_after_approval: int | None
+ queue_seconds: float | None
+ kickout_count: int | None
+
+
+def _approval_hours(pr: PullRequestFriction) -> float | None:
+ if pr.first_approval_wait_seconds is None:
+ return None
+ return pr.first_approval_wait_seconds / 3600
+
+
+def _log_approval_wait(pr: PullRequestFriction) -> float | None:
+ hours = _approval_hours(pr)
+ return None if hours is None else math.log1p(hours / APPROVAL_WAIT_REFERENCE_HOURS)
+
+
+def _slow_approval(pr: PullRequestFriction) -> float | None:
+ hours = _approval_hours(pr)
+ return None if hours is None else float(hours >= APPROVAL_SLOW_HOURS)
+
+
+def _ci_wait_minutes(pr: PullRequestFriction) -> float:
+ return sum(max(0.0, seconds - CI_WAIT_FREE_SECONDS) for seconds in pr.ci_wait_seconds) / 60
+
+
+def _queue_minutes(pr: PullRequestFriction) -> float:
+ # A pull request that never entered the queue met no queue friction, so it still counts, as zero.
+ return max(0.0, (pr.queue_seconds or 0.0) - QUEUE_FREE_SECONDS) / 60
+
+
+def _optional(value: int | None) -> float | None:
+ return None if value is None else float(value)
+
+
+@dataclass(frozen=True, kw_only=True)
+class FrictionMetric:
+ key: str
+ group: FrictionGroup
+ weight: float
+ external: bool
+ # The metric's value for one pull request, curve applied. None means the pull request has no value.
+ value: Callable[[PullRequestFriction], float | None]
+
+
+METRICS: tuple[FrictionMetric, ...] = (
+ # Each red stretch counts once, whatever its length: a red pull request left alone hardly affects anyone.
+ FrictionMetric(
+ key="flake_red", group=FrictionGroup.CI, weight=1, external=True, value=lambda pr: pr.flake_red_count
+ ),
+ FrictionMetric(
+ key="master_red", group=FrictionGroup.CI, weight=1, external=True, value=lambda pr: pr.master_red_count
+ ),
+ FrictionMetric(
+ key="unknown_red", group=FrictionGroup.CI, weight=0.5, external=False, value=lambda pr: pr.unknown_red_count
+ ),
+ FrictionMetric(key="ci_wait", group=FrictionGroup.CI, weight=1, external=False, value=_ci_wait_minutes),
+ FrictionMetric(
+ key="futile_reruns", group=FrictionGroup.CI, weight=1.5, external=True, value=lambda pr: pr.futile_rerun_count
+ ),
+ FrictionMetric(
+ key="first_approval_wait", group=FrictionGroup.REVIEW, weight=1, external=False, value=_log_approval_wait
+ ),
+ FrictionMetric(
+ key="first_approval_over_a_day", group=FrictionGroup.REVIEW, weight=1, external=False, value=_slow_approval
+ ),
+ FrictionMetric(key="queue_time", group=FrictionGroup.QUEUE, weight=1, external=False, value=_queue_minutes),
+ FrictionMetric(
+ key="kickouts",
+ group=FrictionGroup.QUEUE,
+ weight=1.5,
+ external=True,
+ value=lambda pr: pr.kickout_count or 0,
+ ),
+ FrictionMetric(
+ key="own_red", group=FrictionGroup.REWORK, weight=1, external=False, value=lambda pr: pr.own_red_count
+ ),
+ FrictionMetric(
+ key="extra_pushes",
+ group=FrictionGroup.REWORK,
+ weight=0.5,
+ external=False,
+ value=lambda pr: max(0, pr.push_count - 1),
+ ),
+ FrictionMetric(
+ key="pushes_after_approval",
+ group=FrictionGroup.REWORK,
+ weight=1,
+ external=False,
+ value=lambda pr: _optional(pr.pushes_after_approval),
+ ),
+)
+
+
+def effective_weights() -> list[float]:
+ """Each metric's share of the whole score: its group's share, split by the weights inside the group."""
+ group_total = sum(GROUP_WEIGHTS.values())
+ inner = [metric.weight * (EXTERNAL_CAUSE_MULTIPLIER if metric.external else 1) for metric in METRICS]
+ inner_totals = {
+ group: sum(w for metric, w in zip(METRICS, inner) if metric.group == group) for group in GROUP_WEIGHTS
+ }
+ return [
+ GROUP_WEIGHTS[metric.group] / group_total * w / inner_totals[metric.group] if inner_totals[metric.group] else 0
+ for metric, w in zip(METRICS, inner)
+ ]
+
+
+@dataclass(frozen=True, kw_only=True)
+class _AuthorScore:
+ author: str
+ score: float
+ groups: dict[FrictionGroup, float]
+ pr_count: int
+
+
+@frozen
+class _RankBand:
+ low: int
+ high: int
+
+
+class FrictionScorer:
+ """Scores every author with at least ``MIN_PULL_REQUESTS`` pull requests against each other."""
+
+ def __init__(self, pull_requests: list[PullRequestFriction]) -> None:
+ by_author: dict[str, list[PullRequestFriction]] = {}
+ for pr in pull_requests:
+ by_author.setdefault(pr.author, []).append(pr)
+ self._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), "")
+ for author, prs in by_author.items()
+ }
+ self._weights = effective_weights()
+ # values[author][metric] holds the curve value of each of the author's pull requests.
+ self._values = {
+ 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 = {
+ 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()
+ }
+ 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)
+ shrunk = {
+ author: [
+ (sum(author_values[m]) + SHRINKAGE * pooled[m]) / (len(author_values[m]) + SHRINKAGE)
+ for m in range(len(METRICS))
+ ]
+ for author, author_values in present.items()
+ }
+ typical = [statistics.fmean(s[m] for s in shrunk.values()) if shrunk else 0.0 for m in range(len(METRICS))]
+ # A metric nobody meets (a repository without a merge queue) passes its weight on to the others,
+ # so the typical author stays at 1.0.
+ weight_in_use = sum(w for m, w in enumerate(self._weights) if typical[m] > 0)
+ scores = []
+ for author, author_shrunk in shrunk.items():
+ groups = dict.fromkeys(GROUP_WEIGHTS, 0.0)
+ for m, metric in enumerate(METRICS):
+ if typical[m] > 0:
+ groups[metric.group] += self._weights[m] / weight_in_use * author_shrunk[m] / typical[m]
+ scores.append(
+ _AuthorScore(author=author, score=sum(groups.values()), groups=groups, pr_count=len(values[author][0]))
+ )
+ return scores
+
+ def _ranks(self, scores: list[_AuthorScore]) -> dict[str, int]:
+ ordered = sorted(scores, key=lambda s: (-s.score, s.author))
+ return {s.author: rank for rank, s in enumerate(ordered, start=1)}
+
+ def _rank_bands(self) -> dict[str, _RankBand]:
+ """The 10th to 90th percentile rank over bootstrap resamples of each author's pull requests."""
+ rng = random.Random(_BOOTSTRAP_SEED)
+ samples: dict[str, list[int]] = {author: [] for author in self._authors}
+ for _ in range(BOOTSTRAP_ROUNDS):
+ resampled = {}
+ for author, author_values in self._values.items():
+ count = len(author_values[0])
+ picks = [rng.randrange(count) for _ in range(count)]
+ resampled[author] = [[metric_values[i] for i in picks] for metric_values in author_values]
+ for author, rank in self._ranks(self._score(resampled)).items():
+ samples[author].append(rank)
+ bands: dict[str, _RankBand] = {}
+ for author, ranks in samples.items():
+ deciles = statistics.quantiles(sorted(ranks), n=10, method="inclusive")
+ bands[author] = _RankBand(low=math.floor(deciles[0]), high=math.ceil(deciles[-1]))
+ return bands
+
+ def score(self) -> list[AuthorFriction]:
+ """Every scored author, most friction first."""
+ if not self._authors:
+ return []
+ scores = self._score(self._values)
+ ranks = self._ranks(scores)
+ bands = self._rank_bands()
+ return sorted(
+ (
+ AuthorFriction(
+ author=s.author,
+ avatar_url=self._avatars[s.author],
+ score=s.score,
+ groups=[FrictionGroupShare(group=group, score=value) for group, value in s.groups.items()],
+ pr_count=s.pr_count,
+ rank=ranks[s.author],
+ rank_low=min(bands[s.author].low, ranks[s.author]),
+ rank_high=max(bands[s.author].high, ranks[s.author]),
+ )
+ for s in scores
+ ),
+ key=lambda item: item.rank,
+ )
+
+
+_FRICTION_SELECT = f"""
+ SELECT number, repo_owner, repo_name, author, author_avatar_url, push_count, flake_red_count, master_red_count,
+ unknown_red_count, own_red_count, futile_rerun_count, ci_wait_seconds, first_approval_wait_seconds,
+ pushes_after_approval, queue_seconds, kickout_count
+ FROM {pr_friction.VIEW_NAME}
+ WHERE NOT is_bot AND author != '' AND __REPO__
+"""
+
+_TEAM_MEMBERS_SELECT = """
+ SELECT DISTINCT member_handle FROM __MEMBERS_SOURCE__ AS m WHERE team_slug = {team}
+"""
+
+
+def _query_pull_requests(curated: CuratedGitHubSource) -> list[PullRequestFriction] | None:
+ """The view's rows for the curated source's repository, or None when the team has no friction view.
+
+ The view unions every GitHub source of the team, so the read keeps to the one source the caller is
+ authorized for. A legacy single-repo source has no repository name, so the source id is the filter
+ that always holds."""
+ placeholders: dict[str, ast.Expr] = {"source_id": ast.Constant(value=curated.source_id)}
+ repo_filter = "source_id = {source_id}"
+ if "/" in curated.repository:
+ owner, name = curated.repository.split("/", 1)
+ # A source can store its repositories lowercased, while the view keeps GitHub's casing.
+ repo_filter += " AND lower(repo_owner) = lower({repo_owner}) AND lower(repo_name) = lower({repo_name})"
+ placeholders |= {"repo_owner": ast.Constant(value=owner), "repo_name": ast.Constant(value=name)}
+ try:
+ rows = curated.run_paged(
+ _FRICTION_SELECT.replace("__REPO__", repo_filter),
+ # A multi-repo source read without a repository keeps several repositories under one source id,
+ # and their pull request numbers collide, so the page key carries the repository too.
+ page_key=(("repo_owner", 1), ("repo_name", 2), ("number", 0)),
+ query_type="engineering_analytics.author_friction",
+ placeholders=placeholders,
+ )
+ except QueryError as exc:
+ if f"Unknown table `{pr_friction.VIEW_NAME}`" in str(exc):
+ return None
+ raise
+ return [
+ PullRequestFriction(
+ number=int(number),
+ author=author,
+ author_avatar_url=avatar_url or "",
+ push_count=int(push_count),
+ flake_red_count=int(flake),
+ master_red_count=int(master),
+ unknown_red_count=int(unknown),
+ own_red_count=int(own),
+ futile_rerun_count=int(futile),
+ ci_wait_seconds=tuple(float(s) for s in ci_wait or ()),
+ first_approval_wait_seconds=None if approval is None else float(approval),
+ pushes_after_approval=None if after_approval is None else int(after_approval),
+ queue_seconds=None if queue is None else float(queue),
+ kickout_count=None if kickouts is None else int(kickouts),
+ )
+ for (
+ number,
+ _repo_owner,
+ _repo_name,
+ author,
+ avatar_url,
+ push_count,
+ flake,
+ master,
+ unknown,
+ own,
+ futile,
+ ci_wait,
+ approval,
+ after_approval,
+ queue,
+ kickouts,
+ ) in rows
+ ]
+
+
+def _query_team_members(curated: CuratedGitHubSource, github_team: str) -> set[str] | None:
+ members_source = curated.members_source()
+ if members_source is None:
+ return None
+ 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)},
+ )
+ return {handle for (handle,) in response.results or []}
+
+
+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-wide
+ scores 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 None
+ pull_requests = _query_pull_requests(curated)
+ if pull_requests is None:
+ return AuthorFrictionList(
+ available=False,
+ window_days=window_days,
+ ranked_author_count=0,
+ github_team=github_team,
+ has_membership_data=has_membership_data,
+ items=[],
+ )
+ items = FrictionScorer(pull_requests).score()
+ ranked_author_count = len(items)
+ if github_team:
+ members = _query_team_members(curated, github_team) or set()
+ items = [item for item in items if item.author in 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,
+ items=items,
+ )
diff --git a/products/engineering_analytics/backend/presentation/serializers/friction.py b/products/engineering_analytics/backend/presentation/serializers/friction.py
new file mode 100644
index 000000000000..194c628bfd4d
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/serializers/friction.py
@@ -0,0 +1,68 @@
+"""Payloads for the friction read: every author's friction as a multiple of the typical author."""
+
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from products.engineering_analytics.backend.facade.contracts import (
+ AuthorFriction,
+ AuthorFrictionList,
+ FrictionGroupShare,
+)
+
+
+class FrictionGroupShareSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = FrictionGroupShare
+ extra_kwargs = {
+ "group": {
+ "help_text": "ci (red CI and CI waits), review (waiting for the first approval), queue (merge-queue "
+ "time and kickouts), or rework (own failures and extra pushes)."
+ },
+ "score": {"help_text": "This group's part of the score, in the same 'x typical' unit. The parts add up."},
+ }
+
+
+class AuthorFrictionSerializer(DataclassSerializer):
+ groups = FrictionGroupShareSerializer(many=True, help_text="The score split by the kind of friction.")
+
+ class Meta:
+ dataclass = AuthorFriction
+ extra_kwargs = {
+ "author": {"help_text": "GitHub login."},
+ "avatar_url": {"help_text": "The author's GitHub avatar, or empty when the pull requests carry none."},
+ "score": {
+ "help_text": "Friction as a multiple of the typical author: 1.0 is typical, 2.0 is twice as much. "
+ "Counts only what happened to the author, never how much or how fast they ship."
+ },
+ "pr_count": {"help_text": "The author's merged pull requests in the window."},
+ "rank": {"help_text": "Position by friction in the repository, 1 is the most."},
+ "rank_low": {
+ "help_text": "Low end of the rank band: the 10th percentile rank over resamples of the author's "
+ "pull requests, and never above rank."
+ },
+ "rank_high": {
+ "help_text": "High end of the rank band: the 90th percentile rank over the same resamples, and "
+ "never below rank."
+ },
+ }
+
+
+class AuthorFrictionListSerializer(DataclassSerializer):
+ items = AuthorFrictionSerializer(many=True, help_text="Authors by friction, most first.")
+
+ class Meta:
+ dataclass = AuthorFrictionList
+ 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 with at least 3 merged pull requests, all ranked together. A team list "
+ "keeps these repository-wide ranks."
+ },
+ "github_team": {"help_text": "The team the list is filtered to, or null for every author."},
+ "has_membership_data": {
+ "help_text": "False when the team membership table isn't synced, so a team filter matches nobody."
+ },
+ }
diff --git a/products/engineering_analytics/backend/presentation/views/__init__.py b/products/engineering_analytics/backend/presentation/views/__init__.py
index 87aa4cefb276..b1c5b6de8cc2 100644
--- a/products/engineering_analytics/backend/presentation/views/__init__.py
+++ b/products/engineering_analytics/backend/presentation/views/__init__.py
@@ -14,6 +14,7 @@ from products.engineering_analytics.backend.presentation.views._base import (
from products.engineering_analytics.backend.presentation.views.ci_signals import CISignalsConfigMixin
from products.engineering_analytics.backend.presentation.views.delivery import DeliveryActionsMixin
from products.engineering_analytics.backend.presentation.views.dora import DoraActionsMixin
+from products.engineering_analytics.backend.presentation.views.friction import FrictionActionsMixin
from products.engineering_analytics.backend.presentation.views.pull_requests import PullRequestActionsMixin
from products.engineering_analytics.backend.presentation.views.sources import SourcesMixin
from products.engineering_analytics.backend.presentation.views.suite_health import SuiteHealthActionsMixin
@@ -31,6 +32,7 @@ class EngineeringAnalyticsViewSet(
SuiteHealthActionsMixin,
TeamActionsMixin,
DoraActionsMixin,
+ FrictionActionsMixin,
EngineeringAnalyticsViewSetBase,
):
"""PR and CI lifecycle analytics over the GitHub warehouse data."""
@@ -46,6 +48,7 @@ class EngineeringAnalyticsViewSet(
*SuiteHealthActionsMixin.READ_ACTIONS,
*TeamActionsMixin.READ_ACTIONS,
*DoraActionsMixin.READ_ACTIONS,
+ *FrictionActionsMixin.READ_ACTIONS,
]
scope_object_write_actions: list[str] = [
*CISignalsConfigMixin.WRITE_ACTIONS,
diff --git a/products/engineering_analytics/backend/presentation/views/friction.py b/products/engineering_analytics/backend/presentation/views/friction.py
new file mode 100644
index 000000000000..c2c1ecce4be5
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/friction.py
@@ -0,0 +1,64 @@
+"""Friction read: every author's friction as a multiple of the typical author."""
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from products.engineering_analytics.backend.facade import api
+from products.engineering_analytics.backend.presentation.serializers.friction import AuthorFrictionListSerializer
+from products.engineering_analytics.backend.presentation.views._base import (
+ _SOURCE_ID,
+ EngineeringAnalyticsViewSetBase,
+ _bad_request,
+)
+
+_GITHUB_TEAM = OpenApiParameter(
+ name="github_team",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="GitHub team slug: list only the team's members, through the team membership table. Ranks stay "
+ "repository-wide.",
+)
+
+_REPO = OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="'owner/name' repository, when the selected source syncs several.",
+)
+
+
+class FrictionActionsMixin(EngineeringAnalyticsViewSetBase):
+ READ_ACTIONS = ["author_friction"]
+
+ @extend_schema(
+ operation_id="engineering_analytics_author_friction",
+ parameters=[_GITHUB_TEAM, _SOURCE_ID, _REPO],
+ responses={
+ 200: AuthorFrictionListSerializer,
+ 400: OpenApiResponse(description="Invalid source_id or repo."),
+ },
+ description=(
+ "Every author's friction over pull requests merged in the last 30 days, most first: red CI they did "
+ "not cause, re-runs that failed again, CI waits, the wait for the first approval, merge-queue time and "
+ "kickouts, and rework. The score is a multiple of the typical author and never counts how much or how "
+ "fast someone ships. Bots are excluded, and authors need at least 3 merged pull requests."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def author_friction(self, request: Request, **kwargs) -> Response:
+ try:
+ friction = api.get_author_friction(
+ team=self.team,
+ github_team=request.query_params.get("github_team") or None,
+ 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 source_id or repo")
+ return Response(AuthorFrictionListSerializer(instance=friction).data)
diff --git a/products/engineering_analytics/backend/tests/test_friction.py b/products/engineering_analytics/backend/tests/test_friction.py
new file mode 100644
index 000000000000..16d6f3bf89da
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_friction.py
@@ -0,0 +1,156 @@
+import statistics
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.hogql.errors import QueryError
+
+from products.engineering_analytics.backend.facade.contracts import FrictionGroup
+from products.engineering_analytics.backend.logic.friction import (
+ MIN_PULL_REQUESTS,
+ FrictionScorer,
+ PullRequestFriction,
+ build_author_friction,
+)
+
+
+def _pr(author: str, number: int, **friction: Any) -> PullRequestFriction:
+ values: dict[str, Any] = {
+ "push_count": 1,
+ "flake_red_count": 0,
+ "master_red_count": 0,
+ "unknown_red_count": 0,
+ "own_red_count": 0,
+ "futile_rerun_count": 0,
+ "ci_wait_seconds": (600.0,),
+ "first_approval_wait_seconds": 3 * 3600.0,
+ "pushes_after_approval": 0,
+ "queue_seconds": 20 * 60.0,
+ "kickout_count": 0,
+ **friction,
+ }
+ return PullRequestFriction(number=number, author=author, author_avatar_url="", **values)
+
+
+def _population() -> list[PullRequestFriction]:
+ rows = []
+ for i in range(6):
+ rows.append(_pr("calm", 100 + i))
+ rows.append(_pr("typical", 200 + i, own_red_count=1, push_count=2, first_approval_wait_seconds=8 * 3600.0))
+ rows.append(
+ _pr(
+ "blocked",
+ 300 + i,
+ master_red_count=2,
+ futile_rerun_count=3,
+ kickout_count=2,
+ queue_seconds=3 * 3600.0,
+ )
+ )
+ rows.extend(_pr("newcomer", 400 + i, master_red_count=5) for i in range(MIN_PULL_REQUESTS - 1))
+ return rows
+
+
+def _row(pr: PullRequestFriction) -> tuple:
+ return (
+ pr.number,
+ "PostHog",
+ "posthog",
+ pr.author,
+ pr.author_avatar_url,
+ pr.push_count,
+ pr.flake_red_count,
+ pr.master_red_count,
+ pr.unknown_red_count,
+ pr.own_red_count,
+ pr.futile_rerun_count,
+ list(pr.ci_wait_seconds),
+ pr.first_approval_wait_seconds,
+ pr.pushes_after_approval,
+ pr.queue_seconds,
+ pr.kickout_count,
+ )
+
+
+class _Curated:
+ """The slice of CuratedGitHubSource the friction read uses."""
+
+ repository = "PostHog/posthog"
+ source_id = "0192f000-0000-7000-8000-000000000001"
+
+ def __init__(self, rows: list[tuple] | None, members: list[str] | None) -> None:
+ self._rows = rows
+ self._members = members
+ self.friction_placeholders: dict[str, Any] = {}
+
+ 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]:
+ 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 []])
+
+
+class TestFrictionScore(SimpleTestCase):
+ def test_scores_order_experiences_around_the_typical_author(self) -> None:
+ items = FrictionScorer(_population()).score()
+
+ assert [item.author for item in items] == ["blocked", "typical", "calm"]
+ assert statistics.fmean(item.score for item in items) == pytest.approx(1.0)
+ for item in items:
+ assert sum(share.score for share in item.groups) == pytest.approx(item.score)
+ assert item.rank_low <= item.rank <= item.rank_high
+
+ def test_unqueued_pull_requests_count_as_no_queue_friction(self) -> None:
+ rows = [_pr("always_queued", 500 + i, queue_seconds=2 * 3600.0) for i in range(4)]
+ rows += [_pr("once_queued", 600, queue_seconds=2 * 3600.0)]
+ rows += [_pr("once_queued", 601 + i, queue_seconds=None, kickout_count=None) for i in range(3)]
+
+ queue = {
+ item.author: next(share.score for share in item.groups if share.group == FrictionGroup.QUEUE)
+ for item in FrictionScorer(rows).score()
+ }
+
+ assert queue["once_queued"] < queue["always_queued"]
+
+ @parameterized.expand(
+ [
+ ("no_view_yet", None, ["typical"], None, False, []),
+ ("whole_repository", _population(), None, None, True, [("blocked", 1), ("typical", 2), ("calm", 3)]),
+ (
+ "team_keeps_repository_ranks",
+ _population(),
+ ["typical", "calm"],
+ "team-devex",
+ True,
+ [("typical", 2), ("calm", 3)],
+ ),
+ ]
+ )
+ 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]],
+ ) -> None:
+ 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]
+
+ assert friction.available is available
+ 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
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 95d4d271f079..adbbb42f06c6 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -285,6 +285,33 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
enabled=True,
).exists()
+ def test_author_friction_forwards_the_team_and_serializes(self) -> None:
+ friction = contracts.AuthorFrictionList(
+ available=True,
+ window_days=30,
+ ranked_author_count=12,
+ github_team="team-devex",
+ has_membership_data=True,
+ items=[
+ contracts.AuthorFriction(
+ author="alice",
+ avatar_url="",
+ score=2.5,
+ groups=[contracts.FrictionGroupShare(group=contracts.FrictionGroup.QUEUE, score=2.5)],
+ pr_count=9,
+ rank=1,
+ rank_low=1,
+ rank_high=3,
+ )
+ ],
+ )
+ with mock.patch(f"{_VIEWS}.get_author_friction", return_value=friction) as get_friction:
+ response = self.client.get(self._url("author_friction"), {"github_team": "team-devex"})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert get_friction.call_args.kwargs["github_team"] == "team-devex"
+ assert response.json()["items"][0]["groups"] == [{"group": "queue", "score": 2.5}]
+
def test_ci_cards_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.get_ci_cards", return_value=_cards()):
response = self.client.get(self._url("ci_cards"))
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 1e23d78543b1..0d2a6f00eb7e 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -7,6 +7,70 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `ci` - CI
+ * * `review` - REVIEW
+ * * `queue` - QUEUE
+ * * `rework` - REWORK
+ */
+export type FrictionGroupEnumApi = (typeof FrictionGroupEnumApi)[keyof typeof FrictionGroupEnumApi]
+
+export const FrictionGroupEnumApi = {
+ Ci: 'ci',
+ Review: 'review',
+ Queue: 'queue',
+ Rework: 'rework',
+} as const
+
+export interface FrictionGroupShareApi {
+ /** ci (red CI and CI waits), review (waiting for the first approval), queue (merge-queue time and kickouts), or rework (own failures and extra pushes).
+ *
+ * * `ci` - CI
+ * * `review` - REVIEW
+ * * `queue` - QUEUE
+ * * `rework` - REWORK */
+ group: FrictionGroupEnumApi
+ /** This group's part of the score, in the same 'x typical' unit. The parts add up. */
+ score: number
+}
+
+export interface AuthorFrictionApi {
+ /** The score split by the kind of friction. */
+ groups: FrictionGroupShareApi[]
+ /** GitHub login. */
+ author: string
+ /** The author's GitHub avatar, or empty when the pull requests carry none. */
+ avatar_url: string
+ /** Friction as a multiple of the typical author: 1.0 is typical, 2.0 is twice as much. Counts only what happened to the author, never how much or how fast they ship. */
+ score: number
+ /** The author's merged pull requests in the window. */
+ pr_count: number
+ /** Position by friction in the repository, 1 is the most. */
+ rank: number
+ /** Low end of the rank band: the 10th percentile rank over resamples of the author's pull requests, and never above rank. */
+ rank_low: number
+ /** High end of the rank band: the 90th percentile rank over the same resamples, and never below rank. */
+ rank_high: number
+}
+
+export interface AuthorFrictionListApi {
+ /** Authors by friction, most first. */
+ items: AuthorFrictionApi[]
+ /** 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 with at least 3 merged pull requests, all ranked together. A team list keeps these repository-wide ranks. */
+ ranked_author_count: number
+ /**
+ * The team the list is filtered to, or null for every author.
+ * @nullable
+ */
+ github_team: string | null
+ /** False when the team membership table isn't synced, so a team filter matches nobody. */
+ has_membership_data: boolean
+}
+
export interface WorkflowCostApi {
/** GitHub Actions workflow name this cost is for. */
workflow_name: string
@@ -2091,6 +2155,21 @@ export interface WorkflowRunnerCostApi {
estimated_cost_usd: number | null
}
+export type EngineeringAnalyticsAuthorFrictionParams = {
+ /**
+ * GitHub team slug: list only the team's members, through the team membership table. Ranks stay repository-wide.
+ */
+ github_team?: 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.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 094163847219..f74c2163cee6 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 {
+ AuthorFrictionListApi,
BranchPRMatchApi,
BrokenTestsResultApi,
CICardSummaryApi,
@@ -19,6 +20,7 @@ import type {
DeliveryComparisonApi,
DeliverySummaryApi,
DoraOverviewApi,
+ EngineeringAnalyticsAuthorFrictionParams,
EngineeringAnalyticsAuthorWorkflowCostsParams,
EngineeringAnalyticsBrokenTestsParams,
EngineeringAnalyticsCiCardsParams,
@@ -75,6 +77,39 @@ import type {
WorkflowRunnerCostApi,
} from './api.schemas'
+export const getEngineeringAnalyticsAuthorFrictionUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsAuthorFrictionParams
+) => {
+ 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/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/author_friction/`
+}
+
+/**
+ * Every author's friction over pull requests merged in the last 30 days, most first: red CI they did not cause, re-runs that failed again, CI waits, the wait for the first approval, merge-queue time and kickouts, and rework. The score is a multiple of the typical author and never counts how much or how fast someone ships. Bots are excluded, and authors need at least 3 merged pull requests.
+ */
+export const engineeringAnalyticsAuthorFriction = async (
+ projectId: string,
+ params?: EngineeringAnalyticsAuthorFrictionParams,
+ options?: RequestInit
+): Promise<AuthorFrictionListApi> => {
+ return apiMutator<AuthorFrictionListApi>(getEngineeringAnalyticsAuthorFrictionUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsAuthorWorkflowCostsUrl = (
projectId: string,
params: EngineeringAnalyticsAuthorWorkflowCostsParams
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index 6afa315f0ba8..65458aeaac56 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -9,6 +9,9 @@ feature: engineering_analytics
url_prefix: /engineering-analytics
ui_apps: {}
tools:
+ engineering-analytics-author-friction:
+ operation: engineering_analytics_author_friction
+ enabled: false
engineering-analytics-author-workflow-costs:
operation: engineering_analytics_author_workflow_costs
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 79c75595c7c8..65d1902b666f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11509,6 +11509,71 @@ export namespace Schemas {
is_bot: boolean;
}
+ /**
+ * * `ci` - CI
+ * * `review` - REVIEW
+ * * `queue` - QUEUE
+ * * `rework` - REWORK
+ */
+ export type FrictionGroupEnum = typeof FrictionGroupEnum[keyof typeof FrictionGroupEnum];
+
+
+ export const FrictionGroupEnum = {
+ Ci: 'ci',
+ Review: 'review',
+ Queue: 'queue',
+ Rework: 'rework',
+ } as const;
+
+ export interface FrictionGroupShare {
+ /** ci (red CI and CI waits), review (waiting for the first approval), queue (merge-queue time and kickouts), or rework (own failures and extra pushes).
+ *
+ * * `ci` - CI
+ * * `review` - REVIEW
+ * * `queue` - QUEUE
+ * * `rework` - REWORK */
+ group: FrictionGroupEnum;
+ /** This group's part of the score, in the same 'x typical' unit. The parts add up. */
+ score: number;
+ }
+
+ export interface AuthorFriction {
+ /** The score split by the kind of friction. */
+ groups: FrictionGroupShare[];
+ /** GitHub login. */
+ author: string;
+ /** The author's GitHub avatar, or empty when the pull requests carry none. */
+ avatar_url: string;
+ /** Friction as a multiple of the typical author: 1.0 is typical, 2.0 is twice as much. Counts only what happened to the author, never how much or how fast they ship. */
+ score: number;
+ /** The author's merged pull requests in the window. */
+ pr_count: number;
+ /** Position by friction in the repository, 1 is the most. */
+ rank: number;
+ /** Low end of the rank band: the 10th percentile rank over resamples of the author's pull requests, and never above rank. */
+ rank_low: number;
+ /** High end of the rank band: the 90th percentile rank over the same resamples, and never below rank. */
+ rank_high: number;
+ }
+
+ export interface AuthorFrictionList {
+ /** Authors by friction, most first. */
+ items: AuthorFriction[];
+ /** 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 with at least 3 merged pull requests, all ranked together. A team list keeps these repository-wide ranks. */
+ ranked_author_count: number;
+ /**
+ * The team the list is filtered to, or null for every author.
+ * @nullable
+ */
+ github_team: string | null;
+ /** False when the team membership table isn't synced, so a team filter matches nobody. */
+ has_membership_data: boolean;
+ }
+
export type AutocompleteCompletionItemKind = typeof AutocompleteCompletionItemKind[keyof typeof AutocompleteCompletionItemKind];
@@ -108074,6 +108139,21 @@ export namespace Schemas {
offset?: number;
};
+ export type EngineeringAnalyticsAuthorFrictionParams = {
+ /**
+ * GitHub team slug: list only the team's members, through the team membership table. Ranks stay repository-wide.
+ */
+ github_team?: 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.