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
2 changed files with 117 additions and 16 deletions

View file

@ -34,6 +34,7 @@ use async_nats::jetstream::{self, AckKind, consumer::PullConsumer};
use forgejo_api::ForgejoError;
use futures_util::StreamExt as _;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use swarm_wire::review_classifier::{
Overall, REQUEST_CONSUMER, REQUEST_STREAM, REQUEST_SUBJECT_PREFIX, Reply, Row, TryOut, Verdict,
run_deadline,
@ -385,8 +386,14 @@ async fn accept(
let reason = ruling.reason.clone();
let sent = post(poster, request, None, ruling.review()).await;
let ended = ended(RunOutcome::NoVerdict, reason, sent);
runs.record(record(request, None, started_unix, ended, (None, None)))
.await;
runs.record(record(
request,
(None, None),
started_unix,
ended,
(None, None),
))
.await;
}
/// 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"
);
}
let described = pull.as_ref().ok().map(described);
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)
{
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
/// none, nothing is recorded for it, or the store can't be read; each of
/// those leads to a fresh run.
async fn newest_review(runs: &Runs, req: &Requested) -> Option<RunRecord> {
/// A hash of the title and description `pull` was read with: the verdict
/// depends on them as much as on the head, so an edit to either makes the
/// next request a fresh run.
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() {
return None;
}
let repo = format!("{}/{}", req.owner, req.name);
match runs
.newest_review(&repo, req.pr.unsigned_abs(), &req.head)
.newest_review(&repo, req.pr.unsigned_abs(), &req.head, described)
.await
{
Ok(found) => found,
@ -805,7 +829,7 @@ async fn repost(
let sent = post(poster, req, earlier.head_sha.as_deref(), ruling.review()).await;
record(
req,
earlier.head_sha.clone(),
(earlier.head_sha.clone(), earlier.described.clone()),
started_unix,
ended(earlier.outcome, reason, sent),
(earlier.rows.clone(), earlier.overall),
@ -897,6 +921,7 @@ async fn run(
) -> RunRecord {
let started_unix = unix_now();
let timer = Instant::now();
let described = pull.as_ref().ok().map(described);
let (head, narrowed, outcome) = classify(files, pull, sink, req).await;
let mut ruling = review_for(&outcome);
metrics.verdict(verdict_label(ruling.event));
@ -927,7 +952,7 @@ async fn run(
};
let ended = ended(posted_as, reason, sent);
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
@ -1055,7 +1080,7 @@ fn ended(
/// The record of a run on `req` that read `head`.
fn record(
req: &Requested,
head: Option<String>,
(head, described): (Option<String>, Option<String>),
started_unix: i64,
ended: Ended,
(rows, overall): (Option<Vec<Row>>, Option<Overall>),
@ -1068,6 +1093,7 @@ fn record(
pr: req.pr.unsigned_abs(),
requester: req.requester.clone(),
head_sha: head,
described,
started_unix,
finished_unix: unix_now(),
outcome: ended.outcome,
@ -1753,6 +1779,15 @@ mod tests {
RunOutcome::ChangesRequested => Overall::RequestChanges,
_ => 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)
};
store.record(earlier.clone()).await;
@ -1764,6 +1799,7 @@ mod tests {
struct Heads {
fake: Fake,
head_of: Mutex<std::collections::HashMap<i64, String>>,
description_of: Mutex<std::collections::HashMap<i64, String>>,
}
impl Heads {
@ -1776,9 +1812,18 @@ mod tests {
vec![rules_json()],
),
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) {
self.head_of
.lock()
@ -1801,10 +1846,16 @@ mod tests {
.expect("unpoisoned")
.get(&number)
.cloned();
let description = self
.description_of
.lock()
.expect("unpoisoned")
.get(&number)
.cloned();
Ok(PullForReview {
head_sha: head.unwrap_or_else(|| "abc123".to_owned()),
title: String::new(),
description: String::new(),
description: description.unwrap_or_default(),
commits: Vec::new(),
diff: String::new(),
narrowed: None,
@ -2256,6 +2307,41 @@ mod tests {
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]
async fn nothing_is_refused_while_every_run_place_is_taken() {
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.
#[serde(default, skip_serializing_if = "Option::is_none")]
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
/// run place.
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(
&self,
repo: &str,
pr: u64,
head: &str,
described: &str,
) -> anyhow::Result<Option<RunRecord>> {
let (runs, _) = match self {
Self::Live(client) => {
@ -273,7 +280,8 @@ impl Runs {
if run.trigger == Trigger::Review
&& run.repo == repo
&& 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)
}
@ -468,6 +476,7 @@ pub(crate) mod tests {
pr: 7,
requester: "alice".to_owned(),
head_sha: Some("abc123".to_owned()),
described: None,
started_unix: 1_000,
finished_unix: 1_060,
outcome: RunOutcome::Done,