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 @@

Repository stats

const locEnd = DATA.loc.days.filter((d) => d[0] <= r.hi).slice(-1)[0]; const kpi = (label, value, hint, b) => h("div", { class: "kpi" }, h("div", { class: "label" }, label), h("div", { class: "value" }, value, bandEl(b)), h("div", { class: "hint" }, hint)); const freq = deploys.length / days; + const cyc = cycleSplit(merged); + const noCyc = META.mode === "git" ? "needs API review data" : "no review data"; app.append(h("div", { class: "kpis", id: "overview" }, kpi("Merged PRs", fmtInt(merged.length), `${fmtNum(merged.length / days * 7)} per week`), kpi("Median PR size", merged.length ? fmtInt(size.median) : "–", `lines changed · p90 ${fmtInt(size.p90)}`), kpi("Median lead time", fmtDur(lead.median), `${lm.label} · p90 ${fmtDur(lead.p90)}`, band("lead", lead.median)), + kpi("Median review cycles", cyc.reviewed.length ? fmtNum(cyc.stReviewed.median) : "–", cyc.known.length ? `reviewed PRs · p90 ${fmtNum(cyc.stReviewed.p90)} · ${fmtNum(cyc.stAll.median)} incl. unreviewed` : noCyc), + kpi("Merged without review", cyc.known.length ? fmtInt(cyc.unreviewed.length) : "–", cyc.known.length ? `${fmtPct(cyc.unreviewed.length / cyc.known.length)} of merged PRs` : noCyc), kpi("Releases", fmtInt(deploys.length), deploys.length ? `${fmtNum(freq * 7)} per week` : "no release tags matched", deploys.length ? band("freq", freq) : null), kpi("Change failure rate", fmtPct(cfr), `${fails} revert/hotfix PRs`, band("cfr", cfr)), kpi("High or critical risk", fmtPct(hiRisk), "share of merged PRs"), @@ -819,12 +832,13 @@

Repository stats

const lm = leadMode(prs); const types = [...new Set(prs.map((p) => p.type))].sort((a, b) => prs.filter((p) => p.type === b).length - prs.filter((p) => p.type === a).length); tc.body.append(h("div", { class: "tablewrap" }, h("table", null, - h("thead", null, h("tr", null, ["Type", "PRs", "Share", "Median lines", "p90 lines", "Median files", lm.release ? "Median lead (to release)" : "Median lead (to merge)", "Mean risk", "Breaking"].map((c) => h("th", null, c)))), + h("thead", null, h("tr", null, ["Type", "PRs", "Share", "Median lines", "p90 lines", "Median files", lm.release ? "Median lead (to release)" : "Median lead (to merge)", "Median review cycles", "Mean risk", "Breaking"].map((c) => h("th", null, c)))), h("tbody", null, types.map((t) => { const sub = prs.filter((p) => p.type === t); return h("tr", null, h("td", null, t), h("td", null, fmtInt(sub.length)), h("td", null, fmtPct(sub.length / prs.length)), h("td", null, fmtInt(stats(sub.map((p) => p.lines)).median)), h("td", null, fmtInt(stats(sub.map((p) => p.lines)).p90)), h("td", null, fmtInt(stats(sub.map((p) => p.files)).median)), h("td", null, fmtDur(stats(sub.map((p) => p[lm.key])).median)), + h("td", null, fmtNum(cycleSplit(sub).stReviewed.median)), h("td", null, fmtNum(stats(sub.map((p) => p.risk)).mean)), h("td", null, fmtInt(sub.filter((p) => p.breaking).length))); }))))); const src = groupBy(prs, (p) => p.type_source); @@ -910,6 +924,78 @@

Repository stats

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 @@

Repository stats

renderTypes(app, sel); renderRisk(app, sel); renderTime(app, sel); + renderReviews(app, sel); renderDora(app, sel); renderMethod(app); scrollTo(0, y); @@ -1067,7 +1162,7 @@

Repository stats

renderAll(); let resizeTimer; addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(renderAll, 200); }); -window.__repoStats = { stats, percentile, bucketStart, countBuckets, band }; +window.__repoStats = { stats, percentile, bucketStart, countBuckets, band, cycleSplit }; diff --git a/repo-stats/tests/mock_servers.py b/repo-stats/tests/mock_servers.py index 091c726..f4dfc7b 100644 --- a/repo-stats/tests/mock_servers.py +++ b/repo-stats/tests/mock_servers.py @@ -102,18 +102,21 @@ def gh_node(number: int, title: str, created: int, merged: int | None = None, cl state: str | None = None, base: str = "main", head: str | None = None, author: str = "alice", author_type: str = "User", additions: int = 10, deletions: int = 2, files: int = 1, commits: int = 1, first_commit: int | None = None, merge_oid: str | None = None, labels: Iterable[str] = (), - reviews: Iterable[tuple[str, str, str, int]] = (), ready: int | None = None, - draft: bool = False) -> dict[str, Any]: + reviews: Iterable[tuple[Any, ...]] = (), ready: int | None = None, + draft: bool = False, review_total: int | None = None) -> dict[str, Any]: """Build one GitHub GraphQL pullRequest node with the fields repo_stats queries. Times are Unix seconds. The state is MERGED when `merged` is set and OPEN otherwise, unless `state` is given. Args: - reviews: (login, author __typename, review state, submitted time) tuples. + reviews: (login, author __typename, review state, submitted time[, reviewed commit oid]) tuples. + Without an oid every review is of the same commit "c0". ready: Time of the ready-for-review event, if any. + review_total: reviews.totalCount; defaults to the number of reviews given. """ state = state or ("MERGED" if merged else "OPEN") + reviews = list(reviews) return { "number": number, "title": title, "state": state, "isDraft": draft, "createdAt": iso(created), "mergedAt": iso(merged), "closedAt": iso(closed or merged), "additions": additions, "deletions": deletions, @@ -122,8 +125,9 @@ def gh_node(number: int, title: str, created: int, merged: int | None = None, cl "labels": {"nodes": [{"name": l} for l in labels]}, "mergeCommit": {"oid": merge_oid} if merge_oid else None, "commits": {"totalCount": commits, "nodes": [{"commit": {"authoredDate": iso(first_commit or created)}}]}, - "reviews": {"nodes": [{"submittedAt": iso(ts), "state": st, "author": {"login": lg, "__typename": ty}} - for lg, ty, st, ts in reviews]}, + "reviews": {"totalCount": len(reviews) if review_total is None else review_total, + "nodes": [{"submittedAt": iso(r[3]), "state": r[2], "commit": {"oid": r[4] if len(r) > 4 else "c0"}, + "author": {"login": r[0], "__typename": r[1]}} for r in reviews]}, "timelineItems": {"nodes": [{"createdAt": iso(ready)}] if ready else []}, } @@ -208,9 +212,19 @@ def handler(req: Request) -> Response: return handler -def gl_note(author: str, ts: int, system: bool = False, bot: bool = False) -> dict[str, Any]: - """Build one GitLab note (MR comment) object.""" - return {"author": {"username": author, "bot": bot}, "created_at": iso(ts), "system": system} +def gl_note(author: str, ts: int, system: bool = False, bot: bool = False, body: str = "") -> dict[str, Any]: + """Build one GitLab note (MR comment, or a system note such as "added 1 commit") object.""" + return {"author": {"username": author, "bot": bot}, "created_at": iso(ts), "system": system, "body": body} + + +def gl_push(author: str, ts: int, n: int = 1) -> dict[str, Any]: + """Build the GitLab system note written when `author` pushes `n` commits to the MR branch.""" + return gl_note(author, ts, system=True, body=f"added {n} commit{'s' if n != 1 else ''}\n\n") + + +def gl_approval(author: str, ts: int) -> dict[str, Any]: + """Build the GitLab system note written when `author` approves the MR.""" + return gl_note(author, ts, system=True, body="approved this merge request") def gl_commit(ts: int) -> dict[str, Any]: diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index 7703937..40d35ed 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -2633,5 +2633,169 @@ def h(req: ms.Request) -> ms.Response: self.assertEqual(set(seen), {"job-tok-123"}) +class H1_ReviewCycles(unittest.TestCase): + """Review cycles per PR: one cycle per reviewed version, from GitHub review commits or GitLab notes.""" + + H = 3600 + + def _gh(self, reviews: Sequence[tuple[Any, ...]], **kw: Any) -> dict[str, Any]: + """Convert a merged mock GitHub PR by "alice" with `reviews` into a raw PR dict.""" + return rs.github_pr(ms.gh_node(1, "feat: x", BASE, merged=BASE + 20 * self.H, reviews=reviews, **kw)) + + def _gl(self, notes: Sequence[dict[str, Any]], merged: int | None = BASE + 20 * 3600, + want_reviews: bool = True) -> dict[str, Any]: + """Run fetch_gitlab for one MR by "alice" with `notes` and return its raw PR dict.""" + mr = ms.gl_mr(1, "feat: x", BASE, merged=merged) + env = helpers.clean_env({"GITLAB_TOKEN": FAKE}) + with ms.MockServer(ms.gitlab_handler([mr], {1: [ms.gl_commit(BASE)]}, {1: list(notes)})) as srv: + cli = rs.Cli("glab", "gitlab.com", {**env, "REPO_STATS_FAKE_URL": srv.url}) + return rs.fetch_gitlab(cli, "g/p", None, "main", False, None, want_reviews, progress=lambda m: None)[0] + + # -- the counting rule + + def test_count_rule(self) -> None: + """Versions and pushes start cycles; repeat reviews of one version and unreviewed pushes do not.""" + c = rs.count_review_cycles + self.assertEqual(c([]), (0, False)) + self.assertEqual(c([(1, "review", "a"), (2, "review", "a"), (3, "review", "a")]), (1, False)) + self.assertEqual(c([(1, "review", "a"), (2, "review", "b"), (3, "review", "b"), (4, "review", "c")]), (3, False)) + self.assertEqual(c([(1, "review", None), (2, "push", None), (3, "review", None), (4, "review", None)]), (2, False)) + self.assertEqual(c([(1, "push", None), (2, "push", None), (3, "review", None)]), (1, False)) + self.assertEqual(c([(1, "review", None), (2, "push", None)]), (1, False)) # unreviewed final push + self.assertEqual(c([(3, "review", None), (1, "review", None), (2, "push", None)]), (2, False)) # any order + self.assertEqual(c([(1, "review", "a"), (2, "review", None), (3, "review", "a")]), (1, False)) # unknown oid + # Replies to an older review thread are reviews of the older commit: A, B, A, B is two versions. + self.assertEqual(c([(1, "review", "a"), (2, "review", "b"), (3, "review", "a"), (4, "review", "b")]), (2, False)) + self.assertEqual(c([(1, "review", "a"), (2, "review", "b"), (3, "review", "a"), (4, "review", "c")]), (3, False)) + + def test_github_replies_to_old_threads_add_no_cycles(self) -> None: + """A real pattern (googleapis/librarian#7469): ten reviews of f4b2, then replies alternating with 91bc.""" + b, h = BASE, self.H + oids = ["f4b2"] * 10 + ["91bc", "91bc", "f4b2", "91bc", "f4b2", "91bc"] + p = self._gh([("bob" if i % 2 else "carol", "User", "COMMENTED", b + i * 60, oid) for i, oid in enumerate(oids)] + + [("bob", "User", "APPROVED", b + h, "91bc")]) + self.assertEqual(p["review_cycles"], 2) + + def test_cap(self) -> None: + """Counting stops at the cap and says so.""" + events = [(i, "review", str(i)) for i in range(rs.REVIEW_CYCLE_CAP + 10)] + self.assertEqual(rs.count_review_cycles(events), (rs.REVIEW_CYCLE_CAP, True)) + self.assertEqual(rs.count_review_cycles(events, cap=3), (3, True)) + + # -- GitHub + + def test_github_scenarios(self) -> None: + """The plan's scenarios, counted from the commit each review was made against.""" + b, h = BASE, self.H + self.assertEqual(self._gh([])["review_cycles"], 0) + self.assertEqual(self._gh([("bob", "User", "APPROVED", b + h, "c1")])["review_cycles"], 1) + p = self._gh([("bob", "User", "CHANGES_REQUESTED", b + h, "c1"), ("bob", "User", "APPROVED", b + 3 * h, "c2")]) + self.assertEqual((p["review_cycles"], p["changes_requested"], p["reviewers"]), (2, 1, 1)) + p = self._gh([("bob", "User", "COMMENTED", b + h, "c1"), ("carol", "User", "CHANGES_REQUESTED", b + 2 * h, "c1"), + ("dave", "User", "COMMENTED", b + 3 * h, "c1"), ("bob", "User", "APPROVED", b + 5 * h, "c2")]) + self.assertEqual((p["review_cycles"], p["changes_requested"], p["reviewers"]), (2, 1, 3)) + self.assertEqual(p["inferred"], []) + + def test_github_force_push_is_a_new_version(self) -> None: + """A rebased or force-pushed head has a new oid, so its review is a new cycle.""" + p = self._gh([("bob", "User", "APPROVED", BASE + self.H, "aaa"), ("bob", "User", "APPROVED", BASE + 2 * self.H, "bbb"), + ("bob", "User", "APPROVED", BASE + 3 * self.H, "ccc")]) + self.assertEqual(p["review_cycles"], 3) + + def test_github_ignored_reviews(self) -> None: + """Author, bot, pending and post-merge reviews start no cycle.""" + b, h = BASE, self.H + p = self._gh([("alice", "User", "COMMENTED", b + h, "c1"), ("ci[bot]", "Bot", "COMMENTED", b + 2 * h, "c2"), + ("carol", "User", "PENDING", b + 3 * h, "c3"), ("bob", "User", "APPROVED", b + 4 * h, "c4"), + ("bob", "User", "COMMENTED", b + 30 * h, "c5")]) # after the merge + self.assertEqual((p["review_cycles"], p["reviewers"], p["changes_requested"]), (1, 1, 0)) + + def test_github_truncated_reviews_are_a_lower_bound(self) -> None: + """More reviews than one page returns marks the count as inferred.""" + p = self._gh([("bob", "User", "APPROVED", BASE + self.H, "c1")], review_total=150) + self.assertIn("review_cycles", p["inferred"]) + + def test_github_query_asks_for_review_commits(self) -> None: + """The GraphQL query requests the reviewed commit and the review total, and stays read-only.""" + self.assertIn("commit{oid}", rs.GITHUB_QUERY) + self.assertIn("reviews(first:100){totalCount", rs.GITHUB_QUERY) + self.assertTrue(rs.READ_ONLY_GRAPHQL.match(rs.GITHUB_QUERY)) + self.assertFalse(rs.WRITE_GRAPHQL.search(rs.GITHUB_QUERY)) + + def test_github_records_end_to_end(self) -> None: + """Through collect(): fixture PR #1 had one outside review, #10 none, the open PR #6 none so far.""" + r = api_repo() + with ms.MockServer(ms.github_handler(desc_nodes(github_nodes(r)), page_size=50)) as srv: + d, _ = collect(r, "--fake-api", srv.url, env={"GITHUB_TOKEN": FAKE}) + prs = by_number(d) + self.assertEqual((prs[1]["review_cycles"], prs[1]["reviewers"]), (1, 1)) + self.assertEqual(prs[3]["changes_requested"], 1) + self.assertEqual(prs[10]["review_cycles"], 0) + self.assertFalse(prs[10]["reviewed"]) + self.assertEqual(prs[6]["review_cycles"], 0) + self.assertEqual(d["meta"]["heuristics"]["review_cycle_cap"], rs.REVIEW_CYCLE_CAP) + + # -- GitLab + + def test_gitlab_pushes_split_cycles(self) -> None: + """Comments and approvals between pushes are one cycle; "added N commits" notes are pushes.""" + b, h = BASE, self.H + p = self._gl([ms.gl_push("alice", b + h), ms.gl_note("bob", b + 2 * h), ms.gl_note("carol", b + 3 * h), + ms.gl_push("alice", b + 4 * h, n=2), ms.gl_approval("bob", b + 5 * h), + ms.gl_push("alice", b + 6 * h)]) # unreviewed final push + self.assertEqual((p["review_cycles"], p["reviewers"], p["first_review"]), (2, 2, b + 2 * h)) + self.assertIsNone(p["changes_requested"]) + self.assertTrue(p["reviewed"]) + + def test_gitlab_approval_alone_is_a_review(self) -> None: + """An approval with no comment is a review and one cycle.""" + p = self._gl([ms.gl_approval("bob", BASE + self.H)]) + self.assertEqual((p["review_cycles"], p["first_review"]), (1, BASE + self.H)) + self.assertTrue(p["reviewed"]) + + def test_gitlab_ignored_notes(self) -> None: + """Author and bot notes, other system notes and post-merge notes are not reviews.""" + b, h = BASE, self.H + p = self._gl([ms.gl_note("alice", b + h), ms.gl_note("ci-bot", b + 2 * h, bot=True), + ms.gl_note("root", b + 3 * h, system=True, body="changed the description"), + ms.gl_approval("alice", b + 4 * h), ms.gl_note("bob", b + 30 * h)]) + self.assertEqual((p["review_cycles"], p["reviewers"]), (0, 0)) + self.assertFalse(p["reviewed"]) + + def test_gitlab_no_reviews_leaves_cycles_unknown(self) -> None: + """--no-reviews skips the notes, so cycles are unknown, not 0.""" + p = self._gl([ms.gl_note("bob", BASE + self.H)], want_reviews=False) + self.assertIsNone(p["review_cycles"]) + self.assertIsNone(p["reviewers"]) + + def test_gitlab_cap_stops_paging(self) -> None: + """An MR with far more cycles than the cap is capped at it and marked inferred (a lower bound).""" + b, notes = BASE, [] + for i in range(rs.REVIEW_CYCLE_CAP * 3): + notes += [ms.gl_push("alice", b + 2 * i), ms.gl_note("bob", b + 2 * i + 1)] + p = self._gl(notes, merged=b + 10 * DAY) + self.assertEqual(p["review_cycles"], rs.REVIEW_CYCLE_CAP) + self.assertIn("review_cycles", p["inferred"]) + + # -- git mode and output + + def test_git_mode_has_no_cycles(self) -> None: + """Git history has no reviews, so every record's cycles are None.""" + d = merge_data() + self.assertTrue(d["prs"]) + self.assertTrue(all(p["review_cycles"] is None and p["reviewers"] is None for p in d["prs"])) + + def test_csv_columns(self) -> None: + """The CSV has the three review columns, with blanks for unknown values.""" + recs = [{"id": 1, "review_cycles": 2, "changes_requested": 1, "reviewers": 2}, + {"id": 2, "review_cycles": None, "changes_requested": None, "reviewers": None}] + path = tmpdir() / "out.csv" + rs.write_csv(str(path), recs) + with path.open(encoding="utf-8") as f: + rows = list(csv.DictReader(f)) + self.assertEqual([(r["review_cycles"], r["changes_requested"], r["reviewers"]) for r in rows], + [("2", "1", "2"), ("", "", "")]) + + if __name__ == "__main__": unittest.main() diff --git a/repo-stats/tests/test_ui.py b/repo-stats/tests/test_ui.py index 2b10666..6d9ebda 100644 --- a/repo-stats/tests/test_ui.py +++ b/repo-stats/tests/test_ui.py @@ -234,6 +234,7 @@ def build_api_data() -> dict[str, Any]: git_data, _ = collect(work) subprocess.run(["git", "-C", str(work), "remote", "add", "origin", "https://github.com/acme/widgets.git"], check=True) rnd = random.Random(11) + crnd = random.Random(12) # review cycles; separate, so the seeded data above stays the same nodes = [] for i, p in enumerate(git_data["prs"]): n = p["number"] @@ -245,9 +246,14 @@ def build_api_data() -> dict[str, Any]: author, atype = "alice", "User" if i % 10 == 3: author, atype = "dependabot[bot]", "Bot" - reviews = [] + reviews: list[tuple[Any, ...]] = [] if rnd.random() < 0.85: - reviews = [("bob", "User", "APPROVED", min(merged - 60, max(ready + 60, ready + int(rnd.expovariate(1 / 20000)))))] + approved = min(merged - 60, max(ready + 60, ready + int(rnd.expovariate(1 / 20000)))) + # 0-5 earlier rounds of changes requested on older commits, spread between ready and the approval. + rounds = crnd.choice([0, 0, 0, 1, 1, 2, 3, 5]) + gap = max(1, (approved - ready - 60) // (rounds + 1)) + reviews = [("carol", "User", "CHANGES_REQUESTED", approved - gap * (rounds - k), f"v{k}") for k in range(rounds)] + reviews.append(("bob", "User", "APPROVED", approved, f"v{rounds}")) title = p["title"] if i == 7: title = "feat!: " + EVIL @@ -666,6 +672,34 @@ def test_kpi_and_dora_median_lead_time_agree(self) -> None: kpi_clean = re.sub(r"(Elite|High|Medium|Low)$", "", kpi).strip() self.assertEqual(kpi_clean, median_cell, "KPI uses lead_to_deploy ?? lead per PR, DORA card uses one metric for all PRs") + # ------------------------------------------------------------------ review cycles + def test_review_cycle_kpis_and_table_match_python(self) -> None: + """Review cycle KPIs and statistics, with and without unreviewed PRs, match Python's numbers.""" + merged = [p for p in self.sets["api"]["data"]["prs"] if p["state"] == "merged"] + known = [p["review_cycles"] for p in merged if p["review_cycles"] is not None] + reviewed = [c for c in known if c > 0] + self.assertTrue(reviewed and len(reviewed) < len(known) and max(reviewed) > 1, "dataset needs a mix of cycles") + snap = self.R["stats"]["api"]["snap"] + k = snap["kpis"] + self.assertAlmostEqual(cast(float, parse_num(k["Median review cycles"]["value"])), cast(float, percentile(reviewed, 50)), delta=0.051) + self.assertEqual(int(k["Merged without review"]["value"]), len(known) - len(reviewed)) + rows = {r[0]: r for r in snap["cycles"]} + for label, vals in (("Review cycles, reviewed PRs only", reviewed), ("Review cycles, unreviewed PRs counted as 0", known)): + want = cast(dict, stat_row(vals)) + for i, col in enumerate(COLS): + with self.subTest(label, col=col): + self.assertAlmostEqual(cast(float, parse_num(rows[label][i + 1])), want[col], delta=0.051) + self.assertEqual(sum(int(r[1]) for r in snap["cyclesBySize"]), len(known)) + self.assertEqual(int(snap["mostCycles"][0][3]), max(reviewed)) + + def test_review_cycles_need_api_in_git_mode(self) -> None: + """In git mode the review cycle KPIs are empty and the section says it needs the API.""" + snap = self.R["stats"]["merge"]["snap"] + self.assertEqual(snap["kpis"]["Median review cycles"]["value"], "–") + self.assertEqual(snap["kpis"]["Merged without review"]["hint"], "needs API review data") + self.assertIsNone(snap["cycles"]) + self.assertTrue(any("Review cycles need review data" in e for e in snap["empties"])) + # ------------------------------------------------------------------ D6 def test_d6_tooltips(self) -> None: """Chart tooltips show valid text inside the viewport and hide on mouse leave.""" diff --git a/repo-stats/tests/ui_runner.js b/repo-stats/tests/ui_runner.js index ed9f422..6340c70 100644 --- a/repo-stats/tests/ui_runner.js +++ b/repo-stats/tests/ui_runner.js @@ -73,6 +73,9 @@ const snapshot = (page) => page.evaluate(() => { periodStats: tbl('Merged PRs per period: statistics'), byType: tbl('Statistics by type'), duration: tbl('Duration statistics'), + cycles: tbl('Review cycle statistics'), + cyclesBySize: tbl('Review cycles by PR size'), + mostCycles: tbl('Ten PRs with the most review cycles'), empties: [...document.querySelectorAll('.empty')].map((e) => e.textContent), preset: (document.querySelector('#preset') || {}).value, title: document.title, @@ -121,7 +124,7 @@ async function applyStep(page, st) { ds: d.name, theme, width, errors: rec.errors, pageErrors: rec.pageErrors, dialogs: rec.dialogs, attempts: rec.attempts, hscroll: await hScroll(page), themeAttr: await page.evaluate(() => document.documentElement.dataset.theme), text: await textIssues(page), - sections: await page.evaluate(() => ['overview', 'loc', 'throughput', 'size', 'types', 'risk', 'time', 'dora', 'method'].filter((id) => !document.getElementById(id))), + sections: await page.evaluate(() => ['overview', 'loc', 'throughput', 'size', 'types', 'risk', 'time', 'reviews', 'dora', 'method'].filter((id) => !document.getElementById(id))), cards: await page.evaluate(() => document.querySelectorAll('section.card').length), svgs: await page.evaluate(() => document.querySelectorAll('svg').length), overflowing: await page.evaluate(() => [...document.querySelectorAll('body *')].filter((e) => { const r = e.getBoundingClientRect(); return r.width > 0 && r.right > window.innerWidth + 1 && !e.closest('.tablewrap') && !e.closest('svg') && !e.closest('#tip'); }).slice(0, 5).map((e) => e.tagName + '.' + e.className)),