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.

fix(engineering-analytics): cap friction per pull request and ignore stuck runs (#107540)

Julian Beze0c52697219d
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 4b07533de647..9e665fd7d425 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -171,7 +171,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **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): `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.
+- **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. An unfinished run with no update for a day stopped reporting (the webhook sync missed its final event), so the replay ends it at its last update. The run row then gives it no outcome, and only a failed job row can mark it failed. Otherwise a run stuck in `in_progress` would read as running until the pull request merged. 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.
- **Time to merge** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (draft + ready combined). The precise companion is `ready_to_merge_seconds` = `merged_at` minus the last observed `ready_for_review` issue event (only the last draft/ready switch counts; a draft can't merge), falling back to `created_at` for a merged PR verifiably never drafted (no transition rows and its whole open-to-merge span inside the observed issue-event window, so the transitions can't merely be unsynced). NULL means "not observed", never zero: GitHub caps the issue-events history walk, so coverage grows forward from the first sync.
diff --git a/products/engineering_analytics/backend/logic/friction.py b/products/engineering_analytics/backend/logic/friction.py
index b33da5087ed6..9b5f30f70b53 100644
--- a/products/engineering_analytics/backend/logic/friction.py
+++ b/products/engineering_analytics/backend/logic/friction.py
@@ -53,6 +53,14 @@ GROUP_WEIGHTS: dict[FrictionGroup, float] = {
# 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
+# Waiting hurts in steps: past a few hours the author has moved on, and the data cannot tell a longer wait
+# from a pull request left alone overnight or over a weekend. So time counts only up to these caps, and
+# one stuck pull request cannot put its author at the top of the ranking.
+CI_WAIT_CAP_SECONDS = 2 * 3600
+QUEUE_CAP_SECONDS = 4 * 3600
+# The same holds for counted events: the fourth red stretch or kickout on one pull request tells little
+# more than the third, and a re-run loop can add dozens that the author did not start.
+COUNT_CAP = 3
APPROVAL_WAIT_REFERENCE_HOURS = 8
APPROVAL_SLOW_HOURS = 24
BOOTSTRAP_ROUNDS = 20
@@ -103,12 +111,18 @@ def _slow_approval(pr: PullRequestFriction) -> float | None:
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
+ return (
+ sum(max(0.0, min(seconds, CI_WAIT_CAP_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
+ return max(0.0, min(pr.queue_seconds or 0.0, QUEUE_CAP_SECONDS) - QUEUE_FREE_SECONDS) / 60
+
+
+def _capped(count: int) -> float:
+ return float(min(count, COUNT_CAP))
def _optional(value: int | None) -> float | None:
@@ -128,17 +142,29 @@ class FrictionMetric:
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
+ key="flake_red", group=FrictionGroup.CI, weight=1, external=True, value=lambda pr: _capped(pr.flake_red_count)
),
FrictionMetric(
- key="master_red", group=FrictionGroup.CI, weight=1, external=True, value=lambda pr: pr.master_red_count
+ key="master_red",
+ group=FrictionGroup.CI,
+ weight=1,
+ external=True,
+ value=lambda pr: _capped(pr.master_red_count),
),
FrictionMetric(
- key="unknown_red", group=FrictionGroup.CI, weight=0.5, external=False, value=lambda pr: pr.unknown_red_count
+ key="unknown_red",
+ group=FrictionGroup.CI,
+ weight=0.5,
+ external=False,
+ value=lambda pr: _capped(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
+ key="futile_reruns",
+ group=FrictionGroup.CI,
+ weight=1.5,
+ external=True,
+ value=lambda pr: _capped(pr.futile_rerun_count),
),
FrictionMetric(
key="first_approval_wait", group=FrictionGroup.REVIEW, weight=1, external=False, value=_log_approval_wait
@@ -152,10 +178,10 @@ METRICS: tuple[FrictionMetric, ...] = (
group=FrictionGroup.QUEUE,
weight=1.5,
external=True,
- value=lambda pr: pr.kickout_count or 0,
+ value=lambda pr: _capped(pr.kickout_count or 0),
),
FrictionMetric(
- key="own_red", group=FrictionGroup.REWORK, weight=1, external=False, value=lambda pr: pr.own_red_count
+ key="own_red", group=FrictionGroup.REWORK, weight=1, external=False, value=lambda pr: _capped(pr.own_red_count)
),
FrictionMetric(
key="extra_pushes",
diff --git a/products/engineering_analytics/backend/logic/merge_queue.py b/products/engineering_analytics/backend/logic/merge_queue.py
index a264a7dc8a0a..380bf9a0e7c6 100644
--- a/products/engineering_analytics/backend/logic/merge_queue.py
+++ b/products/engineering_analytics/backend/logic/merge_queue.py
@@ -159,7 +159,7 @@ def gate_attempts_sql(
{gate_attempt_expr("r.head_branch")} AS attempt,
min(r.run_started_at) AS started_at,
max(r.updated_at) AS completed_at,
- countIf(r.status != 'completed' OR r.updated_at IS NULL) AS unfinished,
+ countIf((r.status != 'completed' AND NOT r.stopped_reporting) OR r.updated_at IS NULL) AS unfinished,
max(r.status = 'completed' AND r.conclusion IN ({decisive_failure_conclusions_sql})) AS failed,
any(pr.merged_at) AS merged_at
FROM {runs_source} AS r
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
index fc8e99dbbb5e..f5c6be9d563e 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
@@ -95,7 +95,8 @@ _REVIEWS_SELECT = f"""
# Skipped runs add no red or running time, and the shared gate-attempt read handles queue runs.
_RUNS_SELECT = f"""
SELECT
- id, pr_number, workflow_name, head_sha, status, conclusion, run_started_at, updated_at, run_attempt, created_at
+ id, pr_number, workflow_name, head_sha, status, conclusion, run_started_at, updated_at, run_attempt, created_at,
+ stopped_reporting
FROM __RUNS_SOURCE__ AS r
WHERE pr_number IN {{pr_numbers}} AND run_started_at >= {{run_from}}
AND NOT is_merge_queue AND ifNull(conclusion, '') != 'skipped'
@@ -397,9 +398,10 @@ class PullRequestTimelinesQuery:
)
runs = [row for row in rows if row[6] is not None]
# A run on its first attempt that did not fail has exactly one attempt, and its run row already
- # describes it. Only re-runs (earlier attempts) and failures (failed job names) need the jobs.
+ # describes it. Only re-runs (earlier attempts), failures (failed job names) and runs that stopped
+ # reporting (whose job rows are the only settled outcome) need the jobs.
job_attempts = self._query_job_attempts(
- [int(row[0]) for row in runs if int(row[8] or 1) > 1 or row[5] in DECISIVE_FAILURE_CONCLUSIONS],
+ [int(row[0]) for row in runs if int(row[8] or 1) > 1 or row[5] in DECISIVE_FAILURE_CONCLUSIONS or row[10]],
run_from,
)
@@ -415,11 +417,15 @@ class PullRequestTimelinesQuery:
updated_at,
attempt,
created_at,
+ stopped_reporting,
) in runs:
run_attempts = job_attempts.get(int(run_id), [])
queued_at = created_at or started_at
- completed = status == "completed"
- run_failed = completed and conclusion in DECISIVE_FAILURE_CONCLUSIONS
+ # A run that stopped reporting ends at its last update, but its conclusion is not settled, so only
+ # a failed job row can mark it failed. The friction view applies the same split.
+ settled = status == "completed"
+ ended = settled or bool(stopped_reporting)
+ run_failed = settled and conclusion in DECISIVE_FAILURE_CONCLUSIONS
newest_attempt = int(attempt or 1)
for job_attempt in run_attempts:
# The run row decides its newest attempt's outcome and end: the jobs sync can still hold a
@@ -429,9 +435,9 @@ class PullRequestTimelinesQuery:
failed = bool(job_attempt.failed_jobs) or (is_newest and run_failed)
completed_at = job_attempt.completed_at
succeeded = job_attempt.succeeded and not failed
- if is_newest and completed:
+ if is_newest and ended:
completed_at = updated_at or completed_at
- succeeded = conclusion == "success" and not failed
+ succeeded = settled and conclusion == "success" and not failed
attempts[int(number)].append(
RunAttempt(
run_id=int(run_id),
@@ -458,9 +464,9 @@ class PullRequestTimelinesQuery:
attempt=newest_attempt,
queued_at=queued_at,
started_at=started_at,
- completed_at=updated_at if completed else None,
+ completed_at=updated_at if ended else None,
failed=run_failed,
- succeeded=completed and conclusion == "success",
+ succeeded=settled and conclusion == "success",
failed_jobs=(),
)
)
diff --git a/products/engineering_analytics/backend/logic/views/pr_friction.py b/products/engineering_analytics/backend/logic/views/pr_friction.py
index abd0ca0d8dc9..0037e105814c 100644
--- a/products/engineering_analytics/backend/logic/views/pr_friction.py
+++ b/products/engineering_analytics/backend/logic/views/pr_friction.py
@@ -225,16 +225,19 @@ run_rows AS (
-- One row per run, with its attempts assembled the way PullRequestTimelinesQuery does.
SELECT r.pr_number AS number, r.id AS run_id, r.is_merge_queue AS is_merge_queue, r.head_sha AS head_sha,
r.head_branch AS head_branch, r.workflow_name AS workflow_name, r.status AS status,
+ r.stopped_reporting AS stopped_reporting,
r.run_started_at AS run_started_at, r.updated_at AS updated_at,
coalesce(r.created_at, r.run_started_at) AS queued_at,
b.started_at AS s0, b.ended_at AS e0,
NOT r.is_merge_queue AND ifNull(r.conclusion, '') != 'skipped' AS is_ci_run,
ifNull(r.run_attempt, 1) AS newest,
- r.status = 'completed' AS run_completed,
+ -- A run that stopped reporting ends at its last update. Only a failed job row can mark it failed.
+ r.status = 'completed' OR r.stopped_reporting AS run_completed,
r.status = 'completed' AND ifNull(r.conclusion, '') IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL}) AS run_failed,
r.status = 'completed' AND ifNull(r.conclusion, '') = 'success' AS run_success,
- -- Only re-runs and failures need job rows: a first attempt that did not fail is its run row.
- if(ifNull(r.run_attempt, 1) > 1 OR ifNull(r.conclusion, '') IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL}), ja.jas, []) AS jas,
+ -- Only re-runs, failures and stopped runs need job rows: a first attempt that did not fail is its run row.
+ if(ifNull(r.run_attempt, 1) > 1 OR ifNull(r.conclusion, '') IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})
+ OR r.stopped_reporting, ja.jas, []) AS jas,
m.fails AS master_fails
FROM ({runs}) AS r
INNER JOIN bounds AS b ON b.number = r.pr_number
@@ -265,7 +268,8 @@ runs_with_attempts AS (
),
runs_explained AS (
-- Attempt tuple gains element 9: every failed job also failed on the default branch nearby.
- SELECT number, is_merge_queue, head_sha, head_branch, workflow_name, status, run_started_at, updated_at, queued_at,
+ SELECT number, is_merge_queue, head_sha, head_branch, workflow_name, status, stopped_reporting, run_started_at,
+ updated_at, queued_at,
s0, e0, is_ci_run, run_failed,
if(is_ci_run, arrayMap(a -> tuple(a.1, a.2, a.3, a.4, a.5, a.6, a.7, a.8,
a.5 AND a.4 IS NOT NULL AND length(a.7) > 0 AND arrayAll(fj -> arrayExists(
@@ -283,7 +287,7 @@ workflows AS (
arraySort(x -> tuple(x.3, x.1, x.8), arrayFlatten(groupArray(attempts))) AS xs,
minIf(run_started_at, is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0) AS gate_start,
if(countIf(is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0
- AND (status != 'completed' OR updated_at IS NULL)) > 0,
+ AND ((status != 'completed' AND NOT stopped_reporting) OR updated_at IS NULL)) > 0,
{_FAR}, maxIf(updated_at, is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0)) AS gate_end,
countIf(is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0) > 0 AS has_gate,
max(is_merge_queue AND run_started_at >= now() - INTERVAL {gate_days} DAY AND run_started_at <= e0 AND run_failed) AS gate_failed
@@ -309,7 +313,7 @@ workflow_spans AS (
arrayMap(i -> tuple(xs[i].3, least(coalesce(xs[i].4, {_FAR}), if(i < length(xs), xs[i + 1].3, {_FAR}))), arrayEnumerate(xs)),
if(length(xs) > 0, [tuple(arrayMin(arrayMap(y -> if(y.1 = 1, y.2, {_FAR}), xs)), xs[1].3)], [])
)) AS runs,
- arrayCount(x -> x.1 > 1 AND x.5, xs) AS futile_reruns
+ arrayMap(x -> toStartOfFiveMinutes(x.3), arrayFilter(x -> x.1 > 1 AND x.5, xs)) AS futile_rerun_starts
FROM workflows
),
commits AS (
@@ -317,7 +321,9 @@ commits AS (
any(s0) AS c_s0, any(e0) AS c_e0,
min(first_created) AS pushed_at,
arrayFlatten(groupArray(reds)) AS reds, arrayFlatten(groupArray(runs)) AS runs,
- sum(futile_reruns) AS futile_reruns,
+ -- One "Re-run all" starts a new attempt of every failed workflow of the commit at once. It is one
+ -- action of the author, so a commit counts failed re-runs that start in the same five minutes once.
+ arrayDistinct(arrayFlatten(groupArray(futile_rerun_starts))) AS futile_rerun_starts,
any(gate_start) AS gate_start, any(gate_end) AS gate_end, max(has_gate) AS has_gate, max(gate_failed) AS gate_failed
FROM workflow_spans
GROUP BY number, is_merge_queue, key
@@ -327,7 +333,7 @@ per_pr AS (
arraySort(p -> tuple(p.1, p.4), groupArrayIf(tuple(pushed_at, reds, runs, key), NOT is_merge_queue AND pushed_at <= c_e0)) AS pushes,
groupArrayIf(tuple(gate_start, gate_end), is_merge_queue AND has_gate) AS gates,
countIf(is_merge_queue AND has_gate AND gate_failed) AS kickouts,
- sumIf(futile_reruns, NOT is_merge_queue AND pushed_at <= c_e0) AS futile_reruns
+ sumIf(length(futile_rerun_starts), NOT is_merge_queue AND pushed_at <= c_e0) AS futile_reruns
FROM commits
GROUP BY number
),
diff --git a/products/engineering_analytics/backend/logic/views/workflow_runs.py b/products/engineering_analytics/backend/logic/views/workflow_runs.py
index 0d5a7a400fe6..03572f0c1531 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_runs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_runs.py
@@ -90,6 +90,13 @@ from products.engineering_analytics.backend.logic.merge_queue import source_pr_n
# contributor-named branch can't re-key someone else's runs onto their PR (see logic.merge_queue).
_MERGE_QUEUE_PR_NUMBER = source_pr_number_expr("head_branch", queue_actor_column="JSONExtractString(actor, 'login')")
+# An unfinished run with no update for a day. The webhook sync can miss or misorder the final event of a
+# run, most often a workflow that GitHub skips at once, and the row then stays in_progress or queued
+# forever. A consumer that treats an unfinished run as still running would count it open until the pull
+# request merges, so the timeline reads such a run as ended at its last update. The run row then gives
+# it no outcome, and only a failed job row can mark it failed.
+STOPPED_REPORTING_SQL = "(status != 'completed' AND updated_at < now() - INTERVAL 1 DAY)"
+
# The run's PR association, narrowed to PRs based in the run's OWN repo (see module docstring).
# ``> 0`` guards the both-missing case: JSONExtractInt yields 0 for an absent key, so a malformed
# entry would otherwise "match" a run whose ``repository`` JSON never landed.
@@ -160,6 +167,7 @@ def build_query(table_name: str, *, pull_requests_table: str | None = None, star
if(merge_queue_pr_number > 0, merge_queue_pr_number, association_pr_number) AS pr_number,
{commit_pr_number} AS commit_pr_number,
if(status = 'completed', dateDiff('second', run_started_at, updated_at), NULL) AS duration_seconds,
+ {STOPPED_REPORTING_SQL} AS stopped_reporting,
arrayElement(repo_parts, 1) AS repo_owner,
arrayElement(repo_parts, 2) AS repo_name
FROM (
diff --git a/products/engineering_analytics/backend/tests/test_friction.py b/products/engineering_analytics/backend/tests/test_friction.py
index 0ef3bc8021cc..963116e2b3c8 100644
--- a/products/engineering_analytics/backend/tests/test_friction.py
+++ b/products/engineering_analytics/backend/tests/test_friction.py
@@ -12,7 +12,10 @@ from posthog.hogql.errors import QueryError
from products.engineering_analytics.backend.facade.contracts import FrictionGroup
from products.engineering_analytics.backend.logic.friction import (
+ CI_WAIT_CAP_SECONDS,
+ COUNT_CAP,
MIN_PULL_REQUESTS,
+ QUEUE_CAP_SECONDS,
FrictionScorer,
PullRequestFriction,
build_author_friction,
@@ -135,6 +138,26 @@ class TestFrictionScore(SimpleTestCase):
assert queue["once_queued"] < queue["always_queued"]
+ @parameterized.expand(
+ [
+ ("queue_time", {"queue_seconds": float(QUEUE_CAP_SECONDS)}, {"queue_seconds": 7 * 24 * 3600.0}),
+ ("ci_wait", {"ci_wait_seconds": (float(CI_WAIT_CAP_SECONDS),)}, {"ci_wait_seconds": (25 * 24 * 3600.0,)}),
+ ("futile_reruns", {"futile_rerun_count": COUNT_CAP}, {"futile_rerun_count": 41}),
+ ("master_red", {"master_red_count": COUNT_CAP}, {"master_red_count": 44}),
+ ("kickouts", {"kickout_count": COUNT_CAP}, {"kickout_count": 12}),
+ ]
+ )
+ def test_one_outlier_pull_request_scores_no_higher_than_the_cap(
+ self, _name: str, at_cap: dict[str, Any], far_past_cap: dict[str, Any]
+ ) -> None:
+ rows = _population()
+ rows += [_pr("at_cap", 800 + i, **(at_cap if i == 0 else {})) for i in range(MIN_PULL_REQUESTS)]
+ rows += [_pr("far_past_cap", 900 + i, **(far_past_cap if i == 0 else {})) for i in range(MIN_PULL_REQUESTS)]
+
+ scores = {item.author: item.score for item in FrictionScorer(rows).score()}
+
+ assert scores["far_past_cap"] == pytest.approx(scores["at_cap"])
+
@parameterized.expand(
[
("no_view_yet", None, None, False, [], []),
diff --git a/products/engineering_analytics/backend/tests/test_pr_friction.py b/products/engineering_analytics/backend/tests/test_pr_friction.py
index 78f4a0545cfc..23dc4ac3288d 100644
--- a/products/engineering_analytics/backend/tests/test_pr_friction.py
+++ b/products/engineering_analytics/backend/tests/test_pr_friction.py
@@ -50,7 +50,7 @@ def _run(
**kwargs: Any,
) -> dict[str, Any]:
start, end = _span(offset, duration)
- status = "completed" if conclusion else "in_progress"
+ status = kwargs.pop("status", None) or ("completed" if conclusion else "in_progress")
row = _run_row(run_id, kwargs.pop("name", "CI"), sha, status, conclusion, start, end, **kwargs)
# The runs snapshot keeps the newest attempt's start, but the run was created with its first attempt.
if created_offset is not None:
@@ -63,7 +63,7 @@ def _job(job_id: int, run_id: int, name: str, conclusion: str, offset: int, dura
return _job_row(job_id, run_id, name, conclusion, started=start, completed=end, **kwargs)
-def _gate(run_id: int, pr: int, attempt: str, conclusion: str, offset: int, duration: int) -> dict[str, Any]:
+def _gate(run_id: int, pr: int, attempt: str, conclusion: str | None, offset: int, duration: int) -> dict[str, Any]:
return _run(
run_id,
f"queue{run_id}",
@@ -94,6 +94,11 @@ class TestPRFrictionView(_WarehouseMixin):
_merged(36, 120),
_merged(37, 360),
_merged(38, 60, login="dependabot[bot]"),
+ _merged(40, 190),
+ _merged(41, 180),
+ _merged(42, 200),
+ _merged(43, 120),
+ _merged(44, 120),
_pr_row(39, "alice", "closed", 0, _ago(70), merged_at=_at(60), default_branch="master"),
],
)
@@ -114,13 +119,34 @@ class TestPRFrictionView(_WarehouseMixin):
_run(3401, "sha34", "success", 0, 15, pr_number=34),
_gate(3402, 34, "first", "failure", 60, 30),
_gate(3403, 34, "second", "success", 120, 30),
- # 35: two runs of one workflow start in the same second; the unfinished one has the higher id.
+ # 35: two runs of one workflow start in the same second. The unfinished one has the higher id and
+ # stopped reporting days ago, so it ends at its start instead of running until the merge.
_run(3501, "sha35", "success", 0, 5, pr_number=35, name="Lint"),
_run(3502, "sha35", None, 0, 0, pr_number=35, name="Lint"),
# 37: approved three hours after ready, then pushed again.
_run(3701, "sha37a", "success", 0, 10, pr_number=37),
_run(3702, "sha37b", "success", 300, 10, pr_number=37),
_run(3801, "sha38", "success", 0, 10, pr_number=38),
+ # 40: kicked out, pushed again and merged. A skipped gate run of the first attempt stayed
+ # in_progress, which must not hold the queue open until the merge.
+ _run(4001, "sha40a", "success", 0, 10, pr_number=40),
+ _gate(4002, 40, "first", "failure", 20, 30),
+ _gate(4003, 40, "first", None, 20, 0),
+ _run(4004, "sha40b", "success", 120, 10, pr_number=40),
+ _gate(4005, 40, "second", "success", 150, 30),
+ # 41: "Re-run all" re-ran two failed workflows of one commit, and both failed again.
+ _run(4101, "sha41a", "failure", 30, 10, pr_number=41, run_attempt=2, created_offset=0),
+ _run(4102, "sha41a", "failure", 30, 10, pr_number=41, run_attempt=2, created_offset=0, name="Lint"),
+ _run(4103, "sha41b", "success", 120, 10, pr_number=41),
+ # 42: two failed workflows re-run separately, an hour apart, and both failed again.
+ _run(4201, "sha42a", "failure", 90, 10, pr_number=42, run_attempt=2, created_offset=0),
+ _run(4202, "sha42a", "failure", 30, 10, pr_number=42, run_attempt=2, created_offset=0, name="Lint"),
+ _run(4203, "sha42b", "success", 150, 10, pr_number=42),
+ # 43: stopped reporting with a stale conclusion, which must not turn the run red.
+ _run(4301, "sha43", "failure", 0, 20, pr_number=43, status="in_progress"),
+ # 44: a first attempt stopped reporting, but its job row settled as a failure before a fixing push.
+ _run(4401, "sha44a", None, 0, 0, pr_number=44),
+ _run(4402, "sha44b", "success", 60, 10, pr_number=44),
],
)
self._create_table(
@@ -133,6 +159,15 @@ class TestPRFrictionView(_WarehouseMixin):
_job(4, 3201, "test (1/2)", "failure", 20, 10, run_attempt=2),
_job(5, 3201, "test (1/2)", "failure", 40, 10, run_attempt=3),
_job(6, 3901, "test (2/2)", "failure", 0, 5, head_branch="master"),
+ _job(7, 4101, "build", "failure", 0, 10),
+ _job(8, 4101, "build", "failure", 30, 10, run_attempt=2),
+ _job(9, 4102, "lint", "failure", 0, 10),
+ _job(10, 4102, "lint", "failure", 30, 10, run_attempt=2),
+ _job(11, 4201, "build", "failure", 0, 10),
+ _job(12, 4201, "build", "failure", 90, 10, run_attempt=2),
+ _job(13, 4202, "lint", "failure", 0, 10),
+ _job(14, 4202, "lint", "failure", 30, 10, run_attempt=2),
+ _job(15, 4401, "build", "failure", 0, 10),
],
)
self._create_table(
@@ -214,7 +249,7 @@ class TestPRFrictionView(_WarehouseMixin):
if number in timeline_figures
}
- assert set(timeline_figures) == {31, 32, 33, 34, 35, 36, 37, 39}
+ assert set(timeline_figures) == {31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44}
assert view_figures == timeline_figures
def test_view_counts_what_the_author_went_through(self) -> None:
@@ -259,7 +294,14 @@ class TestPRFrictionView(_WarehouseMixin):
37: {**base, "push_count": 2, "first_approval_wait_seconds": 3 * 3600.0, "pushes_after_approval": 1},
38: {**base, "is_bot": True},
39: {**base, "push_count": 0},
+ 40: {**base, "push_count": 2, "kickout_count": 1},
+ 41: {**base, "push_count": 2, "own_red_count": 2, "futile_rerun_count": 1},
+ 42: {**base, "push_count": 2, "own_red_count": 1, "futile_rerun_count": 2},
+ 43: base,
+ 44: {**base, "push_count": 2, "own_red_count": 1},
}
assert self._github_source is not None
assert {row["source_id"] for row in rows.values()} == {str(self._github_source.id)}
- assert rows[35]["ci_wait_seconds"] == [timedelta(hours=1).total_seconds()]
+ assert rows[35]["ci_wait_seconds"] == [0.0]
+ # The first gate attempt ends when its finished runs end: 30 minutes, plus 40 from the second gate to the merge.
+ assert rows[40]["queue_seconds"] == timedelta(minutes=70).total_seconds()
diff --git a/products/engineering_analytics/frontend/lib/friction.ts b/products/engineering_analytics/frontend/lib/friction.ts
index d82da77630de..6cc5b0522146 100644
--- a/products/engineering_analytics/frontend/lib/friction.ts
+++ b/products/engineering_analytics/frontend/lib/friction.ts
@@ -14,10 +14,10 @@ export const FRICTION_GROUP_LABELS: Record<FrictionGroupEnumApi, string> = {
}
export const FRICTION_GROUP_DESCRIPTIONS: Record<FrictionGroupEnumApi, string> = {
- queue: 'time in the merge queue past 30 minutes, and kickouts',
+ queue: 'time in the merge queue from 30 minutes up to 4 hours, and up to 3 kickouts per pull request',
review: 'the wait for the first approval',
- ci: 'red CI by cause, re-runs that failed again, and CI time past 10 minutes per push',
- rework: 'own failures fixed by a push, extra pushes, and pushes after approval',
+ ci: 'red CI by cause and re-runs that failed again, up to 3 of each per pull request, and CI time from 10 minutes up to 2 hours per push',
+ rework: 'own failures fixed by a push (up to 3 per pull request), extra pushes, and pushes after approval',
}
export const FRICTION_GROUP_COLORS: Record<FrictionGroupEnumApi, string> = {