From e96c6b6c01ee7a2208b7d61533d43ae76246dede Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Sun, 6 Dec 2026 19:35:22 +0200 Subject: [PATCH 1/2] Request every pushed branch's review before waiting on any --- src/hooks.rs | 169 ++++++++++++++++++++++++++++++++++++++----------- tests/hooks.rs | 144 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 276 insertions(+), 37 deletions(-) diff --git a/src/hooks.rs b/src/hooks.rs index 7d5550a..7f3b21d 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -5,6 +5,7 @@ //! not reviewed, never as clean. use std::path::Path; +use std::task::Poll; use std::time::Duration; use anyhow::{Context as _, bail}; @@ -24,7 +25,10 @@ use crate::outcome::{self, Outcome}; use crate::render::location; use crate::severity::Severity; use crate::text::one_line; -use crate::{RepositoryArgs, Verdict, connect, connected_repository, preflight, read_review, say}; +use crate::{ + RepositoryArgs, ReviewRead, Verdict, connect, connected_repository, poll_until, preflight, + read_review_once, say, +}; /// Identifies a script this CLI wrote. Uninstall removes a hook only when its /// whole text is the script this version writes, so an edited hook stays. @@ -449,32 +453,37 @@ pub(crate) async fn run( remote: remote.to_owned(), }; let (subjects, skipped) = subjects(hook, here, remote).await?; - let mut reports = Vec::new(); - let mut api: Option> = None; - for subject in subjects { - let report = match ready(subject.changes) { - Err(report) => report, - Ok(changes) => { - // Connect once, and only when something needs a review. - let connection = match api.take() { - Some(connection) => connection, - None => match Http::new(origin.clone()) { - Ok(http) => connect(http, token.clone(), org) - .await - .map_err(|error| format!("{error:#}")), - Err(error) => Err(error.to_string()), - }, - }; - let report = match &connection { - Ok(api) => request(api, &repository, hook, changes, deadline).await, - Err(error) => Report::Unreviewed(error.clone()), - }; - api = Some(connection); - report - } - }; - reports.push((subject.label, report)); - } + let ready: Vec<_> = subjects + .into_iter() + .map(|subject| (subject.label, ready(subject.changes))) + .collect(); + // Connect once, and only when something needs a review. + let connection = if ready.iter().any(|(_, ready)| ready.is_ok()) { + Some(match Http::new(origin) { + Ok(http) => connect(http, token, org) + .await + .map_err(|error| format!("{error:#}")), + Err(error) => Err(error.to_string()), + }) + } else { + None + }; + let reports = match connection { + Some(Ok(api)) => review(&api, &repository, hook, ready, deadline).await, + // Without a connection, every subject that needed one is unreviewed. + failed => { + let error = failed.and_then(Result::err).unwrap_or_default(); + ready + .into_iter() + .map(|(label, ready)| { + let report = ready + .err() + .unwrap_or_else(|| Report::Unreviewed(error.clone())); + (label, report) + }) + .collect() + } + }; Ok(conclude(hook, &settings, &reports, skipped)) } @@ -489,29 +498,87 @@ fn ready(changes: Result) -> Result)>, + deadline: tokio::time::Instant, +) -> Vec<(String, Report)> { + let mut repository_id = None; + let mut requested = Vec::new(); + for (label, ready) in ready { + let next = match ready { + Ok(changes) => request(api, repository, &mut repository_id, hook, changes).await, + Err(report) => Err(report), + }; + requested.push((label, next)); + } + join_all(requested.into_iter().map(|(label, next)| async move { + let report = match next { + Ok(review_id) => wait(api, &label, review_id, deadline).await, + Err(report) => report, + }; + (label, report) + })) + .await +} + +/// Uploads one subject's patch. The repository is looked up until a lookup +/// succeeds, then reused for the rest of the push. async fn request( api: &Api, repository: &RepositoryArgs, + repository_id: &mut Option, hook: Hook, changes: LocalChanges, - deadline: tokio::time::Instant, -) -> Report { +) -> Result { let requested = async { - let (_, repository_id) = connected_repository(api, repository).await?; + let id = match *repository_id { + Some(id) => id, + None => connected_repository(api, repository).await?.1, + }; + *repository_id = Some(id); let request = PatchReviewRequest { base_commit_sha: changes.base_commit_sha, patch: changes.patch, trigger_source: Some(hook.trigger_source()), verify_finding_ids: Vec::new(), }; - let requested = api.request_patch_review(repository_id, &request).await?; - let (_, detail, state) = read_review(api, requested.review_id, Some(deadline), false) - .await? - .context("Proofline did not answer a read of the review before the deadline")?; - anyhow::Ok((requested.review_id, detail, state)) + anyhow::Ok(api.request_patch_review(id, &request).await?.review_id) + }; + requested + .await + .map_err(|error| Report::Unreviewed(format!("{error:#}"))) +} + +/// Reads one requested review as `read_review` does, until it finishes or the +/// deadline passes, but names the subject on every progress line. +async fn wait(api: &Api, label: &str, review_id: Uuid, deadline: tokio::time::Instant) -> Report { + let read = async { + if tokio::time::Instant::now() >= deadline { + return read_review_once(api, review_id, false).await.map(Some); + } + poll_until( + deadline, + || read_review_once(api, review_id, false), + |read: &ReviewRead| read.2.is_some(), + |read: &ReviewRead, delay| { + say(&format!( + "Review of {label} is {}; checking again in {delay} seconds.", + one_line(&read.1.status) + )); + }, + ) + .await }; - match requested.await { - Ok((review_id, detail, state)) => Report::Read { + let read = read.await.and_then(|read| { + read.context("Proofline did not answer a read of the review before the deadline") + }); + match read { + Ok((_, detail, state)) => Report::Read { review_id, url: api.review_url(review_id), detail: Box::new(detail), @@ -521,6 +588,34 @@ async fn request( } } +/// Drives the futures together on this task and returns their outputs in +/// order. The runtime is single-threaded, and the crate has no `futures`. +async fn join_all(futures: impl IntoIterator) -> Vec { + let mut futures: Vec<_> = futures.into_iter().map(|f| Some(Box::pin(f))).collect(); + let mut outputs: Vec> = futures.iter().map(|_| None).collect(); + std::future::poll_fn(|cx| { + let mut pending = false; + for (future, output) in std::iter::zip(&mut futures, &mut outputs) { + if let Some(running) = future { + match running.as_mut().poll(cx) { + Poll::Ready(value) => { + *output = Some(value); + *future = None; + } + Poll::Pending => pending = true, + } + } + } + if pending { + Poll::Pending + } else { + Poll::Ready(()) + } + }) + .await; + outputs.into_iter().flatten().collect() +} + /// The first sentence of model text, on one line. fn first_sentence(text: &str) -> String { let line = one_line(text); diff --git a/tests/hooks.rs b/tests/hooks.rs index ca3f94a..3c4d0ae 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -740,6 +740,150 @@ async fn each_pushed_branch_is_reviewed_against_the_commit_the_remote_has() { ); } +/// A console whose patch review `n` reads RUNNING until `expect` reviews have +/// been requested and `hold` has passed since its own request, then COMPLETED +/// with no findings. Returns the origin and the count of repository lookups. +async fn serve_held(expect: usize, hold: std::time::Duration) -> (String, Arc) { + let lookups = Arc::new(AtomicUsize::new(0)); + let requested = Arc::new(Mutex::new(Vec::::new())); + let counted = lookups.clone(); + let posted = requested.clone(); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/review-repository-source"), + get(move || { + counted.fetch_add(1, Ordering::SeqCst); + async { Json(json!({ "repository_id": REPOSITORY })) } + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/patch-reviews"), + post(move || { + let mut times = posted.lock().unwrap(); + times.push(std::time::Instant::now()); + let id = format!("0190f3a0-0000-7000-8000-0000000001{:02}", times.len()); + async move { + Json(json!({ "review_id": id, "existing": false, "patch_digest": "a".repeat(64) })) + } + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{{id}}"), + get(move |axum::extract::Path(id): axum::extract::Path| { + let times = requested.lock().unwrap(); + // Review n is ...0001nn, so its last group parses as 100 + n. + let n = id.rsplit('-').next().unwrap().parse::().unwrap() - 100; + let done = times.len() >= expect && times[n - 1].elapsed() >= hold; + let mut document = json!({ + "id": id, + "kind": "PATCH", + "status": if done { "COMPLETED" } else { "RUNNING" }, + "assessment_count": 0, + "assessments": [], + }); + if done { + document["code_assessment"] = json!({ + "id": "0190f3a0-0000-7000-8000-000000000066", + "status": "COMPLETED", + "base_commit_sha": "0123456789abcdef0123456789abcdef01234567", + "head_commit_sha": "89abcdef0123456789abcdef0123456789abcdef", + "findings": [], + }); + } + async move { Json(document) } + }), + ); + 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, lookups) +} + +/// A checkout whose push updates `main` and creates `feature`, with the +/// pre-push input Git would give the hook for it. +async fn two_branch_push(checkout: &Checkout) -> String { + let pushed = checkout + .commit("orders.rs", "fn main() { pushed() }\n") + .await; + let head = checkout + .commit("orders.rs", "fn main() { local() }\n") + .await; + let zero = "0".repeat(40); + format!( + "refs/heads/feature {head} refs/heads/feature {zero}\n\ + refs/heads/main {head} refs/heads/main {pushed}\n" + ) +} + +const PRE_PUSH: [&str; 5] = [ + "hook", + "run", + "pre-push", + "origin", + "https://github.com/acme/web.git", +]; + +/// Each review finishes only once every branch has been requested, so waiting +/// out the first branch before requesting the second runs out the timeout. +#[tokio::test] +async fn a_push_requests_every_branch_before_waiting_on_any() { + let checkout = Checkout::new().await; + let input = two_branch_push(&checkout).await; + checkout + .git(&["config", "proofline.hook.pre-push.timeout", "8"]) + .await; + let (origin, lookups) = serve_held(2, std::time::Duration::ZERO).await; + let output = checkout.proofline(&origin, &PRE_PUSH, &input).await; + let text = stderr(&output); + assert_eq!(output.status.code(), Some(0), "{text}"); + assert!( + text.contains("Proofline reviewed feature: COMPLETED"), + "{text}" + ); + assert!( + text.contains("Proofline reviewed main: COMPLETED"), + "{text}" + ); + assert!(!text.contains("still running"), "{text}"); + assert!(!text.contains("without a complete review"), "{text}"); + // The repository is looked up once for the whole push. + assert_eq!(lookups.load(Ordering::SeqCst), 1, "{text}"); +} + +/// Reviews polled side by side say which branch each progress line is about. +#[tokio::test] +async fn progress_lines_name_the_branch_they_are_about() { + let checkout = Checkout::new().await; + let input = two_branch_push(&checkout).await; + let (origin, _) = serve_held(1, std::time::Duration::from_secs(1)).await; + let output = checkout.proofline(&origin, &PRE_PUSH, &input).await; + let text = stderr(&output); + assert_eq!(output.status.code(), Some(0), "{text}"); + let progress: Vec<&str> = text + .lines() + .filter(|line| line.contains("checking again")) + .collect(); + assert!( + progress + .iter() + .any(|line| line.starts_with("Review of feature is RUNNING;")), + "{text}" + ); + assert!( + progress + .iter() + .any(|line| line.starts_with("Review of main is RUNNING;")), + "{text}" + ); + assert!( + progress + .iter() + .all(|line| line.starts_with("Review of feature ") + || line.starts_with("Review of main ")), + "{text}" + ); +} + /// Real pushes through the installed hook: the destination ref, not the /// source, says whether a line is a branch to review or a tag to skip. #[tokio::test] From 15667f09fba52c7c4d107999f82cc10ad1380d79 Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Sun, 6 Dec 2026 20:06:33 +0200 Subject: [PATCH 2/2] Read each accepted review while later branches upload --- src/hooks.rs | 24 +++++++------ tests/hooks.rs | 91 +++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 103 insertions(+), 12 deletions(-) diff --git a/src/hooks.rs b/src/hooks.rs index 7f3b21d..5c1f168 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -498,8 +498,9 @@ fn ready(changes: Result) -> Result)>, deadline: tokio::time::Instant, ) -> Vec<(String, Report)> { - let mut repository_id = None; - let mut requested = Vec::new(); - for (label, ready) in ready { - let next = match ready { - Ok(changes) => request(api, repository, &mut repository_id, hook, changes).await, + // Its holder uploads; waiters get it in the order they asked. + let repository_id = tokio::sync::Mutex::new(None); + let repository_id = &repository_id; + join_all(ready.into_iter().map(|(label, ready)| async move { + let requested = match ready { + Ok(changes) => { + let mut repository_id = repository_id.lock().await; + request(api, repository, &mut repository_id, hook, changes).await + } Err(report) => Err(report), }; - requested.push((label, next)); - } - join_all(requested.into_iter().map(|(label, next)| async move { - let report = match next { + let report = match requested { Ok(review_id) => wait(api, &label, review_id, deadline).await, Err(report) => report, }; diff --git a/tests/hooks.rs b/tests/hooks.rs index 3c4d0ae..0a58373 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -826,7 +826,7 @@ const PRE_PUSH: [&str; 5] = [ /// Each review finishes only once every branch has been requested, so waiting /// out the first branch before requesting the second runs out the timeout. #[tokio::test] -async fn a_push_requests_every_branch_before_waiting_on_any() { +async fn a_push_requests_every_branch_before_any_review_finishes() { let checkout = Checkout::new().await; let input = two_branch_push(&checkout).await; checkout @@ -884,6 +884,95 @@ async fn progress_lines_name_the_branch_they_are_about() { ); } +/// A console where the second upload takes 3.5 seconds and every read takes 2. +/// The first review is complete with a SERIOUS finding. Returns the origin and +/// what happened, in order. +async fn serve_slow_second_upload() -> (String, Arc>>) { + let events = Arc::new(Mutex::new(Vec::::new())); + let uploads = Arc::new(AtomicUsize::new(0)); + let (uploading, reading) = (events.clone(), events.clone()); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/review-repository-source"), + get(async || Json(json!({ "repository_id": REPOSITORY }))), + ) + .route( + &format!("/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/patch-reviews"), + post(move || async move { + let n = uploads.fetch_add(1, Ordering::SeqCst) + 1; + uploading.lock().unwrap().push(format!("upload {n} starts")); + let takes = if n == 1 { 200 } else { 3_500 }; + tokio::time::sleep(std::time::Duration::from_millis(takes)).await; + uploading.lock().unwrap().push(format!("upload {n} ends")); + let id = format!("0190f3a0-0000-7000-8000-0000000001{n:02}"); + Json(json!({ "review_id": id, "existing": false, "patch_digest": "a".repeat(64) })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{{id}}"), + get( + move |axum::extract::Path(id): axum::extract::Path| async move { + let first = id.ends_with("01"); + let n = if first { 1 } else { 2 }; + reading.lock().unwrap().push(format!("read {n} starts")); + tokio::time::sleep(std::time::Duration::from_secs(2)).await; + Json(json!({ + "id": id, + "kind": "PATCH", + "status": "COMPLETED", + "assessment_count": 0, + "assessments": [], + "code_assessment": { + "id": "0190f3a0-0000-7000-8000-000000000066", + "status": "COMPLETED", + "base_commit_sha": "0123456789abcdef0123456789abcdef01234567", + "head_commit_sha": "89abcdef0123456789abcdef0123456789abcdef", + "findings": if first { findings("SERIOUS", true, "ACTIVE") } else { json!([]) }, + }, + })) + }, + ), + ); + 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, events) +} + +/// An accepted review is read while later branches upload. Read only after the +/// last upload, the first branch's finding would miss the deadline. +#[tokio::test] +async fn a_slow_later_upload_does_not_hide_an_earlier_finding() { + let checkout = Checkout::new().await; + let input = two_branch_push(&checkout).await; + for (key, value) in [ + ("timeout", "5"), + ("mode", "block"), + ("onIncomplete", "warn"), + ] { + let key = format!("proofline.hook.pre-push.{key}"); + checkout.git(&["config", &key, value]).await; + } + let (origin, events) = serve_slow_second_upload().await; + let output = checkout.proofline(&origin, &PRE_PUSH, &input).await; + let text = stderr(&output); + let events = events.lock().unwrap().clone(); + assert_eq!( + output.status.code(), + Some(1), + "{events:?} +{text}" + ); + assert!( + text.contains("blocked this push: a finding at or above SERIOUS."), + "{text}" + ); + let at = |event: &str| events.iter().position(|seen| seen == event).unwrap(); + assert!(at("read 1 starts") < at("upload 2 ends"), "{events:?}"); + // Uploads still go one at a time, in Git's order. + assert!(at("upload 1 ends") < at("upload 2 starts"), "{events:?}"); +} + /// Real pushes through the installed hook: the destination ref, not the /// source, says whether a line is a branch to review or a tag to skip. #[tokio::test]