From 04dd4a36126a93770ab8d42e6a3155e46b8cd225 Mon Sep 17 00:00:00 2001 From: Husam Date: Thu, 29 Oct 2026 20:06:28 +0000 Subject: [PATCH 1/2] feat(repo-stats): count self-reviews and bot reviews separately Reviews from the PR author's own account (including agents acting with the author's credentials) and from bot accounts used to be dropped. They are now classified and counted: - review_status per merged PR: others > self > bot > none, colored separately on the dashboard (Reviewed (by others) / (self) / (bot) / Unreviewed). - self_review_cycles and bot_review_cycles, using the same per-version rule as review_cycles, so a batched review, a run of single comments, replies and several reviews of one version count as one cycle. - New "Review cycles by reviewer" chart, a status breakdown in the KPI, the stats table and the monthly chart, plus CSV columns. review_cycles, reviewers, pickup and review time and the unreviewed risk factor still use reviews by others only; the risk detail now says when a PR had only a self or bot review. --- repo-stats/README.adoc | 19 ++++++- repo-stats/repo_stats.py | 85 +++++++++++++++++++++++------ repo-stats/template.html | 62 ++++++++++++++------- repo-stats/tests/test_repo_stats.py | 53 ++++++++++++++++++ repo-stats/tests/test_ui.py | 7 ++- 5 files changed, 185 insertions(+), 41 deletions(-) diff --git a/repo-stats/README.adoc b/repo-stats/README.adoc index e86da45..50d9d20 100644 --- a/repo-stats/README.adoc +++ b/repo-stats/README.adoc @@ -8,7 +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). +* Review cycles per PR, and how many PRs were merged with no review (API data). Reviews by others, self-reviews and bot reviews are counted and colored separately. * 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. @@ -288,7 +288,8 @@ 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. +One round of review on one version of the PR, before the merge. +A batched review, a run of single comments, replies to threads and several reviews of the same version all fall in one cycle. + [cols="3,1"] |=== @@ -299,14 +300,26 @@ One round of review on one version of the PR, by anyone but the author and bots, | 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) +| Reviewer leaves five single comments, then submits a review, all on one commit | 1 |=== + 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. +On GitLab, comments and approvals 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. +Who reviewed (API only):: +Each review is classified by the account that posted it, and cycles are counted separately for each kind: ++ +* *By others*: a person other than the PR author. The headline cycle count, reviewers, pickup and review time use only these. +* *Self*: the PR author's own account. An agent that posts with the author's credentials (for example through `gh`) is the author as far as the API can tell, so it counts here. +* *Bot*: a bot account that is not the author (a GitHub App, or a login ending in `[bot]` or `-bot`). ++ +Each merged PR also gets one review status, the strongest it earned: *Reviewed (by others)*, *Reviewed (self)*, *Reviewed (bot)* or *Unreviewed*. +The dashboard colors them separately, and the CSV has `review_status`, `self_review_cycles` and `bot_review_cycles` columns. +Self and bot reviews do not clear the unreviewed risk factor. + 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 4069a55..a0f88ca 100755 --- a/repo-stats/repo_stats.py +++ b/repo-stats/repo_stats.py @@ -115,6 +115,10 @@ class RiskFactor(TypedDict): 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 +# Review status of a merged PR, strongest first. A PR takes the first status any of its pre-merge reviews +# earns: "others" (a person who is not the author), "self" (the author's own account, including agents that +# act with the author's credentials) or "bot" (a bot account that is not the author); else "none". +REVIEW_STATUSES = ["others", "self", "bot"] # 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) @@ -1151,6 +1155,24 @@ 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 reviewer_kind(pr_author: Optional[str], login: Optional[str], is_bot: bool) -> str: + """Classify one reviewer of a PR as "self" (the PR author's own account), "bot" or "others". + + The author check comes first: an agent that posts with the author's credentials is the author as far + as the API can tell, so its reviews are self-reviews. Bot accounts (GitHub Apps, *[bot], -bot) that + are not the author are "bot"; everyone else is "others". + """ + if login and pr_author and login == pr_author: + return "self" + return "bot" if is_bot else "others" + + +def review_status(kinds: Iterable[str]) -> str: + """Return the strongest review a PR received: others > self > bot > none.""" + present = set(kinds) + return next((k for k in REVIEW_STATUSES if k in present), "none") + + 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). @@ -1193,15 +1215,26 @@ def github_pr(n: Dict[str, Any]) -> PR: merged_at = parse_iso(n.get("mergedAt")) 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"))] + # Every submitted review before the merge, by reviewer kind; post-merge reviews do not count. + by_kind: dict[str, list[dict[str, Any]]] = {k: [] for k in REVIEW_STATUSES} + for r in review_nodes: + if not r.get("submittedAt") or r.get("state") == "PENDING": + continue + if merged_at is not None and cast(int, parse_iso(r["submittedAt"])) > merged_at: + continue + ra = r.get("author") or {} + by_kind[reviewer_kind(login, ra.get("login"), _is_bot(ra.get("login"), ra.get("__typename")))].append(r) + reviews = by_kind["others"] first_review = min((cast(int, parse_iso(r["submittedAt"])) for r in reviews), default=None) + + def cycles_of(rs_: List[Dict[str, Any]]) -> Tuple[int, bool]: + """Count review cycles over these reviews; each names the head commit it was made against.""" + return count_review_cycles((cast(int, parse_iso(r["submittedAt"])), "review", (r.get("commit") or {}).get("oid")) for r in rs_) + # 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) + cycles, capped = cycles_of(reviews) + self_cycles, self_capped = cycles_of(by_kind["self"]) + bot_cycles, bot_capped = cycles_of(by_kind["bot"]) truncated = (review_page.get("totalCount") or 0) > len(review_nodes) commits = n.get("commits") or {} first_commit = None @@ -1219,9 +1252,13 @@ def github_pr(n: Dict[str, Any]) -> PR: "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, "review_cycles": cycles, + "self_review_cycles": self_cycles, "bot_review_cycles": bot_cycles, + "review_status": review_status(k for k, v in by_kind.items() if v) if state == "merged" else None, "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, + "source": "api", "local": None, + "inferred": [k for k, hit_cap in (("review_cycles", capped), ("self_review_cycles", self_capped), + ("bot_review_cycles", bot_capped)) if truncated or hit_cap], } @@ -1315,7 +1352,8 @@ def details(mr: Dict[str, Any]) -> Dict[str, Any]: 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]]] = [] + pushes: list[tuple[int, str, Optional[str]]] = [] + events: dict[str, list[tuple[int, str, Optional[str]]]] = {k: [] for k in REVIEW_STATUSES} reviewers: set[str] = set() first_review: Optional[int] = None for note in pages(f"{base}/{int(iid)}/notes", {"sort": "asc", "order_by": "created_at"}): @@ -1325,20 +1363,24 @@ def details(mr: Dict[str, Any]) -> Dict[str, Any]: continue # comments after the merge are not a review body = note.get("body") or "" if note.get("system") and GITLAB_PUSH_NOTE.match(body): - events.append((t, "push", None)) + pushes.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): + kind = reviewer_kind(me, a.get("username"), _is_bot(a.get("username"), "Bot" if a.get("bot") else None)) + events[kind].append((t, "review", None)) + if kind != "others": 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]: + if len(events["others"]) % 100 == 0 and count_review_cycles(pushes + events["others"])[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["review_cycles"], out["cycles_capped"] = count_review_cycles(pushes + events["others"]) + out["self_review_cycles"], out["self_cycles_capped"] = count_review_cycles(pushes + events["self"]) + out["bot_review_cycles"], out["bot_cycles_capped"] = count_review_cycles(pushes + events["bot"]) + out["review_status"] = review_status(k for k, v in events.items() if v) out["reviewers"] = len(reviewers) except (ApiError, ValueError, KeyError, TypeError, AttributeError) as e: out["review_error"] = str(e) @@ -1367,9 +1409,14 @@ def details(mr: Dict[str, Any]) -> Dict[str, Any]: "reviewed": (ex["first_review"] is not None) if (state == "merged" and review_known) else None, # 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, + "self_review_cycles": ex.get("self_review_cycles") if review_known else None, + "bot_review_cycles": ex.get("bot_review_cycles") if review_known else None, + "review_status": ex.get("review_status") if (state == "merged" and review_known) else 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 []), + + (["review_cycles"] if ex["cycles_capped"] else []) + + (["self_review_cycles"] if ex.get("self_cycles_capped") else []) + + (["bot_review_cycles"] if ex.get("bot_cycles_capped") else []), "squash_sha": mr.get("squash_commit_sha"), "local": None, "commits_refused": commits_refused, }) return result @@ -1401,7 +1448,8 @@ def add(name: str, pts: int, detail: str) -> None: if pr.get("tests") is False and (pr.get("code_lines") or 0) >= RISK["no_tests_min_code_lines"]: add("no tests", RISK["no_tests"], f"{pr['code_lines']} code lines, no test files") if pr.get("reviewed") is False: - add("unreviewed", RISK["unreviewed"], "merged with no review from another person") + only = {"self": " (self-review only)", "bot": " (bot review only)"}.get(pr.get("review_status") or "", "") + add("unreviewed", RISK["unreviewed"], "merged with no review from another person" + only) score = min(RISK["cap"], sum(f["points"] for f in factors)) level = tier(score, [[limit - 1 if limit else None, name] for limit, name in RISK["levels"]]) return score, level, factors @@ -1494,6 +1542,8 @@ def build_records(prs: List[PR], ctx: Dict[str, Any]) -> List[Record]: # 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"), + "self_review_cycles": pr.get("self_review_cycles"), "bot_review_cycles": pr.get("bot_review_cycles"), + "review_status": pr.get("review_status"), } sensitive = tests = code_lines = None if c is not None: @@ -1622,7 +1672,8 @@ 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", "review_cycles", "changes_requested", "reviewers", "source"] + "restore", "review_cycles", "changes_requested", "reviewers", "source", + "review_status", "self_review_cycles", "bot_review_cycles"] def write(f: IO[str]) -> None: """Write the header and one guarded row per record to f.""" diff --git a/repo-stats/template.html b/repo-stats/template.html index 9e33d96..4c13bc4 100644 --- a/repo-stats/template.html +++ b/repo-stats/template.html @@ -662,6 +662,15 @@

