From 057b8c14fda5487f8e984f3797202416ad5ff952 Mon Sep 17 00:00:00 2001 From: Sahib Yar Date: Tue, 1 Dec 2026 00:19:43 +0500 Subject: [PATCH 1/3] refactor: read and validate one export page in a shared helper Move the export request, media-type and row-version checks and the horizon and cursor headers out of `proofline export` into export_page, so another command can follow the continuation with the same checks. `proofline export` prints exactly what it printed before. --- src/tools.rs | 116 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 76 insertions(+), 40 deletions(-) diff --git a/src/tools.rs b/src/tools.rs index a3602f7..52b38ec 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -26,7 +26,7 @@ pub(crate) struct HistoryArgs { } #[derive(Debug, Clone, Copy, ValueEnum)] -enum Dataset { +pub(crate) enum Dataset { Reviews, #[value(name = "finding_outcomes")] FindingOutcomes, @@ -58,7 +58,7 @@ const fn versions(dataset: Dataset) -> &'static [&'static str] { } #[derive(Debug, Clone, Copy, ValueEnum)] -enum Format { +pub(crate) enum Format { Csv, Ndjson, } @@ -121,59 +121,95 @@ pub(crate) async fn export(api: &Api, args: &ExportArgs) -> anyhow::Result, + /// The frozen horizon, the same on every page of one export. + pub(crate) settled_until: String, + /// The continuation, absent on the last page. + pub(crate) next_cursor: Option, +} + +/// Reads one page of `dataset` for the window `(from, to)` and refuses a +/// media type or row version this CLI does not know. +pub(crate) async fn export_page( + api: &Api, + dataset: Dataset, + format: Format, + (from, to): (&str, &str), + cursor: Option<&str>, + group_by: Option<&str>, +) -> anyhow::Result { + let (format, accept) = match format { Format::Csv => ("csv", "text/csv"), Format::Ndjson => ("ndjson", "application/x-ndjson"), }; let mut query = vec![ - ("from", args.from.clone()), - ("to", args.to.clone()), + ("from", from.to_owned()), + ("to", to.to_owned()), ("format", format.to_owned()), ]; - if let Some(cursor) = &args.cursor { - query.push(("cursor", cursor.clone())); + if let Some(cursor) = cursor { + query.push(("cursor", cursor.to_owned())); } - if let Some(group) = &args.group_by { - query.push(("group_by", group.clone())); + if let Some(group) = group_by { + query.push(("group_by", group.to_owned())); } - let reply = api.export(args.dataset.name(), &query, accept).await?; - let content_type = reply - .headers - .get("content-type") - .and_then(|v| v.to_str().ok()) - .unwrap_or_default(); + let reply = api.export(dataset.name(), &query, accept).await?; + let header = |name: &str| reply.headers.get(name).and_then(|v| v.to_str().ok()); + let content_type = header("content-type").unwrap_or_default(); if content_type.split(';').next().map(str::trim) != Some(accept) - || !reply - .headers - .get("x-proofline-export-version") - .and_then(|v| v.to_str().ok()) - .is_some_and(|version| versions(args.dataset).contains(&version)) + || !header("x-proofline-export-version") + .is_some_and(|version| versions(dataset).contains(&version)) { bail!("the server returned an unsupported export format or version"); } - let horizon = reply + let settled_until = reply .headers .get("x-proofline-export-settled-until") .context("the export has no settled horizon")? - .to_str()?; - let body = std::str::from_utf8(&reply.body).context("the export is not UTF-8")?; - let stdout = std::io::stdout(); - if stdout.is_terminal() { - write!(stdout.lock(), "{}", crate::text::terminal_safe(body))?; - } else { - stdout.lock().write_all(&reply.body)?; - } - say(&format!( - "settled-until: {}", - crate::text::terminal_safe(horizon) - )); - if let Some(cursor) = reply.headers.get("x-proofline-export-next-cursor") { - say(&format!( - "next-cursor: {}", - crate::text::terminal_safe(cursor.to_str()?) - )); - } - Ok(Verdict::Done) + .to_str()? + .to_owned(); + let next_cursor = reply + .headers + .get("x-proofline-export-next-cursor") + .map(|cursor| cursor.to_str().map(str::to_owned)) + .transpose()?; + Ok(ExportPage { + body: reply.body, + settled_until, + next_cursor, + }) } #[derive(Debug, Args)] From 377cea528585592ef7cf2a6969a701ca0a3f2af1 Mon Sep 17 00:00:00 2001 From: Sahib Yar Date: Tue, 1 Dec 2026 00:19:43 +0500 Subject: [PATCH 2/3] feat: add proofline stats for review turnaround per repository `proofline stats --from FROM --to TO` reads every page of the reviews export for one window and prints, per repository and in total, the reviews by status and the nearest-rank p50, p90, p99 and longest time from creation to completion of the completed reviews. --json prints the same report with times in seconds. The report is printed only after the last page. A page that fails, a settled horizon that changes between pages or a continuation cursor that repeats exits 1 with no partial report, and the walk is bounded at 10,000 pages. --- README.md | 2 + src/lib.rs | 12 ++ src/stats.rs | 421 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/stats.rs | 308 ++++++++++++++++++++++++++++++++++++ 4 files changed, 743 insertions(+) create mode 100644 src/stats.rs create mode 100644 tests/stats.rs diff --git a/README.md b/README.md index 6a124c3..64990c5 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,8 @@ The command sends the exact 40-character lowercase SHA supplied by CI and does n `proofline export reviews --from 2026-10-01T00:00:00Z --to 2026-10-25T00:00:00Z --format csv` writes one export page to stdout and requires `analytics:read`. The datasets are `reviews`, `findings`, `finding_outcomes`, `finding_validations`, and `spend`. The default format is NDJSON, while CSV repeats its header on every page. The settled horizon and optional next cursor go to stderr. Repeat with `--cursor` and the same window and `--group-by` to continue. A failed page exits nonzero; never treat partial output from several invocations as a complete export. +`proofline stats --from 2026-10-01T00:00:00Z --to 2026-10-25T00:00:00Z` answers how long reviews take and how often they finish, per repository. It reads every page of the `reviews` export for the window, so it needs `analytics:read` and the same window of at most 31 days, then prints one row per repository and an `all` row: the reviews counted by status (`completed`, `incomplete`, `failed`, `unfinished` for pending or running, and `other`) and the p50, p90, p99 and longest time from creation to completion of the completed reviews, by the nearest-rank method. A review that is incomplete, failed or stopped gave no usable result, so it has no turnaround. `--json` prints the same report with times in seconds. The settled horizon and page count go to stderr. The report appears only after the last page: a failed page, a horizon that changes between pages or a cursor that repeats exits 1 and prints no partial report. + ## Development and publishing Build from source with `cargo build --locked --release`. `rustup` installs the pinned Rust toolchain. Run `cargo fmt --check`, `cargo clippy --locked --all-targets -- -D warnings`, `cargo test --locked`, and `cargo deny check` before submitting a pull request. Adding an API operation exposes a CLI command only when a command in `src/` declares and uses it. diff --git a/src/lib.rs b/src/lib.rs index 8bf7a9e..a8c30a2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,6 +24,7 @@ mod sarif; mod scan; mod setup; mod severity; +mod stats; pub mod text; mod tls; pub mod update; @@ -140,6 +141,13 @@ enum Command { FixPrompt { finding_id: Uuid }, /// Export one page of analytics as CSV or NDJSON. Export(tools::ExportArgs), + /// Report each repository's review outcomes and turnaround over a window. + /// + /// Reads every page of the `reviews` export for the window, then prints + /// per repository the reviews by status and the p50, p90, p99 and + /// longest time from creation to completion of its completed reviews. + /// It needs `analytics:read` and prints nothing unless every page reads. + Stats(stats::StatsArgs), /// Print a shell completion script to standard output. /// /// For example, add `source <(proofline completions zsh)` to `~/.zshrc`, @@ -619,6 +627,10 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let api = connect(Http::new(origin)?, token, cli.org).await?; + stats::run(&api, &args).await + } Command::Findings(args) => { if let Some(head) = &args.selector.head { git::commit_sha(head)?; diff --git a/src/stats.rs b/src/stats.rs new file mode 100644 index 0000000..63ed082 --- /dev/null +++ b/src/stats.rs @@ -0,0 +1,421 @@ +//! Review outcomes and turnaround per repository, read from every page of +//! one window of the `reviews` export. +//! +//! The export is the only API that lists reviews across repositories with +//! their creation and completion times, but it answers one page of at most +//! 5,000 rows per request. This command follows the continuation to the end, +//! keeps one frozen horizon for the whole window, and reports only after the +//! last page, so a partial window is never shown as a complete one. + +use std::collections::{BTreeMap, HashSet}; +use std::io::Write as _; + +use anyhow::{Context as _, bail}; +use clap::Args; +use serde::{Deserialize, Serialize}; + +use crate::github_actions::unix_seconds; +use crate::tools::{Dataset, Format, export_page}; +use crate::{Verdict, api::Api, say}; + +/// The most pages one window may take: 50 million reviews at 5,000 a page. +const MAX_PAGES: usize = 10_000; +const NO_REPOSITORY: &str = "(no repository)"; +const ALL: &str = "all"; + +#[derive(Debug, Args)] +pub(crate) struct StatsArgs { + /// Inclusive RFC3339 start of a window of at most 31 days. + #[arg(long)] + from: String, + /// Exclusive RFC3339 end of the window. + #[arg(long)] + to: String, + /// Print JSON instead of a table. + #[arg(long)] + json: bool, +} + +/// The columns of a `reviews` export row that the report reads. +#[derive(Debug, Deserialize)] +struct Row { + status: String, + created_at: String, + completed_at: Option, + repository_full_name: Option, + repository_id: Option, +} + +impl Row { + fn repository(&self) -> &str { + self.repository_full_name + .as_deref() + .or(self.repository_id.as_deref()) + .unwrap_or(NO_REPOSITORY) + } + + /// Seconds from creation to completion of a `COMPLETED` review. Other + /// statuses gave the author no usable result, so they have no turnaround. + fn turnaround(&self) -> anyhow::Result> { + let Some(completed_at) = self + .completed_at + .as_deref() + .filter(|_| self.status == "COMPLETED") + else { + return Ok(None); + }; + let seconds = |time: &str| { + unix_seconds(time).with_context(|| { + format!( + "the export has a review time this CLI cannot read: {}", + crate::text::one_line(time) + ) + }) + }; + let elapsed = seconds(completed_at)? - seconds(&self.created_at)?; + // A completion recorded before its creation is clock skew, not a + // negative wait. + Ok(Some(u64::try_from(elapsed).unwrap_or(0))) + } +} + +/// Counts by status and the turnaround of each completed review. +#[derive(Debug, Default)] +struct Group { + reviews: u64, + completed: u64, + incomplete: u64, + failed: u64, + unfinished: u64, + other: u64, + seconds: Vec, +} + +impl Group { + fn add(&mut self, status: &str, turnaround: Option) { + self.reviews += 1; + let count = match status { + "COMPLETED" => &mut self.completed, + "INCOMPLETE" => &mut self.incomplete, + "FAILED" => &mut self.failed, + "PENDING" | "RUNNING" => &mut self.unfinished, + // SUPERSEDED, STOPPED, EXCLUDED and any status newer than this CLI. + _ => &mut self.other, + }; + *count += 1; + self.seconds.extend(turnaround); + } + + fn summary(mut self, repository: String) -> Summary { + self.seconds.sort_unstable(); + Summary { + repository, + reviews: self.reviews, + completed: self.completed, + incomplete: self.incomplete, + failed: self.failed, + unfinished: self.unfinished, + other: self.other, + seconds_to_complete: Turnaround::of(&self.seconds), + } + } +} + +#[derive(Debug, Serialize)] +struct Turnaround { + p50: u64, + p90: u64, + p99: u64, + max: u64, +} + +impl Turnaround { + /// Nearest-rank percentiles of sorted durations, `None` when empty. + fn of(sorted: &[u64]) -> Option { + let max = *sorted.last()?; + let rank = |percent: usize| { + let index = (percent * sorted.len()).div_ceil(100).max(1) - 1; + sorted.get(index).copied().unwrap_or(max) + }; + Some(Self { + p50: rank(50), + p90: rank(90), + p99: rank(99), + max, + }) + } +} + +#[derive(Debug, Serialize)] +struct Summary { + repository: String, + reviews: u64, + completed: u64, + incomplete: u64, + failed: u64, + unfinished: u64, + other: u64, + seconds_to_complete: Option, +} + +#[derive(Debug, Serialize)] +struct Report<'a> { + from: &'a str, + to: &'a str, + settled_until: String, + pages: usize, + repositories: Vec, + all: Summary, +} + +pub(crate) async fn run(api: &Api, args: &StatsArgs) -> anyhow::Result { + let mut repositories: BTreeMap = BTreeMap::new(); + let mut all = Group::default(); + let mut horizon: Option = None; + let mut cursors = HashSet::new(); + let mut cursor: Option = None; + for pages in 1..=MAX_PAGES { + let page = export_page( + api, + Dataset::Reviews, + Format::Ndjson, + (&args.from, &args.to), + cursor.as_deref(), + None, + ) + .await?; + let settled_until = horizon.get_or_insert_with(|| page.settled_until.clone()); + if *settled_until != page.settled_until { + bail!( + "the export's settled horizon changed from {} to {} between pages, so its pages do not describe one window", + crate::text::one_line(settled_until), + crate::text::one_line(&page.settled_until) + ); + } + for line in page.body.split(|byte| *byte == b'\n') { + if line.iter().all(u8::is_ascii_whitespace) { + continue; + } + let row: Row = serde_json::from_slice(line) + .context("the export has a reviews row this CLI cannot read")?; + let turnaround = row.turnaround()?; + all.add(&row.status, turnaround); + repositories + .entry(row.repository().to_owned()) + .or_default() + .add(&row.status, turnaround); + } + let Some(next) = page.next_cursor else { + let report = Report { + from: &args.from, + to: &args.to, + settled_until: page.settled_until, + pages, + repositories: repositories + .into_iter() + .map(|(repository, group)| group.summary(repository)) + .collect(), + all: all.summary(ALL.to_owned()), + }; + return print(&report, args.json); + }; + if !cursors.insert(next.clone()) { + bail!("the export repeated a continuation cursor, so it would never end"); + } + cursor = Some(next); + } + bail!("the export did not end within {MAX_PAGES} pages") +} + +fn print(report: &Report<'_>, json: bool) -> anyhow::Result { + say(&format!( + "settled-until: {} ({} pages)", + crate::text::one_line(&report.settled_until), + report.pages + )); + let mut stdout = std::io::stdout().lock(); + if json { + writeln!(stdout, "{}", serde_json::to_string_pretty(report)?)?; + return Ok(Verdict::Done); + } + let names: Vec = report + .repositories + .iter() + .chain([&report.all]) + .map(|summary| crate::text::one_line(&summary.repository)) + .collect(); + let width = names + .iter() + .map(|name| name.chars().count()) + .chain(["repository".len()]) + .max() + .unwrap_or_default(); + writeln!( + stdout, + "{:7} {:>9} {:>10} {:>6} {:>10} {:>5} {:>6} {:>6} {:>6} {:>6}", + "repository", + "reviews", + "completed", + "incomplete", + "failed", + "unfinished", + "other", + "p50", + "p90", + "p99", + "max", + )?; + for (name, summary) in names + .iter() + .zip(report.repositories.iter().chain([&report.all])) + { + let [p50, p90, p99, max] = summary.seconds_to_complete.as_ref().map_or_else( + || { + [ + "-".to_owned(), + "-".to_owned(), + "-".to_owned(), + "-".to_owned(), + ] + }, + |turnaround| { + [ + turnaround.p50, + turnaround.p90, + turnaround.p99, + turnaround.max, + ] + .map(duration) + }, + ); + writeln!( + stdout, + "{name:7} {:>9} {:>10} {:>6} {:>10} {:>5} {p50:>6} {p90:>6} {p99:>6} {max:>6}", + summary.reviews, + summary.completed, + summary.incomplete, + summary.failed, + summary.unfinished, + summary.other, + )?; + } + Ok(Verdict::Done) +} + +/// `45s`, `4m05s` or `1h02m`: precise enough to compare, short enough for a column. +fn duration(seconds: u64) -> String { + match seconds { + 0..60 => format!("{seconds}s"), + 60..3_600 => format!("{}m{:02}s", seconds / 60, seconds % 60), + _ => format!("{}h{:02}m", seconds / 3_600, seconds % 3_600 / 60), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nearest_rank_percentiles_pick_an_observed_duration() { + let sorted: Vec = (1..=100).collect(); + let turnaround = Turnaround::of(&sorted).unwrap(); + assert_eq!( + [ + turnaround.p50, + turnaround.p90, + turnaround.p99, + turnaround.max + ], + [50, 90, 99, 100] + ); + + let single = Turnaround::of(&[42]).unwrap(); + assert_eq!([single.p50, single.p90, single.p99, single.max], [42; 4]); + + assert!(Turnaround::of(&[]).is_none()); + } + + #[test] + fn durations_stay_short_at_every_scale() { + for (seconds, shown) in [ + (0, "0s"), + (59, "59s"), + (60, "1m00s"), + (245, "4m05s"), + (3_599, "59m59s"), + (3_600, "1h00m"), + (90_061, "25h01m"), + ] { + assert_eq!(duration(seconds), shown); + } + } + + fn row(status: &str, created_at: &str, completed_at: Option<&str>) -> Row { + Row { + status: status.to_owned(), + created_at: created_at.to_owned(), + completed_at: completed_at.map(str::to_owned), + repository_full_name: None, + repository_id: None, + } + } + + #[test] + fn only_a_completed_review_has_a_turnaround() { + let created = "2026-10-05T10:00:00Z"; + let finished = Some("2026-10-05T10:04:05.250Z"); + assert_eq!( + row("COMPLETED", created, finished).turnaround().unwrap(), + Some(245) + ); + for status in ["FAILED", "INCOMPLETE", "STOPPED", "SUPERSEDED"] { + assert_eq!(row(status, created, finished).turnaround().unwrap(), None); + } + assert_eq!(row("COMPLETED", created, None).turnaround().unwrap(), None); + // Clock skew never yields a negative or wrapped wait. + let early = Some("2026-10-05T09:59:00Z"); + assert_eq!( + row("COMPLETED", created, early).turnaround().unwrap(), + Some(0) + ); + } + + #[test] + fn an_unreadable_time_is_refused_rather_than_guessed() { + let error = row("COMPLETED", "yesterday", Some("2026-10-05T10:00:00Z")) + .turnaround() + .unwrap_err(); + assert!( + error.to_string().contains("cannot read: yesterday"), + "{error}" + ); + } + + #[test] + fn a_row_without_a_repository_name_falls_back_to_its_id() { + let mut row = row("COMPLETED", "2026-10-05T10:00:00Z", None); + assert_eq!(row.repository(), NO_REPOSITORY); + row.repository_id = Some("0190f3a0-0000-7000-8000-000000000022".to_owned()); + assert_eq!(row.repository(), "0190f3a0-0000-7000-8000-000000000022"); + row.repository_full_name = Some("acme/api".to_owned()); + assert_eq!(row.repository(), "acme/api"); + } + + #[test] + fn statuses_newer_than_this_cli_count_as_other() { + let mut group = Group::default(); + for status in ["COMPLETED", "RUNNING", "PENDING", "EXCLUDED", "ARCHIVED"] { + group.add(status, None); + } + let summary = group.summary(ALL.to_owned()); + assert_eq!( + [ + summary.reviews, + summary.completed, + summary.unfinished, + summary.other + ], + [5, 1, 2, 2] + ); + } +} diff --git a/tests/stats.rs b/tests/stats.rs new file mode 100644 index 0000000..1e7bcbb --- /dev/null +++ b/tests/stats.rs @@ -0,0 +1,308 @@ +//! `proofline stats` against a loopback stand-in for the console: it reads +//! every page of the `reviews` export for one window and reports each +//! repository's review outcomes and turnaround. + +use std::sync::{Arc, Mutex}; + +use axum::Router; +use axum::http::{HeaderMap, Uri, header}; +use axum::response::{IntoResponse, Response}; +use axum::routing::get; +use serde_json::{Value, json}; + +const ORG: &str = "0190f3a0-0000-7000-8000-000000000001"; +const TOKEN: &str = "pld_secretsecretsecret"; +const HORIZON: &str = "2026-10-25T00:00:00Z"; +const TO: &str = "2026-10-25T00:00:00Z"; +/// Each `--from` selects how the stand-in pages its answer. +const PAGED: &str = "2026-10-01T00:00:00Z"; +const MOVING_HORIZON: &str = "2026-10-02T00:00:00Z"; +const REPEATED_CURSOR: &str = "2026-10-03T00:00:00Z"; +const OLD_VERSION: &str = "2026-10-04T00:00:00Z"; + +fn row(repository: Option<&str>, status: &str, seconds: Option) -> Value { + // Created at 10:00:00; the fixtures finish within the same day. + let completed_at = seconds.map(|seconds| { + let clock = 10 * 3_600 + seconds; + format!( + "2026-10-05T{:02}:{:02}:{:02}Z", + clock / 3_600, + clock % 3_600 / 60, + clock % 60 + ) + }); + json!({ + "dataset_version": 1, + "organization_id": ORG, + "review_id": "0190f3a0-0000-7000-8000-000000000033", + "kind": "PULL_REQUEST", + "status": status, + "trigger_origin": "AUTOMATIC", + "created_at": "2026-10-05T10:00:00Z", + "completed_at": completed_at, + "repository_full_name": repository, + "repository_id": null, + }) +} + +fn page(rows: &[Value], horizon: &str, next: Option<&str>) -> Response { + let body: String = rows.iter().map(|row| format!("{row}\n")).collect(); + let mut headers = HeaderMap::new(); + headers.insert( + header::CONTENT_TYPE, + "application/x-ndjson; charset=utf-8".parse().unwrap(), + ); + headers.insert("x-proofline-export-version", "1".parse().unwrap()); + headers.insert("x-proofline-export-settled-until", horizon.parse().unwrap()); + if let Some(next) = next { + headers.insert("x-proofline-export-next-cursor", next.parse().unwrap()); + } + (headers, body).into_response() +} + +/// Serves the reviews export and records each request's query. +async fn serve() -> (String, Arc>>>) { + let queries = Arc::new(Mutex::new(Vec::new())); + let seen = Arc::clone(&queries); + let app = Router::new().route( + &format!("/api/v1/organizations/{ORG}/exports/reviews"), + get(move |headers: HeaderMap, uri: Uri| { + let seen = Arc::clone(&seen); + async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + assert!( + headers + .get_all(header::ACCEPT) + .iter() + .any(|accept| accept == "application/x-ndjson") + ); + let query: Vec<(String, String)> = + url::form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()) + .into_owned() + .collect(); + seen.lock().unwrap().push(query.clone()); + let value = |key: &str| { + query + .iter() + .find(|(name, _)| name == key) + .map(|(_, value)| value.clone()) + }; + let cursor = value("cursor"); + match (value("from").unwrap().as_str(), cursor.as_deref()) { + (PAGED, None) => page( + &[ + row(Some("acme/api"), "COMPLETED", Some(120)), + row(Some("acme/api"), "COMPLETED", Some(600)), + row(Some("acme/web"), "FAILED", Some(60)), + row(Some("acme/web"), "RUNNING", None), + ], + HORIZON, + Some("page-2"), + ), + (PAGED, Some("page-2")) => page( + &[ + row(Some("acme/api"), "COMPLETED", Some(60)), + row(Some("acme/api"), "INCOMPLETE", Some(900)), + row(Some("acme/web"), "COMPLETED", Some(3_725)), + row(None, "SUPERSEDED", None), + ], + HORIZON, + None, + ), + // Every page of this window names the same next cursor. + (MOVING_HORIZON, None) | (REPEATED_CURSOR, _) => { + page(&[], HORIZON, Some("page-2")) + } + (MOVING_HORIZON, Some(_)) => page(&[], "2026-10-25T00:05:00Z", None), + (OLD_VERSION, _) => { + let mut response = page(&[], HORIZON, None); + response + .headers_mut() + .insert("x-proofline-export-version", "9".parse().unwrap()); + response + } + other => panic!("unexpected request {other:?}"), + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (origin, queries) +} + +async fn cli(origin: &str, args: &[&str]) -> std::process::Output { + let directory = tempfile::tempdir().unwrap(); + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + command + .args(["--base-url", origin, "--org", ORG]) + .env("PROOFLINE_TOKEN", TOKEN) + .env( + "DBUS_SESSION_BUS_ADDRESS", + "unix:path=/proofline-test-unavailable-bus", + ) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PATH", "") + .current_dir(directory.path()); + tokio::time::timeout( + std::time::Duration::from_secs(15), + command.args(args).kill_on_drop(true).output(), + ) + .await + .unwrap() + .unwrap() +} + +fn stats_args<'a>(from: &'a str, extra: &[&'a str]) -> Vec<&'a str> { + let mut args = vec!["stats", "--from", from, "--to", TO]; + args.extend_from_slice(extra); + args +} + +#[tokio::test] +async fn stats_reads_every_page_and_reports_turnaround_per_repository() { + let (origin, queries) = serve().await; + + let output = cli(&origin, &stats_args(PAGED, &["--json"])).await; + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!( + report, + json!({ + "from": PAGED, + "to": TO, + "settled_until": HORIZON, + "pages": 2, + "repositories": [ + { + "repository": "(no repository)", + "reviews": 1, "completed": 0, "incomplete": 0, "failed": 0, + "unfinished": 0, "other": 1, + "seconds_to_complete": null, + }, + { + "repository": "acme/api", + "reviews": 4, "completed": 3, "incomplete": 1, "failed": 0, + "unfinished": 0, "other": 0, + "seconds_to_complete": {"p50": 120, "p90": 600, "p99": 600, "max": 600}, + }, + { + "repository": "acme/web", + "reviews": 3, "completed": 1, "incomplete": 0, "failed": 1, + "unfinished": 1, "other": 0, + "seconds_to_complete": {"p50": 3725, "p90": 3725, "p99": 3725, "max": 3725}, + }, + ], + "all": { + "repository": "all", + "reviews": 8, "completed": 4, "incomplete": 1, "failed": 1, + "unfinished": 1, "other": 1, + "seconds_to_complete": {"p50": 120, "p90": 3725, "p99": 3725, "max": 3725}, + }, + }) + ); + + // The second page keeps the window and format and adds only the cursor. + let queries = queries.lock().unwrap().clone(); + let base = vec![ + ("from".to_owned(), PAGED.to_owned()), + ("to".to_owned(), TO.to_owned()), + ("format".to_owned(), "ndjson".to_owned()), + ]; + let mut continued = base.clone(); + continued.push(("cursor".to_owned(), "page-2".to_owned())); + assert_eq!(queries, [base, continued]); +} + +#[tokio::test] +async fn stats_prints_a_table_with_readable_durations() { + let (origin, _) = serve().await; + + let output = cli(&origin, &stats_args(PAGED, &[])).await; + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let table = String::from_utf8(output.stdout).unwrap(); + let lines: Vec> = table + .lines() + .map(|line| line.split_whitespace().collect()) + .collect(); + assert_eq!( + lines, + [ + vec![ + "repository", + "reviews", + "completed", + "incomplete", + "failed", + "unfinished", + "other", + "p50", + "p90", + "p99", + "max" + ], + vec![ + "(no", + "repository)", + "1", + "0", + "0", + "0", + "0", + "1", + "-", + "-", + "-", + "-" + ], + vec![ + "acme/api", "4", "3", "1", "0", "0", "0", "2m00s", "10m00s", "10m00s", "10m00s" + ], + vec![ + "acme/web", "3", "1", "0", "1", "1", "0", "1h02m", "1h02m", "1h02m", "1h02m" + ], + vec![ + "all", "8", "4", "1", "1", "1", "1", "2m00s", "1h02m", "1h02m", "1h02m" + ], + ], + "{table}" + ); + let progress = String::from_utf8_lossy(&output.stderr); + assert!( + progress.contains(&format!("settled-until: {HORIZON}")), + "{progress}" + ); +} + +#[tokio::test] +async fn stats_refuses_a_horizon_that_moves_a_cursor_that_repeats_or_an_unknown_version() { + let (origin, _) = serve().await; + + for (from, reason) in [ + (MOVING_HORIZON, "settled horizon changed"), + (REPEATED_CURSOR, "repeated a continuation cursor"), + (OLD_VERSION, "unsupported export format or version"), + ] { + let output = cli(&origin, &stats_args(from, &["--json"])).await; + + assert_eq!(output.status.code(), Some(1), "{from}"); + assert!( + output.stdout.is_empty(), + "{from}: a partial report is never printed" + ); + let diagnostic = String::from_utf8_lossy(&output.stderr); + assert!(diagnostic.contains(reason), "{from}: {diagnostic}"); + assert!(!diagnostic.contains(TOKEN)); + } +} From 439686bcf5f5c04c83f0824219b2249c805f7449 Mon Sep 17 00:00:00 2001 From: Sahib Yar Date: Tue, 1 Dec 2026 01:32:46 +0500 Subject: [PATCH 3/3] feat: count pull-request reviews by default and group by repository ID The reviews export mixes pull-request, deployment, local patch, commit, named-file, merge-group and revision-scan reviews. Mixing them skews the turnaround authors wait for, and revision scans currently end FAILED or INCOMPLETE, so they inflate the failed count. stats now counts pull_request reviews unless a repeatable --kind selects others, and reports the kinds it counted and how many reviews it left out. Repository names are display data, so reviews now group by the stable repository ID and show its current name, falling back to the name and then '(no repository)' when the review records no ID. --- README.md | 2 +- src/lib.rs | 3 +- src/stats.rs | 124 +++++++++++++++++++++++++++++++++++++++++-------- tests/stats.rs | 121 ++++++++++++++++++++++++++++++++++++----------- 4 files changed, 202 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 64990c5..4ab51fc 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ The command sends the exact 40-character lowercase SHA supplied by CI and does n `proofline export reviews --from 2026-10-01T00:00:00Z --to 2026-10-25T00:00:00Z --format csv` writes one export page to stdout and requires `analytics:read`. The datasets are `reviews`, `findings`, `finding_outcomes`, `finding_validations`, and `spend`. The default format is NDJSON, while CSV repeats its header on every page. The settled horizon and optional next cursor go to stderr. Repeat with `--cursor` and the same window and `--group-by` to continue. A failed page exits nonzero; never treat partial output from several invocations as a complete export. -`proofline stats --from 2026-10-01T00:00:00Z --to 2026-10-25T00:00:00Z` answers how long reviews take and how often they finish, per repository. It reads every page of the `reviews` export for the window, so it needs `analytics:read` and the same window of at most 31 days, then prints one row per repository and an `all` row: the reviews counted by status (`completed`, `incomplete`, `failed`, `unfinished` for pending or running, and `other`) and the p50, p90, p99 and longest time from creation to completion of the completed reviews, by the nearest-rank method. A review that is incomplete, failed or stopped gave no usable result, so it has no turnaround. `--json` prints the same report with times in seconds. The settled horizon and page count go to stderr. The report appears only after the last page: a failed page, a horizon that changes between pages or a cursor that repeats exits 1 and prints no partial report. +`proofline stats --from 2026-10-01T00:00:00Z --to 2026-10-25T00:00:00Z` answers how long reviews take and how often they finish, per repository. It reads every page of the `reviews` export for the window, so it needs `analytics:read` and the same window of at most 31 days. It counts pull-request reviews only; repeat `--kind` to choose others (`pull_request`, `deployment`, `patch`, `commit`, `files`, `merge_group`, `revision_scan`), so scans or deployments never skew how long pull requests wait. It then prints one row per repository, grouped by repository ID and shown by its current name, and an `all` row: the reviews counted by status (`completed`, `incomplete`, `failed`, `unfinished` for pending or running, and `other`) and the p50, p90, p99 and longest time from creation to completion of the completed reviews, by the nearest-rank method. A review that is incomplete, failed or stopped gave no usable result, so it has no turnaround. `--json` prints the same report with times in seconds. The settled horizon, page count, counted kinds and number of reviews left out go to stderr. The report appears only after the last page: a failed page, a horizon that changes between pages or a cursor that repeats exits 1 and prints no partial report. ## Development and publishing diff --git a/src/lib.rs b/src/lib.rs index a8c30a2..fd55e00 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -146,7 +146,8 @@ enum Command { /// Reads every page of the `reviews` export for the window, then prints /// per repository the reviews by status and the p50, p90, p99 and /// longest time from creation to completion of its completed reviews. - /// It needs `analytics:read` and prints nothing unless every page reads. + /// It counts pull-request reviews unless `--kind` selects others. It + /// needs `analytics:read` and prints nothing unless every page reads. Stats(stats::StatsArgs), /// Print a shell completion script to standard output. /// diff --git a/src/stats.rs b/src/stats.rs index 63ed082..117eabd 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, HashSet}; use std::io::Write as _; use anyhow::{Context as _, bail}; -use clap::Args; +use clap::{Args, ValueEnum}; use serde::{Deserialize, Serialize}; use crate::github_actions::unix_seconds; @@ -31,14 +31,46 @@ pub(crate) struct StatsArgs { /// Exclusive RFC3339 end of the window. #[arg(long)] to: String, + /// Review kind to count; repeat for several. Other kinds are left out, + /// so a scan or deployment never skews how long pull requests wait. + #[arg(long = "kind", value_enum, default_values_t = [Kind::PullRequest])] + kinds: Vec, /// Print JSON instead of a table. #[arg(long)] json: bool, } +/// What a review analyzes, as the `reviews` export's `kind` names it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] +#[value(rename_all = "snake_case")] +enum Kind { + PullRequest, + Deployment, + Patch, + Commit, + Files, + MergeGroup, + RevisionScan, +} + +impl Kind { + const fn wire(self) -> &'static str { + match self { + Self::PullRequest => "PULL_REQUEST", + Self::Deployment => "DEPLOYMENT", + Self::Patch => "PATCH", + Self::Commit => "COMMIT", + Self::Files => "FILES", + Self::MergeGroup => "MERGE_GROUP", + Self::RevisionScan => "REVISION_SCAN", + } + } +} + /// The columns of a `reviews` export row that the report reads. #[derive(Debug, Deserialize)] struct Row { + kind: String, status: String, created_at: String, completed_at: Option, @@ -47,7 +79,18 @@ struct Row { } impl Row { - fn repository(&self) -> &str { + /// The stable repository ID groups reviews; the name is display data. + /// A review without an ID groups by its name, if it has one. + fn group_key(&self) -> (Option<&str>, Option<&str>) { + self.repository_id + .as_deref() + .map_or((None, self.repository_full_name.as_deref()), |id| { + (Some(id), None) + }) + } + + /// The repository's current name, else its ID, else no repository. + fn display_name(&self) -> &str { self.repository_full_name .as_deref() .or(self.repository_id.as_deref()) @@ -106,10 +149,11 @@ impl Group { self.seconds.extend(turnaround); } - fn summary(mut self, repository: String) -> Summary { + fn summary(mut self, repository: String, repository_id: Option) -> Summary { self.seconds.sort_unstable(); Summary { repository, + repository_id, reviews: self.reviews, completed: self.completed, incomplete: self.incomplete, @@ -149,6 +193,7 @@ impl Turnaround { #[derive(Debug, Serialize)] struct Summary { repository: String, + repository_id: Option, reviews: u64, completed: u64, incomplete: u64, @@ -164,13 +209,19 @@ struct Report<'a> { to: &'a str, settled_until: String, pages: usize, + kinds: Vec<&'static str>, + excluded_reviews: u64, repositories: Vec, all: Summary, } pub(crate) async fn run(api: &Api, args: &StatsArgs) -> anyhow::Result { - let mut repositories: BTreeMap = BTreeMap::new(); + let kinds: Vec<&'static str> = args.kinds.iter().map(|kind| kind.wire()).collect(); + // Keyed by (repository ID, name when there is no ID); holds the name shown. + let mut repositories: BTreeMap<(Option, Option), (String, Group)> = + BTreeMap::new(); let mut all = Group::default(); + let mut excluded_reviews = 0; let mut horizon: Option = None; let mut cursors = HashSet::new(); let mut cursor: Option = None; @@ -198,24 +249,36 @@ pub(crate) async fn run(api: &Api, args: &StatsArgs) -> anyhow::Result } let row: Row = serde_json::from_slice(line) .context("the export has a reviews row this CLI cannot read")?; + if !kinds.contains(&row.kind.as_str()) { + excluded_reviews += 1; + continue; + } let turnaround = row.turnaround()?; all.add(&row.status, turnaround); + let (id, name) = row.group_key(); repositories - .entry(row.repository().to_owned()) - .or_default() + .entry((id.map(str::to_owned), name.map(str::to_owned))) + .or_insert_with(|| (row.display_name().to_owned(), Group::default())) + .1 .add(&row.status, turnaround); } let Some(next) = page.next_cursor else { + let mut summaries: Vec = repositories + .into_iter() + .map(|((id, _), (name, group))| group.summary(name, id)) + .collect(); + summaries.sort_by(|a, b| { + (&a.repository, &a.repository_id).cmp(&(&b.repository, &b.repository_id)) + }); let report = Report { from: &args.from, to: &args.to, settled_until: page.settled_until, pages, - repositories: repositories - .into_iter() - .map(|(repository, group)| group.summary(repository)) - .collect(), - all: all.summary(ALL.to_owned()), + kinds, + excluded_reviews, + repositories: summaries, + all: all.summary(ALL.to_owned(), None), }; return print(&report, args.json); }; @@ -229,9 +292,11 @@ pub(crate) async fn run(api: &Api, args: &StatsArgs) -> anyhow::Result fn print(report: &Report<'_>, json: bool) -> anyhow::Result { say(&format!( - "settled-until: {} ({} pages)", + "settled-until: {} ({} pages); counted {} reviews, left out {} reviews of other kinds", crate::text::one_line(&report.settled_until), - report.pages + report.pages, + report.kinds.join(", "), + report.excluded_reviews )); let mut stdout = std::io::stdout().lock(); if json { @@ -352,6 +417,7 @@ mod tests { fn row(status: &str, created_at: &str, completed_at: Option<&str>) -> Row { Row { + kind: "PULL_REQUEST".to_owned(), status: status.to_owned(), created_at: created_at.to_owned(), completed_at: completed_at.map(str::to_owned), @@ -392,13 +458,33 @@ mod tests { } #[test] - fn a_row_without_a_repository_name_falls_back_to_its_id() { + fn reviews_group_by_repository_id_and_show_its_name() { + let id = "0190f3a0-0000-7000-8000-000000000022"; let mut row = row("COMPLETED", "2026-10-05T10:00:00Z", None); - assert_eq!(row.repository(), NO_REPOSITORY); - row.repository_id = Some("0190f3a0-0000-7000-8000-000000000022".to_owned()); - assert_eq!(row.repository(), "0190f3a0-0000-7000-8000-000000000022"); + assert_eq!(row.group_key(), (None, None)); + assert_eq!(row.display_name(), NO_REPOSITORY); + row.repository_full_name = Some("acme/api".to_owned()); - assert_eq!(row.repository(), "acme/api"); + assert_eq!(row.group_key(), (None, Some("acme/api"))); + + row.repository_id = Some(id.to_owned()); + assert_eq!( + row.group_key(), + (Some(id), None), + "the name never splits an ID" + ); + assert_eq!(row.display_name(), "acme/api"); + + row.repository_full_name = None; + assert_eq!(row.display_name(), id); + } + + #[test] + fn every_kind_names_its_export_value() { + for kind in Kind::value_variants() { + let flag = kind.to_possible_value().unwrap(); + assert_eq!(kind.wire(), flag.get_name().to_ascii_uppercase()); + } } #[test] @@ -407,7 +493,7 @@ mod tests { for status in ["COMPLETED", "RUNNING", "PENDING", "EXCLUDED", "ARCHIVED"] { group.add(status, None); } - let summary = group.summary(ALL.to_owned()); + let summary = group.summary(ALL.to_owned(), None); assert_eq!( [ summary.reviews, diff --git a/tests/stats.rs b/tests/stats.rs index 1e7bcbb..a468c75 100644 --- a/tests/stats.rs +++ b/tests/stats.rs @@ -19,6 +19,11 @@ const PAGED: &str = "2026-10-01T00:00:00Z"; const MOVING_HORIZON: &str = "2026-10-02T00:00:00Z"; const REPEATED_CURSOR: &str = "2026-10-03T00:00:00Z"; const OLD_VERSION: &str = "2026-10-04T00:00:00Z"; +const API: &str = "0190f3a0-0000-7000-8000-0000000000a1"; +const WEB: &str = "0190f3a0-0000-7000-8000-0000000000a2"; +/// A repository the organization no longer owns: the export keeps its ID +/// and drops its name. +const DEPARTED: &str = "0190f3a0-0000-7000-8000-0000000000a3"; fn row(repository: Option<&str>, status: &str, seconds: Option) -> Value { // Created at 10:00:00; the fixtures finish within the same day. @@ -41,10 +46,19 @@ fn row(repository: Option<&str>, status: &str, seconds: Option) -> Value { "created_at": "2026-10-05T10:00:00Z", "completed_at": completed_at, "repository_full_name": repository, - "repository_id": null, + "repository_id": match repository { + Some("acme/api") => Some(API), + Some("acme/web") => Some(WEB), + _ => None, + }, }) } +fn with(mut row: Value, field: &str, value: Value) -> Value { + row[field] = value; + row +} + fn page(rows: &[Value], horizon: &str, next: Option<&str>) -> Response { let body: String = rows.iter().map(|row| format!("{row}\n")).collect(); let mut headers = HeaderMap::new(); @@ -105,6 +119,22 @@ async fn serve() -> (String, Arc>>>) { row(Some("acme/api"), "INCOMPLETE", Some(900)), row(Some("acme/web"), "COMPLETED", Some(3_725)), row(None, "SUPERSEDED", None), + // Not pull-request reviews: left out unless --kind selects them. + with( + row(Some("acme/api"), "FAILED", Some(30)), + "kind", + json!("REVISION_SCAN"), + ), + with( + row(Some("acme/web"), "COMPLETED", Some(20)), + "kind", + json!("PATCH"), + ), + with( + row(None, "COMPLETED", Some(90)), + "repository_id", + json!(DEPARTED), + ), ], HORIZON, None, @@ -172,6 +202,17 @@ async fn stats_reads_every_page_and_reports_turnaround_per_repository() { String::from_utf8_lossy(&output.stderr) ); let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + let group = |repository: &str, id: Option<&str>, counts: [u64; 6], turnaround: Value| { + let [reviews, completed, incomplete, failed, unfinished, other] = counts; + json!({ + "repository": repository, "repository_id": id, + "reviews": reviews, "completed": completed, "incomplete": incomplete, + "failed": failed, "unfinished": unfinished, "other": other, + "seconds_to_complete": turnaround, + }) + }; + let only = + |seconds: u64| json!({"p50": seconds, "p90": seconds, "p99": seconds, "max": seconds}); assert_eq!( report, json!({ @@ -179,32 +220,25 @@ async fn stats_reads_every_page_and_reports_turnaround_per_repository() { "to": TO, "settled_until": HORIZON, "pages": 2, + "kinds": ["PULL_REQUEST"], + "excluded_reviews": 2, "repositories": [ - { - "repository": "(no repository)", - "reviews": 1, "completed": 0, "incomplete": 0, "failed": 0, - "unfinished": 0, "other": 1, - "seconds_to_complete": null, - }, - { - "repository": "acme/api", - "reviews": 4, "completed": 3, "incomplete": 1, "failed": 0, - "unfinished": 0, "other": 0, - "seconds_to_complete": {"p50": 120, "p90": 600, "p99": 600, "max": 600}, - }, - { - "repository": "acme/web", - "reviews": 3, "completed": 1, "incomplete": 0, "failed": 1, - "unfinished": 1, "other": 0, - "seconds_to_complete": {"p50": 3725, "p90": 3725, "p99": 3725, "max": 3725}, - }, + group("(no repository)", None, [1, 0, 0, 0, 0, 1], Value::Null), + group(DEPARTED, Some(DEPARTED), [1, 1, 0, 0, 0, 0], only(90)), + group( + "acme/api", + Some(API), + [4, 3, 1, 0, 0, 0], + json!({"p50": 120, "p90": 600, "p99": 600, "max": 600}), + ), + group("acme/web", Some(WEB), [3, 1, 0, 1, 1, 0], only(3_725)), ], - "all": { - "repository": "all", - "reviews": 8, "completed": 4, "incomplete": 1, "failed": 1, - "unfinished": 1, "other": 1, - "seconds_to_complete": {"p50": 120, "p90": 3725, "p99": 3725, "max": 3725}, - }, + "all": group( + "all", + None, + [9, 5, 1, 1, 1, 1], + json!({"p50": 120, "p90": 3725, "p99": 3725, "max": 3725}), + ), }) ); @@ -266,6 +300,9 @@ async fn stats_prints_a_table_with_readable_durations() { "-", "-" ], + vec![ + DEPARTED, "1", "1", "0", "0", "0", "0", "1m30s", "1m30s", "1m30s", "1m30s" + ], vec![ "acme/api", "4", "3", "1", "0", "0", "0", "2m00s", "10m00s", "10m00s", "10m00s" ], @@ -273,18 +310,48 @@ async fn stats_prints_a_table_with_readable_durations() { "acme/web", "3", "1", "0", "1", "1", "0", "1h02m", "1h02m", "1h02m", "1h02m" ], vec![ - "all", "8", "4", "1", "1", "1", "1", "2m00s", "1h02m", "1h02m", "1h02m" + "all", "9", "5", "1", "1", "1", "1", "2m00s", "1h02m", "1h02m", "1h02m" ], ], "{table}" ); let progress = String::from_utf8_lossy(&output.stderr); assert!( - progress.contains(&format!("settled-until: {HORIZON}")), + progress.contains(&format!("settled-until: {HORIZON}")) + && progress.contains("left out 2 reviews of other kinds"), "{progress}" ); } +#[tokio::test] +async fn stats_counts_the_kinds_that_kind_selects() { + let (origin, _) = serve().await; + + let output = cli( + &origin, + &stats_args( + PAGED, + &["--kind", "pull_request", "--kind", "patch", "--json"], + ), + ) + .await; + + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["kinds"], json!(["PULL_REQUEST", "PATCH"])); + assert_eq!(report["excluded_reviews"], 1, "only the scan is left out"); + let web = &report["repositories"][3]; + assert_eq!(web["repository"], "acme/web"); + assert_eq!([&web["reviews"], &web["completed"]], [4, 2]); + assert_eq!(web["seconds_to_complete"]["p50"], 20); + assert_eq!(report["all"]["reviews"], 10); + assert_eq!(report["all"]["seconds_to_complete"]["p50"], 90); +} + #[tokio::test] async fn stats_refuses_a_horizon_that_moves_a_cursor_that_repeats_or_an_unknown_version() { let (origin, _) = serve().await;