diff --git a/repo-stats/README.adoc b/repo-stats/README.adoc
index 878daf1..0a00116 100644
--- a/repo-stats/README.adoc
+++ b/repo-stats/README.adoc
@@ -8,6 +8,7 @@ Generate a self-contained HTML dashboard of code statistics for any git reposito
* PR type, read from Conventional Commit titles.
* A transparent risk score for each PR.
* Time per PR: coding, pickup, review, open to merge, lead time and merge to release.
+* Review cycles per PR, and how many PRs were merged with no review (API data).
* DORA metrics: deployment frequency, lead time for changes, change failure rate and time to restore.
Every metric shows count, mean, median, p75, p90, p95, p99, min, max and standard deviation.
@@ -256,6 +257,26 @@ The rate is failures divided by merged PRs.
Time to restore::
For reverts that name the commit they undo: the time from the reverted change's merge to the revert's merge.
+Review cycles (API only)::
+One round of review on one version of the PR, by anyone but the author and bots, before the merge.
++
+[cols="3,1"]
+|===
+| Scenario | Cycles
+
+| Merged with no review | 0
+| Approved on first look | 1
+| Changes requested, author pushes a fix, approved | 2
+| Three reviewers comment on the same commit, then approval after one push | 2
+| Author pushes again after approval, then merges with no re-review | 2 (an unreviewed push is not a cycle)
+|===
++
+On GitHub, each review names the commit it was made against, so a review of a new commit (including after a force-push) starts a new cycle.
+On GitLab, comments and approvals by others are reviews and "added N commits" system notes are pushes; a cycle is the reviews between two pushes.
+All of an MR's notes are read, up to 50 cycles.
+The dashboard shows the statistics without unreviewed PRs, with them counted as 0, and the number of PRs merged with no review.
+Git history has no reviews, so in git mode cycles are empty, never guessed.
+
Performance bands::
The Elite, High, Medium and Low bands use rounded thresholds from published DORA reports. Treat them as rough.
diff --git a/repo-stats/repo_stats.py b/repo-stats/repo_stats.py
index d8ec207..f412517 100644
--- a/repo-stats/repo_stats.py
+++ b/repo-stats/repo_stats.py
@@ -111,6 +111,13 @@ class RiskFactor(TypedDict):
}
SIZE_BUCKETS = [[10, "XS"], [100, "S"], [500, "M"], [1000, "L"], [None, "XL"]]
+# Review cycles per PR: the dashboard groups counts into these bars; the last one is "this many or more".
+REVIEW_CYCLE_BUCKETS = [0, 1, 2, 3, 4, 5]
+# Counting stops here (the value is then marked inferred). Real PRs very rarely go past a handful.
+REVIEW_CYCLE_CAP = 50
+# GitLab system notes that mark a push to the MR branch, an approval and a change request.
+GITLAB_PUSH_NOTE = re.compile(r"^\s*(?:added \d+ (?:new )?commits?|force-pushed)\b", re.I)
+GITLAB_REVIEW_NOTE = re.compile(r"^\s*(?:approved this merge request|requested changes)\b", re.I)
DEFAULT_SENSITIVE = (
r"(^|/)(migrations?|db/migrate|schema|auth|authn|authz|security|crypto|secrets?|payments?|"
@@ -895,7 +902,7 @@ def parse_iso(s: Optional[str]) -> Optional[int]:
labels(first:20){nodes{name}}
mergeCommit{oid}
commits(first:1){totalCount nodes{commit{authoredDate}}}
- reviews(first:50){nodes{submittedAt state author{login __typename}}}
+ reviews(first:100){totalCount nodes{submittedAt state commit{oid} author{login __typename}}}
timelineItems(first:20,itemTypes:[READY_FOR_REVIEW_EVENT]){nodes{... on ReadyForReviewEvent{createdAt}}}
}
}
@@ -959,6 +966,35 @@ def _is_bot(login: Optional[str], typename: Optional[str] = None) -> bool:
return bool(typename == "Bot" or (login and (login.endswith("[bot]") or login.endswith("-bot"))))
+def count_review_cycles(events: Iterable[Tuple[int, str, Optional[str]]], cap: int = REVIEW_CYCLE_CAP) -> Tuple[int, bool]:
+ """Count review cycles from (time, kind, version) events; return (cycles, capped).
+
+ kind is "review" or "push". A cycle starts at the first review of a version that no earlier review
+ covered: a version (a commit oid) not seen in any earlier review, or, for events without a version, the
+ first review after a push. Reviews of an already reviewed version are part of an earlier cycle (on
+ GitHub, a reply to an old review thread is a new review of the old commit), and a push that nobody
+ reviews before the merge starts none. Counting stops at `cap` (capped is then True).
+ """
+ cycles = 0
+ fresh = True # the next version-less review sees code that no review has covered yet
+ seen: set[str] = set()
+ for _, kind, version in sorted(events, key=lambda e: (e[0], e[1] != "push")):
+ if kind == "push":
+ fresh = True
+ continue
+ if version is not None:
+ new = version not in seen
+ seen.add(version)
+ else:
+ new = fresh
+ fresh = False
+ if new:
+ cycles += 1
+ if cycles >= cap:
+ return cap, True
+ return cycles, False
+
+
def github_pr(n: Dict[str, Any]) -> PR:
"""Convert one GraphQL pullRequest node into a raw PR dict."""
author = (n.get("author") or {})
@@ -970,12 +1006,18 @@ def github_pr(n: Dict[str, Any]) -> PR:
ready = parse_iso(t["createdAt"])
break
merged_at = parse_iso(n.get("mergedAt"))
- reviews = [r for r in (n.get("reviews") or {}).get("nodes", [])
- if r and r.get("submittedAt") and r["state"] != "PENDING"
+ review_page = n.get("reviews") or {}
+ review_nodes = [r for r in review_page.get("nodes") or [] if r]
+ reviews = [r for r in review_nodes
+ if r.get("submittedAt") and r["state"] != "PENDING"
and (merged_at is None or cast(int, parse_iso(r["submittedAt"])) <= merged_at) # post-merge reviews do not count
and (r.get("author") or {}).get("login") != login
and not _is_bot((r.get("author") or {}).get("login"), (r.get("author") or {}).get("__typename"))]
first_review = min((cast(int, parse_iso(r["submittedAt"])) for r in reviews), default=None)
+ # Each review names the head commit it was made against, so a new oid is a new version under review.
+ cycles, capped = count_review_cycles(
+ (cast(int, parse_iso(r["submittedAt"])), "review", (r.get("commit") or {}).get("oid")) for r in reviews)
+ truncated = (review_page.get("totalCount") or 0) > len(review_nodes)
commits = n.get("commits") or {}
first_commit = None
if commits.get("nodes"):
@@ -991,7 +1033,10 @@ def github_pr(n: Dict[str, Any]) -> PR:
"additions": n.get("additions"), "deletions": n.get("deletions"), "files": n.get("changedFiles"),
"labels": [l["name"] for l in (n.get("labels") or {}).get("nodes", []) if l],
"reviewed": first_review is not None if state == "merged" else None,
- "source": "api", "inferred": [], "local": None,
+ "review_cycles": cycles,
+ "changes_requested": sum(1 for r in reviews if r["state"] == "CHANGES_REQUESTED"),
+ "reviewers": len({(r.get("author") or {}).get("login") for r in reviews}),
+ "source": "api", "inferred": ["review_cycles"] if truncated or capped else [], "local": None,
}
@@ -1061,12 +1106,13 @@ def mr_commits(iid: Any) -> List[Dict[str, Any]]:
pass
def details(mr: Dict[str, Any]) -> Dict[str, Any]:
- """Fetch first commit time, commit count and first review time for one MR.
+ """Fetch first commit time, commit count, first review time and review cycles for one MR.
API errors are recorded under "commits_error" / "review_error" instead of raised, and the affected
values stay None (unknown) rather than being read as "no commits" or "no review".
"""
- out: dict[str, Any] = {"first_commit": None, "commits": None, "first_review": None}
+ out: dict[str, Any] = {"first_commit": None, "commits": None, "first_review": None,
+ "review_cycles": None, "reviewers": None, "cycles_capped": False}
iid = mr["iid"]
if not commits_refused:
try:
@@ -1081,15 +1127,32 @@ def details(mr: Dict[str, Any]) -> Dict[str, Any]:
try:
me = (mr.get("author") or {}).get("username")
merged_at = parse_iso(mr.get("merged_at"))
+ # Pushes come from system notes ("added 2 commits"), stamped when pushed, not when authored.
+ events: list[tuple[int, str, Optional[str]]] = []
+ reviewers: set[str] = set()
+ first_review: Optional[int] = None
for note in pages(f"{base}/{int(iid)}/notes", {"sort": "asc", "order_by": "created_at"}):
a = note.get("author") or {}
- if note.get("system") or a.get("username") == me or _is_bot(a.get("username"), "Bot" if a.get("bot") else None):
- continue
t = parse_iso(note.get("created_at"))
if t is None or (merged_at is not None and t > merged_at):
continue # comments after the merge are not a review
- out["first_review"] = t
- break
+ body = note.get("body") or ""
+ if note.get("system") and GITLAB_PUSH_NOTE.match(body):
+ events.append((t, "push", None))
+ continue
+ if note.get("system") and not GITLAB_REVIEW_NOTE.match(body):
+ continue
+ if a.get("username") == me or _is_bot(a.get("username"), "Bot" if a.get("bot") else None):
+ continue
+ events.append((t, "review", None))
+ reviewers.add(str(a.get("username")))
+ if first_review is None:
+ first_review = t
+ if len(events) % 100 == 0 and count_review_cycles(events)[1]:
+ break # REVIEW_CYCLE_CAP cycles is far past anything useful: stop paging
+ out["first_review"] = first_review
+ out["review_cycles"], out["cycles_capped"] = count_review_cycles(events)
+ out["reviewers"] = len(reviewers)
except (ApiError, ValueError, KeyError, TypeError, AttributeError) as e:
out["review_error"] = str(e)
return out
@@ -1115,7 +1178,11 @@ def details(mr: Dict[str, Any]) -> Dict[str, Any]:
"additions": None, "deletions": None, "files": None,
"labels": mr.get("labels") or [],
"reviewed": (ex["first_review"] is not None) if (state == "merged" and review_known) else None,
- "source": "api", "inferred": ["ready"] + ([] if review_known else ["first_review"]),
+ # Older GitLab versions record no "requested changes" event, so a 0 could mislead: leave it unknown.
+ "review_cycles": ex["review_cycles"] if review_known else None, "changes_requested": None,
+ "reviewers": ex["reviewers"] if review_known else None,
+ "source": "api", "inferred": ["ready"] + ([] if review_known else ["first_review"])
+ + (["review_cycles"] if ex["cycles_capped"] else []),
"squash_sha": mr.get("squash_commit_sha"), "local": None, "commits_refused": commits_refused,
})
return result
@@ -1237,6 +1304,9 @@ def build_records(prs: List[PR], ctx: Dict[str, Any]) -> List[Record]:
"additions": add_, "deletions": del_, "lines": lines, "files": pr["files"], "commits": pr["commits"],
"kind": kind, "source": pr["source"], "inferred": list(pr["inferred"]),
"reviewed": pr.get("reviewed"),
+ # None when unknown: git mode, GitLab with --no-reviews, or a failed review lookup.
+ "review_cycles": pr.get("review_cycles"), "changes_requested": pr.get("changes_requested"),
+ "reviewers": pr.get("reviewers"),
}
sensitive = tests = code_lines = None
if c is not None:
@@ -1336,7 +1406,7 @@ def write_csv(path: str, records: Iterable[Record]) -> None:
cols = ["id", "title", "type", "scope", "breaking", "state", "bot", "created", "first_commit", "first_review",
"merged", "additions", "deletions", "files", "commits", "risk", "risk_level", "kind",
"coding", "pickup", "review", "open_to_merge", "lead", "deployed", "deploy_wait", "lead_to_deploy",
- "restore", "source"]
+ "restore", "review_cycles", "changes_requested", "reviewers", "source"]
with open(path, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(cols)
@@ -1573,7 +1643,8 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non
"reviews": mode == "api" and not (provider == "gitlab" and args.no_reviews),
"commits_as_prs": bool(args.commits_as_prs),
"heuristics": {"risk": RISK, "size_buckets": SIZE_BUCKETS, "sensitive": args.sensitive_pattern or DEFAULT_SENSITIVE,
- "test_path": TEST_PATH.pattern, "doc_path": DOC_PATH.pattern},
+ "test_path": TEST_PATH.pattern, "doc_path": DOC_PATH.pattern,
+ "review_cycle_buckets": REVIEW_CYCLE_BUCKETS, "review_cycle_cap": REVIEW_CYCLE_CAP},
}
return {"meta": meta, "prs": records, "loc": loc, "deploys": deploys}
diff --git a/repo-stats/template.html b/repo-stats/template.html
index 955954e..2871c3b 100644
--- a/repo-stats/template.html
+++ b/repo-stats/template.html
@@ -118,7 +118,7 @@
Repository stats
@@ -654,6 +654,15 @@
Repository stats
return { release, key: release ? "lead_to_deploy" : "lead", label: release ? "first commit to release" : "first commit to merge" };
}
+/** Review cycles for PRs: known (cycle count available), reviewed (1+ cycles), unreviewed (0 cycles), with
+ * statistics that leave unreviewed PRs out (stReviewed) and that count them as 0 (stAll). */
+function cycleSplit(prs) {
+ const known = prs.filter((p) => p.review_cycles != null);
+ const reviewed = known.filter((p) => p.review_cycles > 0);
+ const unreviewed = known.filter((p) => p.review_cycles === 0);
+ return { known, reviewed, unreviewed, stReviewed: stats(reviewed.map((p) => p.review_cycles)), stAll: stats(known.map((p) => p.review_cycles)) };
+}
+
/* ------------------------------------------------------------------ sections */
const METRICS = [
["coding", "Coding time", "First commit to PR ready"],
@@ -678,10 +687,14 @@
draw();
}
+function renderReviews(app, sel) {
+ sectionHead(app, "reviews", "Review cycles", "How many rounds of review each merged PR went through. A cycle starts when someone other than the author reviews a version of the code that no earlier review covered.");
+ const grid = h("div", { class: "grid" });
+ app.append(grid);
+ const cyc = cycleSplit(sel.merged);
+ const prs = cyc.known;
+ if (!prs.length) {
+ const c = card(grid, "Review cycles", { wide: true });
+ c.body.append(h("div", { class: "empty" }, META.mode === "git" ? "Review cycles need review data from the hosting API. Install and log in to gh or glab."
+ : sel.merged.length ? "No review data for the merged PRs in this range (GitLab with --no-reviews, or the review lookups failed)." : "No merged PRs in this range."));
+ return;
+ }
+ const lowerBound = inferredShare(prs, "review_cycles");
+ const t = card(grid, "Review cycle statistics", { wide: true });
+ const rows = [
+ { key: "review_cycles", label: "Review cycles, reviewed PRs only", st: cyc.stReviewed, fmt: fmtNum },
+ { key: "review_cycles", label: "Review cycles, unreviewed PRs counted as 0", st: cyc.stAll, fmt: fmtNum },
+ { key: "changes_requested", label: "Changes-requested reviews per PR", st: stats(prs.map((p) => p.changes_requested)), fmt: fmtNum },
+ { key: "reviewers", label: "Reviewers per PR", st: stats(prs.map((p) => p.reviewers)), fmt: fmtNum },
+ ];
+ t.body.append(statsTable(rows, [{ name: "Source", value: (r) => {
+ if (!r.st.n) return r.key === "changes_requested" ? "GitHub only" : "n/a";
+ return r.key === "review_cycles" && lowerBound ? fmtPct(lowerBound) + " lower bound" : "exact";
+ } }]));
+ const missing = sel.merged.length - prs.length;
+ t.body.append(h("p", { class: "note" }, `${fmtInt(cyc.unreviewed.length)} of ${fmtInt(prs.length)} merged PRs (${fmtPct(cyc.unreviewed.length / prs.length)}) were merged with no review from anyone but the author.`
+ + (missing ? ` ${fmtInt(missing)} merged PR(s) have no review data and are left out.` : "")
+ + (lowerBound ? " A lower bound means the PR had more reviews than one API page returns, or reached the counting cap." : "")));
+
+ const B = META.heuristics.review_cycle_buckets, top = B[B.length - 1];
+ const bucketOf = (v) => Math.min(v, top);
+ const bc = card(grid, "PRs by number of review cycles", { note: `The last bar is ${top} or more cycles. 0 means merged with no review.` });
+ barChart(bc.body, { cats: B.map((b) => ({ short: b === top ? b + "+" : String(b), long: (b === top ? b + " or more" : String(b)) + (b === 1 ? " cycle" : " cycles") })),
+ series: [{ name: "Unreviewed", color: css("--st-crit"), vals: B.map((b) => b === 0 ? cyc.unreviewed.length : 0) },
+ { name: "Reviewed", color: css("--c1"), vals: B.map((b) => b === 0 ? 0 : cyc.reviewed.filter((p) => bucketOf(p.review_cycles) === b).length) }],
+ stacked: true, label: "PRs by number of review cycles", table: bc.table, catName: "Review cycles" });
+
+ const uc = card(grid, "Reviewed and unreviewed PRs by month", { note: "Merged PRs with review data, stacked." });
+ const months = countBuckets([], "month", sel.r.lo, sel.r.hi).map((b) => b.t);
+ barChart(uc.body, { cats: months.map((m) => ({ short: bucketLabel(m, "month"), long: bucketLabel(m, "month") })),
+ series: [{ name: "Reviewed", color: css("--c1"), vals: months.map((m) => cyc.reviewed.filter((p) => bucketStart(p.merged, "month") === m).length) },
+ { name: "Unreviewed", color: css("--st-crit"), vals: months.map((m) => cyc.unreviewed.filter((p) => bucketStart(p.merged, "month") === m).length) }],
+ stacked: true, label: "Reviewed and unreviewed PRs by month", table: uc.table, catName: "Month" });
+
+ const tc = card(grid, "Review cycles over time", { wide: true, note: "Median and p90 of reviewed PRs, and the mean with unreviewed PRs counted as 0, by month. Months with no reviewed PR are skipped." });
+ const byM = groupBy(prs, (p) => bucketStart(p.merged, "month"));
+ const mk = [...byM.keys()].filter((m) => byM.get(m).some((p) => p.review_cycles > 0)).sort((a, b) => a - b);
+ const monthStats = (m) => cycleSplit(byM.get(m));
+ lineChart(tc.body, { xs: mk, series: [{ name: "Median (reviewed)", color: css("--c1"), ys: mk.map((m) => monthStats(m).stReviewed.median) },
+ { name: "p90 (reviewed)", color: css("--c2"), ys: mk.map((m) => monthStats(m).stReviewed.p90) },
+ { name: "Mean (incl. unreviewed)", color: css("--c3"), ys: mk.map((m) => monthStats(m).stAll.mean) }],
+ yFmt: fmtNum, tipFmt: fmtNum, xTip: (x) => bucketLabel(x, "month"), label: "Review cycles over time", table: tc.table });
+
+ const SB = META.heuristics.size_buckets;
+ const sc = card(grid, "Review cycles by PR size", { wide: true, note: SB.map(([lim, n], i) => lim == null ? `${n} > ${SB[i - 1][0]}` : `${n} ≤ ${lim}`).join(", ") + " lines changed." });
+ const sizeOf = (v) => SB.find((b) => b[0] == null || v <= b[0])[1];
+ const sized = groupBy(prs.filter((p) => p.lines != null), (p) => sizeOf(p.lines));
+ sc.body.append(h("div", { class: "tablewrap" }, simpleTable(["Size", "PRs", "Median cycles (reviewed)", "p90 cycles (reviewed)", "Mean cycles (incl. unreviewed)", "Unreviewed", "Unreviewed share"],
+ SB.map((b) => b[1]).filter((n) => sized.has(n)).map((n) => {
+ const s2 = cycleSplit(sized.get(n));
+ return [n, fmtInt(s2.known.length), fmtNum(s2.stReviewed.median), fmtNum(s2.stReviewed.p90), fmtNum(s2.stAll.mean), fmtInt(s2.unreviewed.length), fmtPct(s2.unreviewed.length / s2.known.length)];
+ }))));
+
+ const most = cyc.reviewed.slice().sort((a, b) => b.review_cycles - a.review_cycles || (b.changes_requested || 0) - (a.changes_requested || 0) || (b.lines || 0) - (a.lines || 0)).slice(0, 10);
+ const mc = card(grid, "Ten PRs with the most review cycles", { wide: true });
+ if (!most.length) mc.body.append(h("div", { class: "empty" }, "No reviewed PRs in this range."));
+ else mc.body.append(h("div", { class: "tablewrap" }, h("table", null,
+ h("thead", null, h("tr", null, ["PR", "Type", "Lines", "Review cycles", "Changes requested", "Reviewers"].map((c) => h("th", { class: c === "PR" ? "title" : null }, c)))),
+ h("tbody", null, most.map((p) => h("tr", null, h("td", { class: "title" }, (p.number != null ? "#" + p.number + " " : "") + p.title), h("td", null, p.type), h("td", null, fmtInt(p.lines)),
+ h("td", null, fmtInt(p.review_cycles) + (p.inferred.includes("review_cycles") ? "+" : "")), h("td", null, fmtInt(p.changes_requested)), h("td", null, fmtInt(p.reviewers))))))));
+}
+
function renderDora(app, sel) {
sectionHead(app, "dora", "DORA metrics", "Deployment frequency, lead time for changes, change failure rate and time to restore. Definitions are approximations; see Methodology.");
const grid = h("div", { class: "grid" });
@@ -977,6 +1063,14 @@
Repository stats
h("dt", null, "Time to restore"), h("dd", null, "For reverts whose message says \"This reverts commit \": time from the reverted change's merge to the revert's merge."),
h("dt", null, "Performance bands"), h("dd", null, "Elite, High, Medium and Low use rounded thresholds from published DORA reports: frequency ≥ daily / ≥ weekly / ≥ monthly; lead time < 1 day / < 1 week / < 1 month; failure rate ≤ 5% / 10% / 15%; restore < 1 hour / < 1 day / < 1 week. DORA revises its definitions, so treat bands as rough.")));
+ const rv = card(grid, "Review cycles", { wide: true, note: "API data only. Reviews by the author, by bots, still pending, or submitted after the merge are ignored." });
+ rv.body.append(h("dl", { class: "method" },
+ h("dt", null, "Cycle"), h("dd", null, "One round of review on one version of the PR. A PR approved on first look has 1 cycle; changes requested, a fix pushed and an approval make 2. Several reviewers on the same version are one cycle, and a push nobody reviewed before the merge adds none."),
+ h("dt", null, "GitHub"), h("dd", null, "Each review names the head commit it was made against. The first review of a commit no earlier review covered starts a new cycle, so force-pushes and rebases count correctly, and replies to an older review thread (filed against the older commit) do not add cycles."),
+ h("dt", null, "GitLab"), h("dd", null, "From the merge request's notes: comments and approvals by other people are reviews, and \"added N commits\" system notes are pushes. A cycle is the reviews between two pushes. GitLab gives no changes-requested count."),
+ h("dt", null, "Unreviewed"), h("dd", null, "Merged PRs with 0 cycles. Statistics are shown both without them (reviewed PRs only) and with them counted as 0, and their number is shown on its own."),
+ h("dt", null, "Limits"), h("dd", null, `Counting stops at ${META.heuristics.review_cycle_cap} cycles, and GitHub returns at most 100 reviews per PR; such values are lower bounds.`)));
+
const rk = card(grid, "Risk score rules", { wide: true, note: "Points add up and are capped at " + R.cap + ". Rules that need data the source lacks are skipped, never guessed." });
const tiers = (arr, unit) => arr.map(([lim, pts], i) => `${i ? "> " + arr[i - 1][0] : "≤ " + lim}${lim != null && i ? " to " + lim : ""} ${unit}: ${pts}`).join("; ");
rk.body.append(h("dl", { class: "method" },
@@ -1056,6 +1150,7 @@