Repository stats

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)) }; } +/** Review status of a merged PR, strongest first (REVIEW_STATUSES in repo_stats.py): [key, label, color var, meaning]. */ +const REVIEW_CATS = [ + ["others", "Reviewed (by others)", "--c1", "a review from a person other than the author"], + ["self", "Reviewed (self)", "--c3", "reviews only from the author's own account, including agents acting with the author's credentials"], + ["bot", "Reviewed (bot)", "--c7", "reviews only from bot accounts"], + ["none", "Unreviewed", "--st-crit", "no review before merge"], +]; +/** A PR's review status; "others" whenever it has a review cycle by others. */ +const statusOf = (p) => p.review_cycles > 0 ? "others" : (p.review_status && p.review_status !== "others" ? p.review_status : "none"); /* ------------------------------------------------------------------ sections */ const METRICS = [ @@ -694,7 +703,7 @@

Repository stats

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("Merged without review", cyc.known.length ? fmtInt(cyc.unreviewed.length) : "–", cyc.known.length ? `${fmtPct(cyc.unreviewed.length / cyc.known.length)} of merged PRs · ${fmtInt(cyc.unreviewed.filter((p) => statusOf(p) === "self").length)} self-reviewed · ${fmtInt(cyc.unreviewed.filter((p) => statusOf(p) === "bot").length)} bot only` : 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"), @@ -928,7 +937,7 @@

Repository stats

} 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."); + sectionHead(app, "reviews", "Review cycles", "How many rounds of review each merged PR went through. A cycle starts when a reviewer looks at a version of the code that no earlier review of theirs covered, so a batch of comments, a run of single comments or replies, and several reviews of one version all count once. Cycles by others, self-review cycles and bot cycles are counted separately."); const grid = h("div", { class: "grid" }); app.append(grid); const cyc = cycleSplit(sel.merged); @@ -941,35 +950,46 @@

Repository stats

} const lowerBound = inferredShare(prs, "review_cycles"); const t = card(grid, "Review cycle statistics", { wide: true }); + const ownCycles = (key) => prs.filter((p) => p[key] > 0).map((p) => p[key]); 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: "review_cycles", label: "Review cycles by others, PRs reviewed by others only", st: cyc.stReviewed, fmt: fmtNum }, + { key: "review_cycles", label: "Review cycles by others, other PRs counted as 0", st: cyc.stAll, fmt: fmtNum }, + { key: "self_review_cycles", label: "Self-review cycles, self-reviewed PRs only", st: stats(ownCycles("self_review_cycles")), fmt: fmtNum }, + { key: "bot_review_cycles", label: "Bot review cycles, bot-reviewed PRs only", st: stats(ownCycles("bot_review_cycles")), 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 }, + { key: "reviewers", label: "Reviewers per PR (others)", 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 lb = r.key.endsWith("review_cycles") ? inferredShare(prs, r.key) : null; + return lb ? fmtPct(lb) + " 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.` + const byStatus = groupBy(prs, statusOf); + const n = (k) => (byStatus.get(k) || []).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: ${fmtInt(n("self"))} self-reviewed, ${fmtInt(n("bot"))} reviewed only by bots and ${fmtInt(n("none"))} with no review at all.` + (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.` }); + const bc = card(grid, "PRs by number of review cycles by others", { note: `The last bar is ${top} or more cycles. PRs with 0 cycles by others are split by who else reviewed them.` }); 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) }], + series: REVIEW_CATS.map(([k, label, color]) => ({ name: label, color: css(color), + vals: B.map((b) => k === "others" ? (b === 0 ? 0 : cyc.reviewed.filter((p) => bucketOf(p.review_cycles) === b).length) : (b === 0 ? n(k) : 0)) })), 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 uc = card(grid, "Review status by month", { note: "Merged PRs with review data, stacked. Each PR counts once, under the strongest review it got: " + REVIEW_CATS.map(([, l, , d]) => `${l}, ${d}`).join("; ") + "." }); 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" }); + series: REVIEW_CATS.map(([k, label, color]) => ({ name: label, color: css(color), vals: months.map((m) => (byStatus.get(k) || []).filter((p) => bucketStart(p.merged, "month") === m).length) })), + stacked: true, label: "Review status by month", table: uc.table, catName: "Month" }); + + const kc = card(grid, "Review cycles by reviewer", { wide: true, note: `PRs by number of cycles from each kind of reviewer. A PR can appear in more than one series, for example with 1 bot cycle, 2 self-review cycles and 1 cycle by others. The last bar is ${top} or more.` }); + const kinds = [["review_cycles", ...REVIEW_CATS[0].slice(1, 3)], ["self_review_cycles", ...REVIEW_CATS[1].slice(1, 3)], ["bot_review_cycles", ...REVIEW_CATS[2].slice(1, 3)]]; + barChart(kc.body, { cats: B.filter((b) => b > 0).map((b) => ({ short: b === top ? b + "+" : String(b), long: (b === top ? b + " or more" : String(b)) + (b === 1 ? " cycle" : " cycles") })), + series: kinds.map(([key, label, color]) => ({ name: label, color: css(color), vals: B.filter((b) => b > 0).map((b) => prs.filter((p) => p[key] > 0 && bucketOf(p[key]) === b).length) })), + label: "PRs by number of review cycles, by reviewer", table: kc.table, catName: "Review cycles" }); 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")); @@ -1066,12 +1086,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." }); + const rv = card(grid, "Review cycles", { wide: true, note: "API data only. Reviews 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, "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. A batched review, a run of single comments, replies and several reviews of one version all fall in the same cycle."), + h("dt", null, "Who reviewed"), h("dd", null, "Each review is classified by its account. The PR author's own account is a self-review, including agents that post with the author's credentials, which the API cannot tell apart from the author. A bot account (a GitHub App, or a login ending in [bot] or -bot) is a bot review. Anyone else is a review by others. Cycles are counted separately for each; the headline cycle count, pickup time and review time use reviews by others only."), + h("dt", null, "Review status"), h("dd", null, "Each merged PR counts once, under the strongest review it got: by others, then self, then bot, then unreviewed."), + 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. Every inline comment or reply that is not part of a batched review is its own review object, so it counts as review activity."), + h("dt", null, "GitLab"), h("dd", null, "From the merge request's notes: comments and approvals 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 by others. Statistics are shown both without them and with them counted as 0, and their number is shown on its own, split into self-reviewed, bot-reviewed and not reviewed at all."), 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." }); @@ -1083,7 +1105,7 @@

Repository stats

h("dt", null, "Breaking change"), h("dd", null, `+${R.breaking} when the title has ! after the type or says BREAKING CHANGE.`), h("dt", null, "Sensitive paths"), h("dd", null, `+${R.sensitive_paths} when any changed path looks like migrations, auth, security, payments, infra, CI or container files. Needs the merge commit locally. `, h("details", null, h("summary", null, "Show the pattern"), h("code", null, "/" + META.heuristics.sensitive + "/i"))), h("dt", null, "No tests"), h("dd", null, `+${R.no_tests} when ${R.no_tests_min_code_lines}+ lines of non-test, non-doc source changed and no test file did.`), - h("dt", null, "Unreviewed"), h("dd", null, `+${R.unreviewed} when merged with no review from anyone other than the author. API data only.`), + h("dt", null, "Unreviewed"), h("dd", null, `+${R.unreviewed} when merged with no review from anyone other than the author. Self-reviews and bot reviews do not clear it. API data only.`), h("dt", null, "Levels"), h("dd", null, R.levels.map(([lim, n], i) => `${n} ${lim == null ? "≥ " + R.levels[i - 1][0] : "< " + lim}`).join(", ")))); } diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index e35e067..f0869c5 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -2811,6 +2811,56 @@ def test_github_truncated_reviews_are_a_lower_bound(self) -> None: p = self._gh([("bob", "User", "APPROVED", BASE + self.H, "c1")], review_total=150) self.assertIn("review_cycles", p["inferred"]) + # -- self and bot reviews + + def test_github_review_status(self) -> None: + """A merged PR takes its strongest pre-merge review: others > self > bot > none.""" + b, h = BASE, self.H + mine, bot, bob = ("alice", "User", "COMMENTED"), ("ci[bot]", "Bot", "COMMENTED"), ("bob", "User", "APPROVED") + self.assertEqual(self._gh([(*bot, b + h, "c1"), (*mine, b + 2 * h, "c1"), (*bob, b + 3 * h, "c1")])["review_status"], "others") + self.assertEqual(self._gh([(*bot, b + h, "c1"), (*mine, b + 2 * h, "c1")])["review_status"], "self") + self.assertEqual(self._gh([(*bot, b + h, "c1"), (*bob, b + 30 * h, "c1")])["review_status"], "bot") # bob after merge + self.assertEqual(self._gh([("carol", "User", "PENDING", b + h, "c1")])["review_status"], "none") + self.assertIsNone(rs.github_pr(ms.gh_node(1, "feat: x", BASE, reviews=[(*bob, b + h, "c1")]))["review_status"]) # open + + def test_github_self_and_bot_cycles_group_by_version(self) -> None: + """A batch, single comments and replies on one version are one cycle per reviewer kind.""" + b, h = BASE, self.H + p = self._gh([("ci[bot]", "Bot", "COMMENTED", b + h, "c1"), # agent review of v1 + ("alice", "User", "COMMENTED", b + h + 60, "c1"), # author replies, one by one, + ("alice", "User", "COMMENTED", b + h + 120, "c1"), # to the bot's threads + ("alice", "User", "COMMENTED", b + 2 * h, "c2"), # self-review of v2 ... + ("alice", "User", "COMMENTED", b + 2 * h + 60, "c2"), # ... in several comments + ("ci[bot]", "Bot", "COMMENTED", b + 3 * h, "c3"), # agent re-review of v3 + ("ci[bot]", "Bot", "COMMENTED", b + 3 * h + 60, "c3")]) + self.assertEqual((p["review_cycles"], p["self_review_cycles"], p["bot_review_cycles"]), (0, 2, 2)) + self.assertEqual((p["review_status"], p["reviewed"], p["first_review"], p["reviewers"]), ("self", False, None, 0)) + self.assertEqual(p["inferred"], []) + + def test_self_review_does_not_clear_unreviewed_risk(self) -> None: + """Self and bot reviews keep the unreviewed risk factor, and its detail says why.""" + _, _, factors = rs.risk_for({"type": "fix", "breaking": False, "reviewed": False, "review_status": "self"}) + self.assertEqual([f["detail"] for f in factors if f["name"] == "unreviewed"], + ["merged with no review from another person (self-review only)"]) + _, _, factors = rs.risk_for({"type": "fix", "breaking": False, "reviewed": False, "review_status": "bot"}) + self.assertIn("(bot review only)", [f["detail"] for f in factors if f["name"] == "unreviewed"][0]) + + def test_gitlab_self_and_bot_cycles(self) -> None: + """GitLab author notes and self-approvals are self-reviews and bot notes are bot reviews, split by pushes.""" + b, h = BASE, self.H + p = self._gl([ms.gl_note("ci-bot", b + h, bot=True), ms.gl_note("alice", b + h + 60), ms.gl_note("alice", b + h + 90), + ms.gl_push("alice", b + 2 * h), ms.gl_note("ci-bot", b + 3 * h, bot=True), + ms.gl_approval("alice", b + 3 * h + 60)]) + self.assertEqual((p["review_cycles"], p["self_review_cycles"], p["bot_review_cycles"]), (0, 2, 2)) + self.assertEqual((p["review_status"], p["reviewed"]), ("self", False)) + p = self._gl([ms.gl_note("ci-bot", b + h, bot=True)]) + self.assertEqual((p["review_status"], p["bot_review_cycles"], p["self_review_cycles"]), ("bot", 1, 0)) + p = self._gl([ms.gl_note("alice", b + h), ms.gl_note("bob", b + 2 * h)]) + self.assertEqual((p["review_status"], p["review_cycles"], p["self_review_cycles"]), ("others", 1, 1)) + p = self._gl([ms.gl_note("bob", BASE + self.H)], want_reviews=False) + self.assertIsNone(p["review_status"]) + self.assertIsNone(p["self_review_cycles"]) + 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) @@ -2825,6 +2875,9 @@ def test_github_records_end_to_end(self) -> None: 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[1]["review_status"], prs[1]["self_review_cycles"], prs[1]["bot_review_cycles"]), ("others", 1, 1)) + self.assertEqual((prs[10]["review_status"], prs[10]["self_review_cycles"]), ("self", 1)) + self.assertIsNone(prs[6]["review_status"]) self.assertEqual(prs[3]["changes_requested"], 1) self.assertEqual(prs[10]["review_cycles"], 0) self.assertFalse(prs[10]["reviewed"]) diff --git a/repo-stats/tests/test_ui.py b/repo-stats/tests/test_ui.py index b40636c..45809a7 100644 --- a/repo-stats/tests/test_ui.py +++ b/repo-stats/tests/test_ui.py @@ -253,6 +253,10 @@ def build_api_data() -> dict[str, Any]: 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}")) + elif i % 3 == 0: + reviews = [(author, atype, "COMMENTED", merged - 120, "s1"), (author, atype, "COMMENTED", merged - 60, "s2")] # self only + elif i % 3 == 1: + reviews = [("helper[bot]", "Bot", "COMMENTED", merged - 60, "b1")] # bot only title = p["title"] if i == 7: title = "feat!: " + EVIL @@ -683,7 +687,8 @@ def test_review_cycle_kpis_and_table_match_python(self) -> None: 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)): + for label, vals in (("Review cycles by others, PRs reviewed by others only", reviewed), + ("Review cycles by others, other PRs counted as 0", known)): want = cast(dict, stat_row(vals)) for i, col in enumerate(COLS): with self.subTest(label, col=col): From 9d5ef5da8ca2fb262b364738c0bfae768ecb0171 Mon Sep 17 00:00:00 2001 From: Husam Date: Thu, 29 Oct 2026 21:14:23 +0000 Subject: [PATCH 2/2] fix(repo-stats): clamp the dashboard date range to --since/--until Lines of code keep the whole history so totals stay correct, which made the header and the 'All time' range start at the first commit even with --since. Record the window in meta and clamp the dashboard's range to it. --- repo-stats/repo_stats.py | 3 +++ repo-stats/template.html | 4 ++++ repo-stats/tests/test_repo_stats.py | 8 ++++++++ 3 files changed, 15 insertions(+) diff --git a/repo-stats/repo_stats.py b/repo-stats/repo_stats.py index a0f88ca..7e9a750 100755 --- a/repo-stats/repo_stats.py +++ b/repo-stats/repo_stats.py @@ -1916,6 +1916,9 @@ def collect(args: argparse.Namespace, environ: Optional[Mapping[str, str]] = Non name = args.title or (parsed[1].rsplit("/", 1)[-1] if parsed else os.path.basename(repo)) meta = { "name": name, "branch": branch, "generated": int(time.time()), "version": __version__, + # The --since / --until window (Unix seconds, until exclusive), or None. Lines of code keep the whole + # history so the totals are right, so the dashboard clamps its date range to this window. + "since": since, "until": until, "mode": mode, "provider": provider if mode == "api" else None, "warnings": warnings, "commits": len(graph), "direct_commits": direct, "sync_merges": sync, "deploy_source": args.deploy_source, "tag_pattern": args.tag_pattern, diff --git a/repo-stats/template.html b/repo-stats/template.html index 4c13bc4..e6d2d0c 100644 --- a/repo-stats/template.html +++ b/repo-stats/template.html @@ -236,6 +236,10 @@

