Watch
0
0
Fork
You've already forked hyperhive
0

review-classifier: a re-request after a title or description edit runs again instead of reposting the old verdict

This commit is contained in:
damocles 2026-11-25 20:08:22 +01:00 • committed by mara
commit 0876ff4de8
4 changed files with 117 additions and 16 deletions

View file

@ -113,8 +113,11 @@ fresh run on the new head.
Requesting the account again on a head it already reviewed depends on that Requesting the account again on a head it already reviewed depends on that
head's newest recorded review, as the [run store](#run-store-and-retention) head's newest recorded review, as the [run store](#run-store-and-retention)
holds it. When that review approved or requested changes, nothing runs: the holds it, and on the PR's title and description. A run records a hash of the
account posts the same verdict and result table again, opening with title and description it read, and an edit to either makes the earlier review
not count: the request starts a fresh run, as it does for a review that has no
hash because it predates the field. When that review approved or requested
changes, nothing runs: the account posts the same verdict and result table again, opening with
"Already reviewed `<sha>`, verdict unchanged." When it had no clean "Already reviewed `<sha>`, verdict unchanged." When it had no clean
verdict, or its post failed, the request starts a fresh run. A head with no verdict, or its post failed, the request starts a fresh run. A head with no
recorded review, such as one whose runs have dropped out of the newest 100, or recorded review, such as one whose runs have dropped out of the newest 100, or
@ -674,6 +677,8 @@ header. Each run has:
the try-out, or the forge user who requested the review the try-out, or the forge user who requested the review
- `head_sha`: the commit the run read, absent when the PR wasn't read, as for - `head_sha`: the commit the run read, absent when the PR wasn't read, as for
an unreadable PR or a request the controller couldn't queue an unreadable PR or a request the controller couldn't queue
- `described`: a hash of the title and description the run read, absent when
the PR wasn't read and on a record that predates the field
- `started_unix` and `finished_unix`: a try-out starts at its POST, a review - `started_unix` and `finished_unix`: a try-out starts at its POST, a review
once it has a run place and has read the PR once it has a run place and has read the PR
- `outcome`: `approved`, `changes-requested`, `no-verdict` or `post-failed` - `outcome`: `approved`, `changes-requested`, `no-verdict` or `post-failed`

View file

@ -744,6 +744,7 @@ async fn start(
pr, pr,
requester, requester,
head_sha: Some(pull.head_sha), head_sha: Some(pull.head_sha),
described: None,
started_unix, started_unix,
finished_unix: crate::agent_renewal::unix_now(), finished_unix: crate::agent_renewal::unix_now(),
outcome, outcome,

View file

@ -34,6 +34,7 @@ use async_nats::jetstream::{self, AckKind, consumer::PullConsumer};
use forgejo_api::ForgejoError; use forgejo_api::ForgejoError;
use futures_util::StreamExt as _; use futures_util::StreamExt as _;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use swarm_wire::review_classifier::{ use swarm_wire::review_classifier::{
Overall, REQUEST_CONSUMER, REQUEST_STREAM, REQUEST_SUBJECT_PREFIX, Reply, Row, TryOut, Verdict, Overall, REQUEST_CONSUMER, REQUEST_STREAM, REQUEST_SUBJECT_PREFIX, Reply, Row, TryOut, Verdict,
run_deadline, run_deadline,
@ -385,8 +386,14 @@ async fn accept(
let reason = ruling.reason.clone(); let reason = ruling.reason.clone();
let sent = post(poster, request, None, ruling.review()).await; let sent = post(poster, request, None, ruling.review()).await;
let ended = ended(RunOutcome::NoVerdict, reason, sent); let ended = ended(RunOutcome::NoVerdict, reason, sent);
runs.record(record(request, None, started_unix, ended, (None, None))) runs.record(record(
.await; request,
(None, None),
started_unix,
ended,
(None, None),
))
.await;
} }
/// Open [`REQUEST_STREAM`], creating it if nothing has yet. /// Open [`REQUEST_STREAM`], creating it if nothing has yet.
@ -709,8 +716,10 @@ async fn review(
"review requested on a head the PR has moved on from; reviewing its current head" "review requested on a head the PR has moved on from; reviewing its current head"
); );
} }
let described = pull.as_ref().ok().map(described);
if !moved if !moved
&& let Some(earlier) = newest_review(runs, req).await && let Some(described) = &described
&& let Some(earlier) = newest_review(runs, req, described).await
&& let Some(ruling) = reposted(&earlier) && let Some(ruling) = reposted(&earlier)
{ {
drop(slot); drop(slot);
@ -741,16 +750,31 @@ async fn read_pull(pulls: &impl PullSource, req: &Requested) -> Result<PullForRe
} }
} }
/// The newest recorded review of the head `req` names. `None` when it names /// A hash of the title and description `pull` was read with: the verdict
/// none, nothing is recorded for it, or the store can't be read; each of /// depends on them as much as on the head, so an edit to either makes the
/// those leads to a fresh run. /// next request a fresh run.
async fn newest_review(runs: &Runs, req: &Requested) -> Option<RunRecord> { fn described(pull: &PullForReview) -> String {
let mut hash = Sha256::new();
hash.update(pull.title.as_bytes());
hash.update([0]);
hash.update(pull.description.as_bytes());
hash.finalize().iter().fold(String::new(), |mut hex, b| {
let _ = write!(hex, "{b:02x}");
hex
})
}
/// The newest recorded review of the head `req` names, read with the title
/// and description `described` hashes. `None` when it names no head, nothing
/// is recorded for that head and description, or the store can't be read;
/// each of those leads to a fresh run.
async fn newest_review(runs: &Runs, req: &Requested, described: &str) -> Option<RunRecord> {
if req.head.is_empty() { if req.head.is_empty() {
return None; return None;
} }
let repo = format!("{}/{}", req.owner, req.name); let repo = format!("{}/{}", req.owner, req.name);
match runs match runs
.newest_review(&repo, req.pr.unsigned_abs(), &req.head) .newest_review(&repo, req.pr.unsigned_abs(), &req.head, described)
.await .await
{ {
Ok(found) => found, Ok(found) => found,
@ -805,7 +829,7 @@ async fn repost(
let sent = post(poster, req, earlier.head_sha.as_deref(), ruling.review()).await; let sent = post(poster, req, earlier.head_sha.as_deref(), ruling.review()).await;
record( record(
req, req,
earlier.head_sha.clone(), (earlier.head_sha.clone(), earlier.described.clone()),
started_unix, started_unix,
ended(earlier.outcome, reason, sent), ended(earlier.outcome, reason, sent),
(earlier.rows.clone(), earlier.overall), (earlier.rows.clone(), earlier.overall),
@ -897,6 +921,7 @@ async fn run(
) -> RunRecord { ) -> RunRecord {
let started_unix = unix_now(); let started_unix = unix_now();
let timer = Instant::now(); let timer = Instant::now();
let described = pull.as_ref().ok().map(described);
let (head, narrowed, outcome) = classify(files, pull, sink, req).await; let (head, narrowed, outcome) = classify(files, pull, sink, req).await;
let mut ruling = review_for(&outcome); let mut ruling = review_for(&outcome);
metrics.verdict(verdict_label(ruling.event)); metrics.verdict(verdict_label(ruling.event));
@ -927,7 +952,7 @@ async fn run(
}; };
let ended = ended(posted_as, reason, sent); let ended = ended(posted_as, reason, sent);
metrics.run_duration(ended.outcome, timer.elapsed().as_secs_f64()); metrics.run_duration(ended.outcome, timer.elapsed().as_secs_f64());
record(req, head, started_unix, ended, answer) record(req, (head, described), started_unix, ended, answer)
} }
/// Post `review` on `req`'s PR, naming `head` when there is one. The posted /// Post `review` on `req`'s PR, naming `head` when there is one. The posted
@ -1055,7 +1080,7 @@ fn ended(
/// The record of a run on `req` that read `head`. /// The record of a run on `req` that read `head`.
fn record( fn record(
req: &Requested, req: &Requested,
head: Option<String>, (head, described): (Option<String>, Option<String>),
started_unix: i64, started_unix: i64,
ended: Ended, ended: Ended,
(rows, overall): (Option<Vec<Row>>, Option<Overall>), (rows, overall): (Option<Vec<Row>>, Option<Overall>),
@ -1068,6 +1093,7 @@ fn record(
pr: req.pr.unsigned_abs(), pr: req.pr.unsigned_abs(),
requester: req.requester.clone(), requester: req.requester.clone(),
head_sha: head, head_sha: head,
described,
started_unix, started_unix,
finished_unix: unix_now(), finished_unix: unix_now(),
outcome: ended.outcome, outcome: ended.outcome,
@ -1753,6 +1779,15 @@ mod tests {
RunOutcome::ChangesRequested => Overall::RequestChanges, RunOutcome::ChangesRequested => Overall::RequestChanges,
_ => Overall::Approve, _ => Overall::Approve,
}), }),
// read with the fake forge's empty title and description
described: Some(described(&PullForReview {
head_sha: String::new(),
title: String::new(),
description: String::new(),
commits: Vec::new(),
diff: String::new(),
narrowed: None,
})),
..crate::review_classifier::runs::tests::record(id) ..crate::review_classifier::runs::tests::record(id)
}; };
store.record(earlier.clone()).await; store.record(earlier.clone()).await;
@ -1764,6 +1799,7 @@ mod tests {
struct Heads { struct Heads {
fake: Fake, fake: Fake,
head_of: Mutex<std::collections::HashMap<i64, String>>, head_of: Mutex<std::collections::HashMap<i64, String>>,
description_of: Mutex<std::collections::HashMap<i64, String>>,
} }
impl Heads { impl Heads {
@ -1776,9 +1812,18 @@ mod tests {
vec![rules_json()], vec![rules_json()],
), ),
head_of: Mutex::default(), head_of: Mutex::default(),
description_of: Mutex::default(),
} }
} }
/// Edit PR `pr`'s description, as its author does on the forge.
fn describe(&self, pr: i64, description: &str) {
self.description_of
.lock()
.expect("unpoisoned")
.insert(pr, description.to_owned());
}
fn move_to(&self, pr: i64, head: &str) { fn move_to(&self, pr: i64, head: &str) {
self.head_of self.head_of
.lock() .lock()
@ -1801,10 +1846,16 @@ mod tests {
.expect("unpoisoned") .expect("unpoisoned")
.get(&number) .get(&number)
.cloned(); .cloned();
let description = self
.description_of
.lock()
.expect("unpoisoned")
.get(&number)
.cloned();
Ok(PullForReview { Ok(PullForReview {
head_sha: head.unwrap_or_else(|| "abc123".to_owned()), head_sha: head.unwrap_or_else(|| "abc123".to_owned()),
title: String::new(), title: String::new(),
description: String::new(), description: description.unwrap_or_default(),
commits: Vec::new(), commits: Vec::new(),
diff: String::new(), diff: String::new(),
narrowed: None, narrowed: None,
@ -2256,6 +2307,41 @@ mod tests {
assert_eq!(q.rig.gate.reached(), 1, "the re-post ran nothing"); assert_eq!(q.rig.gate.reached(), 1, "the re-post ran nothing");
} }
#[tokio::test]
async fn an_edited_description_makes_the_next_request_a_fresh_run() {
let q = Queued::new().await;
// `abc123` has a verdict on record, read with the empty description.
reviewed(&q.rig.store, "earlier", RunOutcome::ChangesRequested).await;
q.rig.forge.describe(7, "Refs #1");
q.request(7, "abc123").await;
let _consumer = q.consume(&q.rig.reviews);
until("the run reached the classifier", || {
q.rig.gate.reached() == 1
})
.await;
q.rig.gate.open(1);
until("the edited PR is reviewed", || q.rig.posted().len() == 1).await;
assert!(
!q.rig.posted()[0].2.body.starts_with("Already reviewed"),
"the stale verdict was posted again: {}",
q.rig.posted()[0].2.body
);
// Control: a request on that description, which that run recorded,
// posts its verdict again without a run.
accept(
Some(&q.client),
&*q.rig.poster,
&q.rig.store,
&Metrics::off(),
&requested_at("abc123"),
)
.await;
until("the verdict is posted again", || q.rig.posted().len() == 2).await;
assert!(q.rig.posted()[1].2.body.starts_with("Already reviewed"));
assert_eq!(q.rig.gate.reached(), 1, "the re-post ran nothing");
}
#[tokio::test] #[tokio::test]
async fn nothing_is_refused_while_every_run_place_is_taken() { async fn nothing_is_refused_while_every_run_place_is_taken() {
let q = Queued::new().await; let q = Queued::new().await;

View file

@ -92,6 +92,11 @@ pub(crate) struct RunRecord {
/// The commit the run read. Absent when the PR was not read. /// The commit the run read. Absent when the PR was not read.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) head_sha: Option<String>, pub(super) head_sha: Option<String>,
/// A hash of the title and description the run read, which the verdict
/// also depends on. Absent when the PR was not read, and on a run recorded
/// before this was kept.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) described: Option<String>,
/// Unix seconds: a try-out's POST, or a review's start once it had a /// Unix seconds: a try-out's POST, or a review's start once it had a
/// run place. /// run place.
pub(super) started_unix: i64, pub(super) started_unix: i64,
@ -251,12 +256,14 @@ impl Runs {
} }
} }
/// The newest recorded review of `head` on `repo`'s PR `pr`, if any. /// The newest recorded review of `head` on `repo`'s PR `pr`, read with the
/// title and description `described` hashes, if any.
pub(crate) async fn newest_review( pub(crate) async fn newest_review(
&self, &self,
repo: &str, repo: &str,
pr: u64, pr: u64,
head: &str, head: &str,
described: &str,
) -> anyhow::Result<Option<RunRecord>> { ) -> anyhow::Result<Option<RunRecord>> {
let (runs, _) = match self { let (runs, _) = match self {
Self::Live(client) => { Self::Live(client) => {
@ -273,7 +280,8 @@ impl Runs {
if run.trigger == Trigger::Review if run.trigger == Trigger::Review
&& run.repo == repo && run.repo == repo
&& run.pr == pr && run.pr == pr
&& run.head_sha.as_deref() == Some(head) => && run.head_sha.as_deref() == Some(head)
&& run.described.as_deref() == Some(described) =>
{ {
Some(run) Some(run)
} }
@ -468,6 +476,7 @@ pub(crate) mod tests {
pr: 7, pr: 7,
requester: "alice".to_owned(), requester: "alice".to_owned(),
head_sha: Some("abc123".to_owned()), head_sha: Some("abc123".to_owned()),
described: None,
started_unix: 1_000, started_unix: 1_000,
finished_unix: 1_060, finished_unix: 1_060,
outcome: RunOutcome::Done, outcome: RunOutcome::Done,