Repository stats

let DATA_LO = Infinity, DATA_HI = -Infinity; for (const t of allTimes) { if (t < DATA_LO) DATA_LO = t; if (t > DATA_HI) DATA_HI = t; } // no Math.min(...big array) if (!isFinite(DATA_LO)) { DATA_LO = DATA_HI = Math.floor(Date.now() / 1000); } +// With --since / --until, lines of code still cover the whole history (so totals are right): clamp to the window. +if (META.since != null) DATA_LO = Math.max(DATA_LO, META.since); +if (META.until != null) DATA_HI = Math.min(DATA_HI, META.until - 1); +if (DATA_LO > DATA_HI) DATA_LO = DATA_HI; const TYPE_GROUPS = ["feat", "fix", "refactor", "docs", "test", "chore", "perf", "other"]; const GROUP_OF = { style: "chore", build: "chore", ci: "chore", revert: "other" }; const groupOf = (t) => TYPE_GROUPS.includes(t) ? t : (GROUP_OF[t] || "other"); diff --git a/repo-stats/tests/test_repo_stats.py b/repo-stats/tests/test_repo_stats.py index f0869c5..47e9b3d 100644 --- a/repo-stats/tests/test_repo_stats.py +++ b/repo-stats/tests/test_repo_stats.py @@ -544,6 +544,14 @@ def test_since_until(self) -> None: self.assertEqual([p["number"] for p in d["prs"]], [1, 2]) self.assertEqual([x["name"] for x in d["deploys"]], ["v1.0.0"]) + def test_window_is_recorded_in_meta(self) -> None: + """The --since / --until window is in meta, so the dashboard clamps its date range to it.""" + d, _ = collect(merge_repo(), "--since", "2022-01-05", "--until", "2022-01-06") + self.assertEqual((d["meta"]["since"], d["meta"]["until"]), (T0 + 4 * DAY, T0 + 6 * DAY)) + self.assertLess(d["loc"]["days"][0][0], d["meta"]["since"]) # lines of code still cover the whole history + d, _ = collect(merge_repo()) + self.assertEqual((d["meta"]["since"], d["meta"]["until"]), (None, None)) + def test_until_is_inclusive_of_that_day_only(self) -> None: """--until includes its whole day and nothing after it.""" r = Repo()