From 4a14ee3882a8fdb1f5780ef7b68161c3c73da14c Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 00:02:05 -0500 Subject: [PATCH 01/32] Fill the Before and After table from the end-to-end run's screenshots CoderHelm's own pull request now shows the screenshots its end-to-end run already took, instead of "No screenshot". - common::e2e::shots reads the images Cucumber JSON embeds, Playwright JSON attaches and Playwright's HTML report keeps under data/, keyed by the test's id, and picks the test that shows the change: one the change edits, one the test map ties to the changed files, or one whose name shares a word with a changed UI file. - e2e_screens keeps that test's screenshot on the head and on the default branch's newest passing run in the install's own bucket, records it for the head and rebuilds the description. - The table links each image through the API with a signed link that works for a year (GET /webhooks/ci/tests/screenshot); the bucket keeps the images 395 days. --- infra/lib/storage-stack.ts | 7 + services/common/src/e2e/mod.rs | 4 + services/common/src/e2e/shots.rs | 867 ++++++++++++++++++ services/common/src/pr_body.rs | 18 +- services/gateway/src/main.rs | 3 + services/gateway/src/routes/tests.rs | 60 ++ services/worker/src/passes/description.rs | 36 +- .../worker/src/passes/description_eval.rs | 1 + services/worker/src/passes/e2e.rs | 22 +- services/worker/src/passes/e2e_screens.rs | 426 +++++++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/test_fix.rs | 24 + 12 files changed, 1464 insertions(+), 5 deletions(-) create mode 100644 services/common/src/e2e/shots.rs create mode 100644 services/worker/src/passes/e2e_screens.rs diff --git a/infra/lib/storage-stack.ts b/infra/lib/storage-stack.ts index e15166b02..b467b1b2c 100644 --- a/infra/lib/storage-stack.ts +++ b/infra/lib/storage-stack.ts @@ -133,6 +133,13 @@ export class StorageStack extends cdk.Stack { expiration: cdk.Duration.days(2), noncurrentVersionExpiration: cdk.Duration.days(1), }, + { + // End-to-end screenshots in pull request descriptions: their links + // work for a year (common::e2e::shots), the images a month longer. + prefix: "e2e-shots/", + expiration: cdk.Duration.days(395), + noncurrentVersionExpiration: cdk.Duration.days(1), + }, { // Move old run artifacts to Infrequent Access after 90 days transitions: [ diff --git a/services/common/src/e2e/mod.rs b/services/common/src/e2e/mod.rs index 80c5ae11b..a6cb7c3c7 100644 --- a/services/common/src/e2e/mod.rs +++ b/services/common/src/e2e/mod.rs @@ -29,6 +29,9 @@ //! request comes from the change, from the page and the code it runs. //! - [`bug_rules`] tells a bug from a flake and holds a bug fix to the app, //! with a unit test, keeping only the changes that matter. +//! - [`shots`] finds the screenshots a report carries for the tests that +//! show a change, for the Before and After table of CoderHelm's own pull +//! request. pub mod attribution; pub mod bug_rules; @@ -47,6 +50,7 @@ pub mod owners; pub mod parse; pub mod quarantine; pub mod report_source; +pub mod shots; pub mod signature; pub mod stats; pub mod store; diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs new file mode 100644 index 000000000..1d323f61b --- /dev/null +++ b/services/common/src/e2e/shots.rs @@ -0,0 +1,867 @@ +//! Screenshots the end-to-end reports already carry, for the Before and +//! After table of CoderHelm's own pull request. +//! +//! A pull request whose whole change was visual showed no screenshot, while +//! the team's end-to-end run on it had taken some. The reports CoderHelm +//! reads (`parse`, `attribution`) keep them: +//! +//! - Cucumber JSON (WebdriverIO, Appium): images embedded in a scenario's +//! steps and hooks, base64 in the report itself; +//! - Playwright JSON: image attachments of a test's result, a file in the +//! run's artifacts (`path`) or the image itself (`body`); +//! - Playwright's HTML report: image attachments under its `data/` folder. +//! +//! [`shots_in`] reads them per test, keyed by the test's id +//! ([`ParsedTest::id`]), and [`pick`] chooses the tests that show the change: +//! a test the change edits, a test the repository's test map ties to the +//! changed files, or a test whose name shares a word with a changed UI file. +//! The worker keeps the images in the install's own bucket +//! ([`object_key`]); the description links them with a signed link +//! ([`sign`]) that the API serves at [`LINK_PATH`] until it expires. + +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::Engine; +use hmac::{Hmac, Mac}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::Sha256; + +use super::coverage::TestMap; +use super::model::{test_id, Framework, Outcome, ParsedTest}; + +/// Largest image kept. +pub const MAX_IMAGE: usize = 5 * 1024 * 1024; +/// Where the images are kept in the install's bucket. +pub const KEY_PREFIX: &str = "e2e-shots"; +/// How long an image link works (the bucket keeps the images a little +/// longer, see `infra/lib/storage-stack.ts`). +pub const LINK_VALID_SECS: i64 = 365 * 86_400; +/// The path the API serves an image at. +pub const LINK_PATH: &str = "/webhooks/ci/tests/screenshot"; +const MAX_TOKEN_LEN: usize = 2048; + +/// One test's screenshot in one report. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Shot { + /// The test's id ([`ParsedTest::id`]). + pub test_id: String, + pub image: Image, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Image { + /// The image itself (a Cucumber embedding, a Playwright `body`). + Inline(Vec), + /// A file of the run, as the report wrote its path. + File(String), +} + +/// The image's type, from its first bytes. Only PNG, JPEG and WebP are +/// kept. +pub fn image_type(bytes: &[u8]) -> Option<&'static str> { + if bytes.starts_with(&[0x89, b'P', b'N', b'G']) { + Some("image/png") + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + Some("image/jpeg") + } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + Some("image/webp") + } else { + None + } +} + +/// The file extension for an image type. +pub fn extension(content_type: &str) -> &'static str { + match content_type { + "image/jpeg" => "jpg", + "image/webp" => "webp", + _ => "png", + } +} + +fn is_image(content_type: &str) -> bool { + matches!( + content_type.trim().to_ascii_lowercase().as_str(), + "image/png" | "image/jpeg" | "image/jpg" | "image/webp" + ) +} + +fn decoded(data: &str) -> Option> { + let clean: String = data.chars().filter(|c| !c.is_whitespace()).collect(); + let bytes = STANDARD.decode(clean).ok()?; + (bytes.len() <= MAX_IMAGE && image_type(&bytes).is_some()).then_some(bytes) +} + +/// The screenshots in one report file, the last one of each test (its last +/// attempt, its final state). Empty when the file is not a report this +/// reads or carries no image. +pub fn shots_in(name: &str, bytes: &[u8]) -> Vec { + if bytes.len() > super::parse::MAX_REPORT_BYTES { + return Vec::new(); + } + let lower = name.to_lowercase(); + let found = if lower.ends_with(".html") { + playwright_html(bytes) + } else if lower.ends_with(".json") { + match serde_json::from_slice::(bytes) { + Ok(v) if v.get("suites").is_some() && v.get("config").is_some() => playwright(&v), + Ok(v) if v + .as_array() + .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => + { + cucumber(&v) + } + _ => Vec::new(), + } + } else { + Vec::new() + }; + last_per_test(found) +} + +fn last_per_test(found: Vec) -> Vec { + let mut out: Vec = Vec::new(); + for s in found { + match out.iter_mut().find(|x| x.test_id == s.test_id) { + Some(x) => *x = s, + None => out.push(s), + } + } + out +} + +// ── Cucumber JSON ───────────────────────────────────────────────────────── + +fn cucumber(report: &Value) -> Vec { + let mut out = Vec::new(); + for feature in report.as_array().into_iter().flatten() { + let file = feature["uri"].as_str().unwrap_or(""); + let feature_name = feature["name"].as_str().unwrap_or(""); + let suite: Vec = if feature_name.is_empty() { + vec![] + } else { + vec![feature_name.to_string()] + }; + for el in feature["elements"].as_array().into_iter().flatten() { + if el["type"].as_str() == Some("background") { + continue; + } + let last = ["before", "steps", "after"] + .iter() + .flat_map(|k| el[*k].as_array().into_iter().flatten()) + .flat_map(|s| s["embeddings"].as_array().into_iter().flatten()) + .filter(|e| { + is_image( + e["mime_type"] + .as_str() + .or_else(|| e["media"]["type"].as_str()) + .unwrap_or(""), + ) + }) + .filter_map(|e| e["data"].as_str().and_then(decoded)) + .last(); + if let Some(bytes) = last { + out.push(Shot { + test_id: test_id( + Framework::Cucumber, + file, + &suite, + el["name"].as_str().unwrap_or(""), + None, + ), + image: Image::Inline(bytes), + }); + } + } + } + out +} + +// ── Playwright ──────────────────────────────────────────────────────────── + +/// The last image attachment of a test's last result. +fn pw_image(results: &Value) -> Option { + let last = results.as_array()?.last()?; + last["attachments"] + .as_array()? + .iter() + .filter(|a| is_image(a["contentType"].as_str().unwrap_or(""))) + .filter_map(|a| match (a["body"].as_str(), a["path"].as_str()) { + (Some(b), _) if !b.is_empty() => decoded(b).map(Image::Inline), + (_, Some(p)) if !p.is_empty() && !p.contains("..") => Some(Image::File(p.to_string())), + _ => None, + }) + .last() +} + +fn project_of(test: &Value) -> Option<&str> { + test["projectName"].as_str().filter(|p| !p.is_empty()) +} + +/// The same walk as `parse::parse_playwright`, so ids match. +fn pw_walk(suite: &Value, path: &mut Vec, out: &mut Vec) { + let title = suite["title"].as_str().unwrap_or(""); + let file = suite["file"].as_str().unwrap_or(""); + let pushed = !title.is_empty() && title != file; + if pushed { + path.push(title.to_string()); + } + for spec in suite["specs"].as_array().into_iter().flatten() { + let spec_file = spec["file"].as_str().unwrap_or(file); + for test in spec["tests"].as_array().into_iter().flatten() { + if let Some(image) = pw_image(&test["results"]) { + out.push(Shot { + test_id: test_id( + Framework::Playwright, + spec_file, + path, + spec["title"].as_str().unwrap_or(""), + project_of(test), + ), + image, + }); + } + } + } + for child in suite["suites"].as_array().into_iter().flatten() { + pw_walk(child, path, out); + } + if pushed { + path.pop(); + } +} + +fn playwright(report: &Value) -> Vec { + let mut out = Vec::new(); + for suite in report["suites"].as_array().into_iter().flatten() { + pw_walk(suite, &mut Vec::new(), &mut out); + } + out +} + +/// The same reading as `parse::parse_playwright_html`, so ids match. The +/// attachments' paths are relative to the report (`data/.png`). +fn playwright_html(bytes: &[u8]) -> Vec { + use std::io::Read; + let Some(zip_bytes) = super::parse::html_report_zip(bytes) else { + return Vec::new(); + }; + let Ok(mut zip) = zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)) else { + return Vec::new(); + }; + let limit = super::parse::MAX_REPORT_BYTES as u64; + let mut read = |name: &str| -> Option { + let f = zip.by_name(name).ok()?; + if f.size() > limit { + return None; + } + let mut buf = Vec::new(); + f.take(limit).read_to_end(&mut buf).ok()?; + serde_json::from_slice(&buf).ok() + }; + let Some(report) = read("report.json") else { + return Vec::new(); + }; + let mut out = Vec::new(); + for summary in report["files"].as_array().into_iter().flatten() { + let Some(file) = summary["fileId"] + .as_str() + .and_then(|id| read(&format!("{id}.json"))) + else { + continue; + }; + let file_name = file["fileName"].as_str().unwrap_or(""); + for t in file["tests"].as_array().into_iter().flatten() { + let Some(image) = pw_image(&t["results"]) else { + continue; + }; + let suite: Vec = t["path"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p.as_str().map(str::to_string)) + .collect(); + out.push(Shot { + test_id: test_id( + Framework::Playwright, + t["location"]["file"].as_str().unwrap_or(file_name), + &suite, + t["title"].as_str().unwrap_or(""), + project_of(t), + ), + image, + }); + } + } + out +} + +/// The run's file an image attachment names. `report` is the report's own +/// name in the run's folder, `names` every file there. A relative path is +/// read next to the report; an absolute one (the runner's disk) is the file +/// whose name ends with the most of its trailing folders, at least the +/// image's own folder: every Playwright test writes `test-finished-1.png`, +/// in a folder of its own. +pub fn resolve(report: &str, path: &str, names: &[String]) -> Option { + let p = path.replace('\\', "/"); + if p.split('/').any(|s| s == "..") { + return None; + } + let absolute = p.starts_with('/') || p.get(1..2) == Some(":"); + if !absolute { + let dir = report + .rsplit_once('/') + .map(|(d, _)| format!("{d}/")) + .unwrap_or_default(); + let near = format!("{dir}{}", p.trim_start_matches("./")); + if names.contains(&near) { + return Some(near); + } + } + let segs: Vec<&str> = p.split('/').filter(|s| !s.is_empty()).collect(); + for k in (2..=segs.len()).rev() { + let tail = segs[segs.len() - k..].join("/"); + if let Some(n) = names + .iter() + .find(|n| **n == tail || n.ends_with(&format!("/{tail}"))) + { + return Some(n.clone()); + } + } + None +} + +// ── Which tests show the change ─────────────────────────────────────────── + +/// Why a test's screenshot is shown for a change. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Why { + /// The change edits the test itself. + TestChanged, + /// The repository's test map ties the test's area to a changed file. + Mapped, + /// The test's name shares this word with a changed UI file. + Named(String), +} + +impl Why { + /// Stronger evidence first. + fn rank(&self) -> u8 { + match self { + Why::TestChanged => 0, + Why::Mapped => 1, + Why::Named(_) => 2, + } + } + + pub fn words(&self) -> String { + match self { + Why::TestChanged => "this change edits the test".into(), + Why::Mapped => "the repository's test map ties it to the changed files".into(), + Why::Named(w) => format!("its name and a changed UI file share the word \"{w}\""), + } + } +} + +/// Folder and file names that say nothing about what a file shows. +const GENERIC: &[&str] = &[ + "src", "app", "apps", "lib", "libs", "packages", "package", "components", "component", + "screens", "screen", "pages", "page", "views", "view", "styles", "style", "index", "main", + "common", "shared", "utils", "util", "hooks", "assets", "features", "feature", "layout", + "layouts", "containers", "container", "modules", "module", "default", "mobile", "native", + "client", "public", "test", "tests", "spec", "specs", "e2e", "ui", "tsx", "jsx", "scss", + "css", "vue", "svelte", "html", "styled", "theme", "types", "button", "text", "item", + "list", "card", "modal", +]; + +/// The words of a path or title: split on anything but letters and digits +/// and at camelCase humps, lowercased, at least four letters, none of +/// [`GENERIC`]. +fn words(s: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut cur = String::new(); + let mut prev_lower = false; + let mut push = |w: &mut String| { + let l = w.to_ascii_lowercase(); + if l.len() >= 4 && !GENERIC.contains(&l.as_str()) && !out.contains(&l) { + out.push(l); + } + w.clear(); + }; + for c in s.chars() { + if !c.is_ascii_alphanumeric() { + push(&mut cur); + prev_lower = false; + continue; + } + if c.is_ascii_uppercase() && prev_lower { + push(&mut cur); + } + prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit(); + cur.push(c); + } + push(&mut cur); + out +} + +fn same_file(a: &str, b: &str) -> bool { + let (a, b) = (a.trim_start_matches("./"), b.trim_start_matches("./")); + !a.is_empty() + && !b.is_empty() + && (a == b || a.ends_with(&format!("/{b}")) || b.ends_with(&format!("/{a}"))) +} + +/// Why `t`'s screenshot shows the change to `changed`, if it does. +pub fn why_shown(t: &ParsedTest, changed: &[String], map: Option<&TestMap>) -> Option { + if changed.iter().any(|f| same_file(f, &t.file)) { + return Some(Why::TestChanged); + } + if map.is_some() && !super::triage::related_changes(t, changed, map).is_empty() { + return Some(Why::Mapped); + } + let named = words(&format!("{} {}", t.full_title(), t.file)); + changed + .iter() + .filter(|f| crate::pr_facts::is_ui(f)) + .flat_map(|f| words(f)) + .find(|w| named.contains(w)) + .map(Why::Named) +} + +/// The tests whose screenshots show the change, best first: the tests that +/// passed in the end, a test the change edits before one the test map +/// names, before one that only shares a word. +pub fn pick<'a>( + tests: &'a [ParsedTest], + changed: &[String], + map: Option<&TestMap>, +) -> Vec<(&'a ParsedTest, Why)> { + let mut out: Vec<(&ParsedTest, Why)> = tests + .iter() + .filter(|t| matches!(Outcome::of(&t.attempts), Outcome::Passed | Outcome::Flaky)) + .filter_map(|t| why_shown(t, changed, map).map(|w| (t, w))) + .collect(); + out.sort_by_key(|(_, w)| w.rank()); + out +} + +// ── What the description shows ──────────────────────────────────────────── + +/// One side of the table: the kept image and the run it came from. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Side { + /// The image's key in the install's bucket. + pub key: String, + /// The run's page; empty for an upload with no run page. + #[serde(default)] + pub run_url: String, +} + +/// The screenshots kept for one head of a pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Kept { + pub pr: u64, + /// The test's full title. + pub test: String, + /// Why this test shows the change ([`Why::words`]). + pub why: String, + /// The branch the Before side was taken on. + pub base: String, + /// The test on the base branch, when a run there kept one. + #[serde(default)] + pub before: Option, + /// The test on the head. + pub after: Side, + /// When the links stop working (unix seconds); fixed when kept, so the + /// description is the same text on every rebuild. + pub expires_at: i64, +} + +fn md_link(text: &str, url: &str) -> String { + if url.starts_with("https://") { + format!("[{text}]({url})") + } else { + text.to_string() + } +} + +/// The table for `k`; `link` gives an image's link from its key. +pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Screens { + let test = k.test.replace('`', "'"); + let base: &str = if k.base.is_empty() { + "the base branch" + } else { + &k.base + }; + let (before, before_alt) = match &k.before { + Some(s) => (link(&s.key), format!("{test} on {base}, before this change")), + None => ( + String::new(), + format!("No screenshot of this test on {base} yet"), + ), + }; + let runs = [ + k.before + .as_ref() + .map(|s| md_link(&format!("{base}'s run"), &s.run_url)), + Some(md_link("this head's run", &k.after.run_url)), + ] + .into_iter() + .flatten() + .collect::>() + .join(", "); + crate::pr_body::Screens::Images { + before, + before_alt, + after: link(&k.after.key), + after_alt: format!("{test} on this head"), + caption: format!( + "From the end-to-end test `{test}` ({runs}), shown because {}.", + k.why.trim_end_matches('.') + ), + } +} + +/// The key an image is kept under in the install's bucket. +pub fn object_key(team: &str, repo: &str, pr: u64, sha: &str, side: &str, ext: &str) -> String { + format!( + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{side}.{ext}", + team_folder(team), + sha.get(..12).unwrap_or(sha) + ) +} + +fn team_folder(team: &str) -> String { + team.replace(['#', '/'], "_") +} + +// ── Signed links ────────────────────────────────────────────────────────── + +type HmacSha256 = Hmac; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TokenError { + Malformed, + BadSignature, + Expired, +} + +fn mac(secret: &str, payload: &str) -> HmacSha256 { + // A key for screenshot links only, so a link never stands in for a + // session or for any other signed link. + let mut kdf = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC takes any key"); + kdf.update(b"coderhelm/e2e-screenshot/v1"); + let key = kdf.finalize().into_bytes(); + let mut m = HmacSha256::new_from_slice(&key).expect("HMAC takes any key"); + m.update(payload.as_bytes()); + m +} + +/// A token that reads one kept image of one team until `expires_at`. The +/// token is `base64url(team \n key \n expiry) . base64url(HMAC-SHA256)`. +pub fn sign(secret: &str, team: &str, key: &str, expires_at: i64) -> String { + let payload = format!("{team}\n{key}\n{expires_at}"); + let sig = mac(secret, &payload).finalize().into_bytes(); + format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(payload.as_bytes()), + URL_SAFE_NO_PAD.encode(sig) + ) +} + +/// The image key a token reads, if it is genuine, current, and names one of +/// its own team's kept images. +pub fn verify(secret: &str, token: &str, now: i64) -> Result { + if token.is_empty() || token.len() > MAX_TOKEN_LEN { + return Err(TokenError::Malformed); + } + let (body, sig) = token.split_once('.').ok_or(TokenError::Malformed)?; + let payload = URL_SAFE_NO_PAD + .decode(body) + .ok() + .and_then(|b| String::from_utf8(b).ok()) + .ok_or(TokenError::Malformed)?; + let sig = URL_SAFE_NO_PAD + .decode(sig) + .map_err(|_| TokenError::Malformed)?; + mac(secret, &payload) + .verify_slice(&sig) + .map_err(|_| TokenError::BadSignature)?; + let p: Vec<&str> = payload.split('\n').collect(); + let [team, key, exp] = p.as_slice() else { + return Err(TokenError::Malformed); + }; + let exp: i64 = exp.parse().map_err(|_| TokenError::Malformed)?; + let own = format!("{KEY_PREFIX}/{}/", team_folder(team)); + if team.is_empty() || !key.starts_with(&own) || key.split('/').any(|s| s == "..") { + return Err(TokenError::Malformed); + } + if now >= exp { + return Err(TokenError::Expired); + } + Ok(key.to_string()) +} + +/// The link for a token on this deployment's API. +pub fn url(api: &str, token: &str) -> String { + format!("{}{LINK_PATH}?t={token}", api.trim_end_matches('/')) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::e2e::model::{Attempt, AttemptStatus}; + use serde_json::json; + + const PNG: &[u8] = &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3]; + + fn b64(b: &[u8]) -> String { + STANDARD.encode(b) + } + + fn ids(report: &str, bytes: &[u8]) -> Vec { + let tests = super::super::parse::parse_any(report, bytes, &Default::default()).unwrap(); + tests.iter().map(ParsedTest::id).collect() + } + + #[test] + fn cucumber_embeddings_give_each_scenario_its_last_image_under_the_test_id() { + let report = json!([{ + "uri": "features/checkout.feature", + "name": "Checkout", + "elements": [ + {"type": "background", "name": "", "steps": [ + {"keyword": "Given ", "name": "signed in", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "image/png", "data": b64(PNG)}]} + ]}, + {"type": "scenario", "name": "Pays by card", "steps": [ + {"keyword": "When ", "name": "pay", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "image/png", "data": b64(b"\x89PNG first")}]}, + {"keyword": "Then ", "name": "paid", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "text/plain", "data": b64(b"log")}]} + ], "after": [ + {"keyword": "After", "result": {"status": "passed"}, + "embeddings": [{"media": {"type": "image/png"}, "data": b64(PNG)}]} + ]}, + {"type": "scenario", "name": "No image", "steps": [ + {"keyword": "When ", "name": "x", "result": {"status": "passed"}} + ]} + ] + }]); + let bytes = serde_json::to_vec(&report).unwrap(); + let shots = shots_in("wdio/cucumber.json", &bytes); + assert_eq!(shots.len(), 1); + assert_eq!(shots[0].image, Image::Inline(PNG.to_vec())); + // The id is the one the parser gives the scenario. + assert!(ids("wdio/cucumber.json", &bytes).contains(&shots[0].test_id)); + } + + #[test] + fn playwright_attachments_are_a_body_or_a_file_of_the_last_attempt() { + let report = json!({ + "config": {}, + "suites": [{"title": "home.spec.ts", "file": "home.spec.ts", "specs": [], "suites": [{ + "title": "Home", "file": "home.spec.ts", + "specs": [ + {"title": "shows the hero", "file": "home.spec.ts", "tests": [{ + "projectName": "chromium", + "results": [ + {"retry": 0, "status": "failed", "attachments": [ + {"name": "screenshot", "contentType": "image/png", "path": "/runner/test-results/home-hero/test-failed-1.png"}]}, + {"retry": 1, "status": "passed", "attachments": [ + {"name": "trace", "contentType": "application/zip", "path": "/runner/test-results/home-hero/trace.zip"}, + {"name": "screenshot", "contentType": "image/png", "path": "/runner/test-results/home-hero/test-finished-1.png"}]} + ]}]}, + {"title": "inline", "file": "home.spec.ts", "tests": [{ + "projectName": "chromium", + "results": [{"retry": 0, "status": "passed", "attachments": [ + {"name": "after", "contentType": "image/png", "body": b64(PNG)}]}]}]} + ] + }]}] + }); + let bytes = serde_json::to_vec(&report).unwrap(); + let shots = shots_in("results.json", &bytes); + assert_eq!(shots.len(), 2); + assert_eq!( + shots[0].image, + Image::File("/runner/test-results/home-hero/test-finished-1.png".into()) + ); + assert_eq!(shots[1].image, Image::Inline(PNG.to_vec())); + let parsed = ids("results.json", &bytes); + assert!(shots.iter().all(|s| parsed.contains(&s.test_id))); + } + + #[test] + fn an_attachment_is_found_next_to_its_report_or_by_its_own_folder() { + let names: Vec = [ + "report/index.html", + "report/data/abc.png", + "results/home-hero/test-finished-1.png", + "results/cart-total/test-finished-1.png", + ] + .map(String::from) + .to_vec(); + assert_eq!( + resolve("report/index.html", "data/abc.png", &names).as_deref(), + Some("report/data/abc.png") + ); + assert_eq!( + resolve( + "results/results.json", + "/home/runner/work/app/test-results/cart-total/test-finished-1.png", + &names + ) + .as_deref(), + Some("results/cart-total/test-finished-1.png") + ); + // The file name alone is every test's; it never decides. + assert_eq!( + resolve("r.json", "/elsewhere/test-finished-1.png", &names), + None + ); + assert_eq!(resolve("r.json", "../secret/a.png", &names), None); + } + + fn passed(file: &str, suite: &[&str], title: &str) -> ParsedTest { + ParsedTest { + framework: Framework::Playwright, + file: file.into(), + suite: suite.iter().map(|s| s.to_string()).collect(), + title: title.into(), + project: None, + tags: vec![], + attempts: vec![Attempt { + retry: 0, + status: AttemptStatus::Passed, + duration_ms: 1, + error: None, + trace_url: None, + video_url: None, + screenshot_url: None, + }], + } + } + + #[test] + fn the_test_the_change_edits_comes_before_one_that_shares_a_word() { + let mut failed = passed("e2e/checkout.spec.ts", &["Checkout"], "fails"); + failed.attempts[0].status = AttemptStatus::Failed; + let tests = vec![ + passed("e2e/home.spec.ts", &["Home"], "shows the hero"), + passed("e2e/checkout.spec.ts", &["Checkout"], "pays by card"), + failed, + passed("e2e/profile.spec.ts", &["Profile"], "edits the name"), + ]; + let changed: Vec = [ + "src/screens/Checkout/PayButton.tsx", + "e2e/profile.spec.ts", + "README.md", + ] + .map(String::from) + .to_vec(); + let picked = pick(&tests, &changed, None); + let titles: Vec<&str> = picked.iter().map(|(t, _)| t.title.as_str()).collect(); + assert_eq!(titles, vec!["edits the name", "pays by card"]); + assert_eq!(picked[0].1, Why::TestChanged); + assert_eq!(picked[1].1, Why::Named("checkout".into())); + } + + #[test] + fn generic_folders_and_non_ui_files_never_match() { + let tests = vec![passed("e2e/screens.spec.ts", &["Components"], "index page")]; + let changed: Vec = ["src/components/index.tsx", "src/api/screens.ts"] + .map(String::from) + .to_vec(); + assert!(pick(&tests, &changed, None).is_empty()); + } + + #[test] + fn words_split_camel_case_and_drop_short_and_generic_ones() { + assert_eq!( + words("src/screens/CheckoutSummary/PayButton.tsx"), + vec!["checkout", "summary"] + ); + } + + #[test] + fn the_table_names_the_test_its_runs_and_why() { + let k = Kept { + pr: 7, + test: "Checkout › pays by `card`".into(), + why: Why::Named("checkout".into()).words(), + base: "main".into(), + before: Some(Side { + key: "e2e-shots/T/o/r/7/abc/before.png".into(), + run_url: "https://github.com/o/r/actions/runs/1".into(), + }), + after: Side { + key: "e2e-shots/T/o/r/7/abc/after.png".into(), + run_url: "https://github.com/o/r/actions/runs/2".into(), + }, + expires_at: 10, + }; + let s = screens(&k, |key| format!("https://api.example.com/x?k={key}")); + let crate::pr_body::Screens::Images { + before, + after, + caption, + after_alt, + .. + } = s + else { + panic!("images"); + }; + assert!(before.ends_with("before.png")); + assert!(after.ends_with("after.png")); + assert_eq!(after_alt, "Checkout › pays by 'card' on this head"); + assert_eq!( + caption, + "From the end-to-end test `Checkout › pays by 'card'` ([main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)), shown because its name and a changed UI file share the word \"checkout\"." + ); + let none = screens( + &Kept { + before: None, + ..k.clone() + }, + |key| key.to_string(), + ); + let crate::pr_body::Screens::Images { + before, before_alt, .. + } = none + else { + panic!("images"); + }; + assert!(before.is_empty()); + assert_eq!(before_alt, "No screenshot of this test on main yet"); + } + + #[test] + fn a_link_reads_one_image_of_its_own_team_until_it_expires() { + let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "after", "png"); + assert_eq!(key, "e2e-shots/TEAM_a/o/r/7/0123456789ab/after.png"); + let t = sign("s", "TEAM#a", &key, 100); + assert_eq!(verify("s", &t, 99), Ok(key.clone())); + assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); + assert_eq!(verify("other", &t, 99), Err(TokenError::BadSignature)); + // Signed, but for another team's image or anything else in the bucket. + let theirs = sign("s", "TEAM#a", "e2e-shots/TEAM_b/o/r/1/x/after.png", 100); + assert_eq!(verify("s", &theirs, 99), Err(TokenError::Malformed)); + let raw = sign("s", "TEAM#a", "e2e/TEAM_a/o/r/raw/1-1/report.json", 100); + assert_eq!(verify("s", &raw, 99), Err(TokenError::Malformed)); + let up = sign("s", "TEAM#a", "e2e-shots/TEAM_a/../../secret", 100); + assert_eq!(verify("s", &up, 99), Err(TokenError::Malformed)); + // An unsubscribe token never reads an image. + let u = crate::unsubscribe::sign("s", "TEAM#a", "USER#1", "weekly_summary", 100); + assert!(verify("s", &u, 99).is_err()); + assert!(url("https://api.example.com/", &t) + .starts_with("https://api.example.com/webhooks/ci/tests/screenshot?t=")); + } + + #[test] + fn only_real_images_are_kept() { + assert_eq!(image_type(PNG), Some("image/png")); + assert_eq!(image_type(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg")); + assert_eq!(image_type(b""), None); + assert_eq!(decoded(&b64(b"")), None); + } +} diff --git a/services/common/src/pr_body.rs b/services/common/src/pr_body.rs index cb48d18d1..155299690 100644 --- a/services/common/src/pr_body.rs +++ b/services/common/src/pr_body.rs @@ -218,11 +218,16 @@ impl Row { /// The screenshots of a UI change, or why there are none. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum Screens { + /// One Before and After pair. An empty `before` is a side with no + /// image: its cell says `before_alt` instead. Images { before: String, before_alt: String, after: String, after_alt: String, + /// One line under the table: where the images came from. + #[serde(default)] + caption: String, }, /// One line: why there is no screenshot. Missing(String), @@ -732,19 +737,28 @@ fn screens_markdown(s: &Screens) -> String { before_alt, after, after_alt, + caption, } => { let img = |src: &str, alt: &str| { + if src.trim().is_empty() { + return cell(&one_line(alt)); + } format!( "\"{}\"", src.replace('"', "%22"), one_line(alt).replace('"', "'") ) }; - format!( + let mut s = format!( "| Before | After |\n|---|---|\n| {} | {} |", img(before, before_alt), img(after, after_alt) - ) + ); + let caption = one_line(caption); + if !caption.is_empty() { + s.push_str(&format!("\n\n{caption}")); + } + s } Screens::Missing(why) => format!("No screenshot: {}.", part(why)), } diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 031a55666..9ce6acf30 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1583,6 +1583,9 @@ fn build_app(state: Arc) -> Router { // CI calls signed with a GitHub Actions OIDC token .route("/ci/tests/results", post(routes::tests::ci_upload)) .route("/ci/tests/quarantine", get(routes::tests::ci_quarantine)) + // A screenshot in the Before and After table of CoderHelm's own pull + // request; the signed link is the credential (routes::tests). + .route("/ci/tests/screenshot", get(routes::tests::ci_screenshot)) // Events CoderHelm's relay forwards to a hybrid install, and its // ownership proof (routes::hybrid_install). .route("/relay", post(routes::hybrid_install::intake)) diff --git a/services/gateway/src/routes/tests.rs b/services/gateway/src/routes/tests.rs index 44bdbb1a9..4fec457c2 100644 --- a/services/gateway/src/routes/tests.rs +++ b/services/gateway/src/routes/tests.rs @@ -1382,6 +1382,66 @@ pub async fn ci_quarantine( })) } +#[derive(Deserialize)] +pub struct ShotQuery { + #[serde(default)] + t: String, +} + +/// GET /webhooks/ci/tests/screenshot?t= — one end-to-end screenshot kept for +/// the Before and After table of CoderHelm's own pull request +/// (`common::e2e::shots`). Public, because GitHub fetches the image for the +/// pull request's readers: the signed token is the credential, and it names +/// one image of one team until it expires. Anything else is a 404 that says +/// nothing. +pub async fn ci_screenshot( + State(state): State>, + Query(q): Query, +) -> axum::response::Response { + use axum::http::header; + use axum::response::IntoResponse; + use common::e2e::shots; + let not_found = || (StatusCode::NOT_FOUND, "Not found").into_response(); + let secret = state.secrets.jwt_secret.as_str(); + if secret.is_empty() { + return not_found(); + } + let key = match shots::verify(secret, q.t.trim(), chrono::Utc::now().timestamp()) { + Ok(k) => k, + Err(e) => { + info!(reason = ?e, "Screenshot link refused"); + return not_found(); + } + }; + let Ok(obj) = state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(&key) + .send() + .await + else { + return not_found(); + }; + let Ok(body) = obj.body.collect().await else { + return not_found(); + }; + let bytes = body.into_bytes(); + let Some(content_type) = shots::image_type(&bytes) else { + return not_found(); + }; + ( + StatusCode::OK, + [ + (header::CONTENT_TYPE, content_type), + (header::CACHE_CONTROL, "public, max-age=86400"), + (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), + ], + bytes, + ) + .into_response() +} + #[cfg(test)] mod unit { use super::*; diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 8d9a32dc0..f5dfad71d 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -410,6 +410,25 @@ pub async fn rebuild( .await } +/// [`rebuild`] for a pull request, its ticket read from the run that opened +/// it: something its description shows arrived on the same head (the +/// screenshots of the end-to-end run, `e2e_screens`). +pub async fn rebuild_pr( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, +) -> Reconciled { + let ticket = match super::review_pr::lookup_run_by_pr(state, team_id, owner, repo, number).await + { + Some(run_id) => run_ticket(state, team_id, &run_id).await, + None => String::new(), + }; + rebuild(state, github, team_id, owner, repo, number, &ticket).await +} + /// What was read about a pull request for one build. struct Gathered { pr: serde_json::Value, @@ -418,6 +437,9 @@ struct Gathered { checks: Option>, run: RunBits, run_url: String, + /// The Before and After table the end-to-end run on the head filled + /// (`e2e_screens`). + screens: Option, } /// What the run behind a pull request holds for its description. @@ -466,7 +488,7 @@ impl Gathered { title: self.run.title.clone(), url: self.run.ticket_url.clone(), }); - super::description_facts::facts(&super::description_facts::Inputs { + let mut facts = super::description_facts::facts(&super::description_facts::Inputs { head: self.head(), body, files: &self.files, @@ -490,7 +512,11 @@ impl Gathered { .into_iter() .collect(), repo_url: self.pr["base"]["repo"]["html_url"].as_str().unwrap_or(""), - }) + }); + if self.screens.is_some() { + facts.screens = self.screens.clone(); + } + facts } } @@ -595,6 +621,11 @@ async fn gather( } else { format!("{app}/runs/detail?id={run_id}") }; + let screens = if head.is_empty() { + None + } else { + super::e2e_screens::screens_for(state, team_id, &format!("{owner}/{repo}"), &head).await + }; Ok(Gathered { pr, files, @@ -602,6 +633,7 @@ async fn gather( checks, run, run_url, + screens, }) } diff --git a/services/worker/src/passes/description_eval.rs b/services/worker/src/passes/description_eval.rs index 63c78d843..541d94892 100644 --- a/services/worker/src/passes/description_eval.rs +++ b/services/worker/src/passes/description_eval.rs @@ -680,6 +680,7 @@ pub fn ui_facts() -> Facts { before_alt: "Sub Title field with a 190-character subtitle and no warning".into(), after: "https://github.com/user-attachments/assets/after-example".into(), after_alt: "Same field showing the warning 'Over 160 characters (190)'".into(), + caption: String::new(), }), run_url: "https://app.example.com/runs/detail?id=run-4812".into(), repo_url: "https://github.com/acme/site".into(), diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index b206cdf11..22e1e98c2 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -622,10 +622,30 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { if run.rescued { note_rescued(&st, &gh, &msg, &run, pr).await; } + let own = is_own_pr(&gh, &msg, pr).await; // A run that failed only on quarantined tests needs no fix or re-run. - if failed > 0 && !run.rescued && is_own_pr(&gh, &msg, pr).await { + if failed > 0 && !run.rescued && own { own_pr_failures(state, &gh, &msg, &run, pr, &lines, &tests).await; } + // CoderHelm's own pull request shows the screenshots this run took + // of the tests its change touches. + if own { + super::e2e_screens::keep( + state, + &gh, + &st, + super::e2e_screens::Head { + msg: &msg, + pr, + tests: &tests, + reports: &reports, + changed: &changed, + map: map.as_ref(), + }, + |t| scoped_id(&repo, t), + ) + .await; + } recommend_from_pr(state, &gh, &msg, pr, &changed, map.as_ref()).await; follow_generated(state, &gh, &msg, &run, &tests).await; } diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs new file mode 100644 index 000000000..4bc649b14 --- /dev/null +++ b/services/worker/src/passes/e2e_screens.rs @@ -0,0 +1,426 @@ +//! The Before and After table of CoderHelm's own pull request, filled from +//! the screenshots its end-to-end run took (the rules are +//! `common::e2e::shots`). +//! +//! When a run on the pull request's head is read (`e2e::ingest`), the +//! tests that show the change are chosen ([`shots::pick`]), and the first +//! one with a screenshot on the head is kept with its screenshot from the +//! newest passing run on the default branch, when one is kept there too. +//! The images go to the install's own bucket, the record to the settings +//! table for the head, and the description is rebuilt: its table links each +//! image through the API with a signed link that expires +//! ([`screens_for`]). A head keeps the first pair found; a later run on the +//! same head changes nothing. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::e2e::coverage::TestMap; +use common::e2e::messages::TestIngest; +use common::e2e::model::{Outcome, ParsedTest}; +use common::e2e::report_source::Location; +use common::e2e::shots::{self, Image, Kept, Side}; +use common::e2e::store::Store; +use tracing::{info, warn}; + +use super::test_fix::{CiReports, KeptRun, Reports, S3Reports}; +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// Tests tried for a screenshot on the head. +const MAX_TRIED: usize = 3; +/// How long the record of a head is kept. +const RECORD_DAYS: i64 = 90; + +fn record_sk(repo: &str, sha: &str) -> String { + format!("E2E_SHOTS#{repo}#{sha}") +} + +pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> Option { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&record_sk(repo, sha))) + .send() + .await + .ok()? + .item?; + serde_json::from_str(item.get("data")?.as_s().ok()?).ok() +} + +async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) { + let ttl = (chrono::Utc::now() + chrono::Duration::days(RECORD_DAYS)).timestamp(); + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", super::attr_s(team_id)) + .item("sk", super::attr_s(&record_sk(repo, sha))) + .item( + "data", + super::attr_s(&serde_json::to_string(k).unwrap_or_default()), + ) + .item("ttl", AttributeValue::N(ttl.to_string())) + .send() + .await + { + warn!(error = %e, "Could not save the end-to-end screenshots of a head"); + } +} + +/// The Before and After table for a pull request's head, when a run on it +/// kept screenshots. `None` without a signing secret or a public API +/// address: GitHub fetches the images from the API, so a link must reach +/// it. +pub async fn screens_for( + state: &WorkerState, + team_id: &str, + repo: &str, + sha: &str, +) -> Option { + let secret = state.secrets.jwt_secret.as_str(); + let api = common::public_urls::api_url(&state.config.stage); + if secret.is_empty() || !api.starts_with("https://") { + return None; + } + let k = load(state, team_id, repo, sha).await?; + Some(shots::screens(&k, |key| { + shots::url(api, &shots::sign(secret, team_id, key, k.expires_at)) + })) +} + +/// Report files held in memory: an uploaded report, or the raw reports kept +/// in the install's bucket for an upload. +struct Held(Vec<(String, Vec)>); + +#[async_trait::async_trait] +impl Reports for Held { + fn label(&self, _run_id: u64, _attempt: u32) -> String { + "the uploaded report".into() + } + + async fn runs(&self) -> Vec { + Vec::new() + } + + async fn reports(&self, _run_id: u64, _attempt: u32) -> Result)>, String> { + Ok(self.0.clone()) + } + + async fn file(&self, _run_id: u64, _attempt: u32, path: &str) -> Option> { + self.0 + .iter() + .find(|(n, _)| n == path) + .map(|(_, b)| b.clone()) + } + + async fn names(&self, _run_id: u64, _attempt: u32) -> Vec { + self.0.iter().map(|(n, _)| n.clone()).collect() + } +} + +/// Where one run's reports are read. +enum Source<'a> { + Held(Held), + S3(Box), + Ci(CiReports<'a>), +} + +impl Source<'_> { + fn reports(&self) -> &dyn Reports { + match self { + Source::Held(r) => r, + Source::S3(r) => r.as_ref(), + Source::Ci(r) => r, + } + } +} + +/// The raw reports kept in the install's bucket for an uploaded run +/// (`e2e::ingest` keeps them within a budget). +async fn kept_raw(state: &WorkerState, team_id: &str, repo: &str, run_key: &str) -> Held { + let marker = common::e2e::store::raw_report_key(team_id, repo, run_key, "x"); + let prefix = marker.trim_end_matches('x').to_string(); + let mut out = Vec::new(); + let Ok(listed) = state + .s3 + .list_objects_v2() + .bucket(&state.config.bucket_name) + .prefix(&prefix) + .max_keys(20) + .send() + .await + else { + return Held(out); + }; + for o in listed.contents() { + let (Some(key), size) = (o.key(), o.size().unwrap_or(0)) else { + continue; + }; + if size < 0 || size as usize > common::e2e::parse::MAX_REPORT_BYTES { + continue; + } + let Ok(obj) = state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(key) + .send() + .await + else { + continue; + }; + if let Ok(body) = obj.body.collect().await { + let name = key.strip_prefix(&prefix).unwrap_or(key).to_string(); + out.push((name, body.into_bytes().to_vec())); + } + } + Held(out) +} + +/// `{run_id}-{attempt}`, the key of a run read from GitHub. +fn run_of(run_key: &str) -> Option<(u64, u32)> { + let (run, attempt) = run_key.split_once('-')?; + Some((run.parse().ok()?, attempt.parse().ok()?)) +} + +/// The screenshots of `wanted` (test ids) in one run, by test id. +async fn images( + r: &dyn Reports, + run_id: u64, + attempt: u32, + wanted: &[String], +) -> HashMap> { + let mut out = HashMap::new(); + let Ok(files) = r.reports(run_id, attempt).await else { + return out; + }; + let mut names: Option> = None; + for (name, bytes) in &files { + for s in shots::shots_in(name, bytes) { + if !wanted.contains(&s.test_id) { + continue; + } + let image = match s.image { + Image::Inline(b) => Some(b), + Image::File(p) => { + if names.is_none() { + names = Some(r.names(run_id, attempt).await); + } + match shots::resolve(name, &p, names.as_deref().unwrap_or_default()) { + Some(n) => r.file(run_id, attempt, &n).await, + None => None, + } + } + }; + if let Some(b) = + image.filter(|b| b.len() <= shots::MAX_IMAGE && shots::image_type(b).is_some()) + { + out.insert(s.test_id, b); + } + } + } + out +} + +/// Keeps one image in the install's bucket; its key. +async fn put(state: &WorkerState, key_of: impl Fn(&str) -> String, bytes: Vec) -> Option { + let content_type = shots::image_type(&bytes)?; + let key = key_of(shots::extension(content_type)); + match state + .s3 + .put_object() + .bucket(&state.config.bucket_name) + .key(&key) + .content_type(content_type) + .body(bytes.into()) + .send() + .await + { + Ok(_) => Some(key), + Err(e) => { + warn!(error = %e, "Could not keep an end-to-end screenshot"); + None + } + } +} + +/// Everything a run on a pull request's head brings for its table. +pub struct Head<'a> { + pub msg: &'a TestIngest, + pub pr: u64, + pub tests: &'a [ParsedTest], + /// The reports this run was read from (an upload's report). + pub reports: &'a [(String, Vec)], + /// The files the pull request changes. + pub changed: &'a [String], + pub map: Option<&'a TestMap>, +} + +/// Keeps the screenshots that show the change of CoderHelm's own pull +/// request from one run on its head, and rebuilds its description with +/// them. `scoped` is a test's id in the store. +pub async fn keep( + state: &WorkerState, + gh: &GitHubClient, + st: &Store<'_>, + h: Head<'_>, + scoped: impl Fn(&ParsedTest) -> String, +) { + let msg = h.msg; + let (owner, name) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); + let repo = format!("{owner}/{name}"); + if state.secrets.jwt_secret.is_empty() || msg.head_sha.is_empty() { + return; + } + let picked = shots::pick(h.tests, h.changed, h.map); + if picked.is_empty() || load(state, &msg.team_id, &repo, &msg.head_sha).await.is_some() { + return; + } + let location = st + .settings(&msg.team_id) + .await + .ok() + .and_then(|s| s.report_source(&repo).and_then(|r| r.location().ok())); + let location = location.as_ref(); + // Where the team keeps the repository's reports, else the run's + // artifacts: the same places the failure attribution reads. + let open = |run_id: u64| async move { + if let Some(l @ Location::S3 { .. }) = location { + let mut tried = Vec::new(); + if let Some(r) = super::test_fix::open_s3(state, &msg.team_id, l, &mut tried).await { + return Source::S3(Box::new(r)); + } + } + Source::Ci(CiReports::new(gh, owner, name, vec![(run_id, 1)])) + }; + // The head's run. + let head = if msg.upload_key.is_some() { + Source::Held(Held(h.reports.to_vec())) + } else { + open(msg.run_id).await + }; + let tried: Vec<&(&ParsedTest, shots::Why)> = picked.iter().take(MAX_TRIED).collect(); + let ids: Vec = tried.iter().map(|(t, _)| t.id()).collect(); + let mut after = images(head.reports(), msg.run_id, msg.run_attempt, &ids).await; + let Some((t, why, after_bytes)) = tried + .into_iter() + .find_map(|(t, w)| after.remove(&t.id()).map(|b| (*t, w, b))) + else { + info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); + return; + }; + // The same test on the default branch: its newest passing run there. + let newest = st + .record(&msg.team_id, &scoped(t)) + .await + .ok() + .flatten() + .and_then(|r| { + r.history.into_iter().rev().find(|e| { + e.branch == msg.default_branch + && !e.bad_run + && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) + }) + }); + let mut before: Option<(Vec, String)> = None; + if let Some(e) = newest { + let (src, run_id, attempt, run_url) = if e.run_key.starts_with("up-") { + ( + Source::Held(kept_raw(state, &msg.team_id, &repo, &e.run_key).await), + 0, + 1, + String::new(), + ) + } else if let Some((run_id, attempt)) = run_of(&e.run_key) { + ( + open(run_id).await, + run_id, + attempt, + format!("https://github.com/{repo}/actions/runs/{run_id}"), + ) + } else { + (Source::Held(Held(Vec::new())), 0, 1, String::new()) + }; + before = images(src.reports(), run_id, attempt, &[t.id()]) + .await + .remove(&t.id()) + .map(|b| (b, run_url)); + } + let key_of = |side: &'static str| { + let (team, pr, sha) = (msg.team_id.clone(), h.pr, msg.head_sha.clone()); + let repo = repo.clone(); + move |ext: &str| shots::object_key(&team, &repo, pr, &sha, side, ext) + }; + let Some(after_key) = put(state, key_of("after"), after_bytes).await else { + return; + }; + let before = match before { + Some((b, run_url)) => put(state, key_of("before"), b) + .await + .map(|key| Side { key, run_url }), + None => None, + }; + let kept = Kept { + pr: h.pr, + test: t.full_title(), + why: why.words(), + base: msg.default_branch.clone(), + before, + after: Side { + key: after_key, + run_url: msg.html_url.clone(), + }, + expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, + }; + save(state, &msg.team_id, &repo, &msg.head_sha, &kept).await; + info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); + if let super::description::Reconciled::Failed(why) = + super::description::rebuild_pr(state, gh, &msg.team_id, owner, name, h.pr).await + { + warn!(repo = %repo, pr = h.pr, why, "The description was not rebuilt with the screenshots; the next rebuild shows them"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_github_run_key_names_its_run_and_attempt() { + assert_eq!(run_of("123-2"), Some((123, 2))); + assert_eq!(run_of("up-1-1-abcdef"), None); + assert_eq!(run_of("nope"), None); + } + + #[tokio::test] + async fn an_attachment_is_read_from_the_file_its_report_names() { + let png = vec![0x89, b'P', b'N', b'G', 0, 1]; + let report = serde_json::json!({ + "config": {}, + "suites": [{"title": "a.spec.ts", "file": "a.spec.ts", "specs": [ + {"title": "shows it", "file": "a.spec.ts", "tests": [{"results": [ + {"status": "passed", "attachments": [ + {"name": "screenshot", "contentType": "image/png", + "path": "/runner/work/test-results/a-shows-it/test-finished-1.png"}]}]}]} + ]}] + }); + let held = Held(vec![ + ("pw/results.json".into(), serde_json::to_vec(&report).unwrap()), + ("pw/test-results/a-shows-it/test-finished-1.png".into(), png.clone()), + ]); + let tests = common::e2e::parse::parse_any( + "results.json", + &serde_json::to_vec(&report).unwrap(), + &Default::default(), + ) + .unwrap(); + let id = tests[0].id(); + let got = images(&held, 1, 1, &[id.clone()]).await; + assert_eq!(got.get(&id), Some(&png)); + // A test nobody asked for is not read. + assert!(images(&held, 1, 1, &["other".into()]).await.is_empty()); + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index f3cf96975..3cd1a2a29 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1274,6 +1274,7 @@ pub mod description_facts; pub mod dlq_cleanup; pub mod e2e; pub mod e2e_attribution; +pub mod e2e_screens; pub mod e2e_setup; pub mod email_events; pub mod feature; diff --git a/services/worker/src/passes/test_fix.rs b/services/worker/src/passes/test_fix.rs index bdc15a028..9e17506d7 100644 --- a/services/worker/src/passes/test_fix.rs +++ b/services/worker/src/passes/test_fix.rs @@ -367,6 +367,12 @@ pub trait Reports: Send + Sync { async fn reports(&self, run_id: u64, attempt: u32) -> Result)>, String>; /// One file of the run's folder (an attachment of an HTML report). async fn file(&self, run_id: u64, attempt: u32, path: &str) -> Option>; + /// Every file of the run's folder, by the path [`Reports::file`] + /// reads: where a report's attachment is found when the report wrote + /// the runner's own path (`e2e_screens`). + async fn names(&self, _run_id: u64, _attempt: u32) -> Vec { + Vec::new() + } } /// What one run's reports say. @@ -694,6 +700,17 @@ impl Reports for S3Reports { .map(|(_, s, _)| *s)?; self.get(&key, size).await } + + async fn names(&self, run_id: u64, attempt: u32) -> Vec { + let attempt = self.attempt_for(run_id, attempt); + let prefix = self.run_prefix(run_id, attempt); + self.index + .get(&(run_id, attempt)) + .into_iter() + .flatten() + .map(|(k, _, _)| k.strip_prefix(&prefix).unwrap_or(k).to_string()) + .collect() + } } /// Reports in a run's GitHub Actions artifacts. @@ -837,6 +854,13 @@ impl Reports for CiReports<'_> { .find(|(n, _)| n == path) .map(|(_, b)| b) } + + async fn names(&self, run_id: u64, _attempt: u32) -> Vec { + self.files(run_id) + .await + .map(|f| f.into_iter().map(|(n, _)| n).collect()) + .unwrap_or_default() + } } /// The team's AWS session that can read `location`: the first connected From fd67586bc1302404f045ba5ed2b7ef719bbd1da4 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:50:44 -0500 Subject: [PATCH 02/32] Say why a screenshot's test was picked, and pass clippy The reason names the test, not only its name (the match reads its title and file); an empty Before cell says no passing run on the base kept one rather than "yet"; the caption gives the reason before the run links. Formatted, and two iterator and one slice lint fixed. --- services/common/src/e2e/shots.rs | 95 ++++++++++++++++++----- services/worker/src/passes/e2e_screens.rs | 24 ++++-- 2 files changed, 96 insertions(+), 23 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 1d323f61b..0068f2a6f 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -105,9 +105,9 @@ pub fn shots_in(name: &str, bytes: &[u8]) -> Vec { } else if lower.ends_with(".json") { match serde_json::from_slice::(bytes) { Ok(v) if v.get("suites").is_some() && v.get("config").is_some() => playwright(&v), - Ok(v) if v - .as_array() - .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => + Ok(v) + if v.as_array() + .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => { cucumber(&v) } @@ -159,7 +159,7 @@ fn cucumber(report: &Value) -> Vec { ) }) .filter_map(|e| e["data"].as_str().and_then(decoded)) - .last(); + .next_back(); if let Some(bytes) = last { out.push(Shot { test_id: test_id( @@ -191,7 +191,7 @@ fn pw_image(results: &Value) -> Option { (_, Some(p)) if !p.is_empty() && !p.contains("..") => Some(Image::File(p.to_string())), _ => None, }) - .last() + .next_back() } fn project_of(test: &Value) -> Option<&str> { @@ -358,20 +358,73 @@ impl Why { match self { Why::TestChanged => "this change edits the test".into(), Why::Mapped => "the repository's test map ties it to the changed files".into(), - Why::Named(w) => format!("its name and a changed UI file share the word \"{w}\""), + Why::Named(w) => format!("the test and a changed UI file share the word \"{w}\""), } } } /// Folder and file names that say nothing about what a file shows. const GENERIC: &[&str] = &[ - "src", "app", "apps", "lib", "libs", "packages", "package", "components", "component", - "screens", "screen", "pages", "page", "views", "view", "styles", "style", "index", "main", - "common", "shared", "utils", "util", "hooks", "assets", "features", "feature", "layout", - "layouts", "containers", "container", "modules", "module", "default", "mobile", "native", - "client", "public", "test", "tests", "spec", "specs", "e2e", "ui", "tsx", "jsx", "scss", - "css", "vue", "svelte", "html", "styled", "theme", "types", "button", "text", "item", - "list", "card", "modal", + "src", + "app", + "apps", + "lib", + "libs", + "packages", + "package", + "components", + "component", + "screens", + "screen", + "pages", + "page", + "views", + "view", + "styles", + "style", + "index", + "main", + "common", + "shared", + "utils", + "util", + "hooks", + "assets", + "features", + "feature", + "layout", + "layouts", + "containers", + "container", + "modules", + "module", + "default", + "mobile", + "native", + "client", + "public", + "test", + "tests", + "spec", + "specs", + "e2e", + "ui", + "tsx", + "jsx", + "scss", + "css", + "vue", + "svelte", + "html", + "styled", + "theme", + "types", + "button", + "text", + "item", + "list", + "card", + "modal", ]; /// The words of a path or title: split on anything but letters and digits @@ -494,10 +547,13 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree &k.base }; let (before, before_alt) = match &k.before { - Some(s) => (link(&s.key), format!("{test} on {base}, before this change")), + Some(s) => ( + link(&s.key), + format!("{test} on {base}, before this change"), + ), None => ( String::new(), - format!("No screenshot of this test on {base} yet"), + format!("No screenshot of this test from a passing run on {base}"), ), }; let runs = [ @@ -516,7 +572,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree after: link(&k.after.key), after_alt: format!("{test} on this head"), caption: format!( - "From the end-to-end test `{test}` ({runs}), shown because {}.", + "Screenshots of the end-to-end test `{test}`, chosen because {}: {runs}.", k.why.trim_end_matches('.') ), } @@ -816,7 +872,7 @@ mod tests { assert_eq!(after_alt, "Checkout › pays by 'card' on this head"); assert_eq!( caption, - "From the end-to-end test `Checkout › pays by 'card'` ([main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)), shown because its name and a changed UI file share the word \"checkout\"." + "Screenshots of the end-to-end test `Checkout › pays by 'card'`, chosen because the test and a changed UI file share the word \"checkout\": [main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)." ); let none = screens( &Kept { @@ -832,7 +888,10 @@ mod tests { panic!("images"); }; assert!(before.is_empty()); - assert_eq!(before_alt, "No screenshot of this test on main yet"); + assert_eq!( + before_alt, + "No screenshot of this test from a passing run on main" + ); } #[test] diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 4bc649b14..5c339c2d3 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -226,7 +226,11 @@ async fn images( } /// Keeps one image in the install's bucket; its key. -async fn put(state: &WorkerState, key_of: impl Fn(&str) -> String, bytes: Vec) -> Option { +async fn put( + state: &WorkerState, + key_of: impl Fn(&str) -> String, + bytes: Vec, +) -> Option { let content_type = shots::image_type(&bytes)?; let key = key_of(shots::extension(content_type)); match state @@ -276,7 +280,11 @@ pub async fn keep( return; } let picked = shots::pick(h.tests, h.changed, h.map); - if picked.is_empty() || load(state, &msg.team_id, &repo, &msg.head_sha).await.is_some() { + if picked.is_empty() + || load(state, &msg.team_id, &repo, &msg.head_sha) + .await + .is_some() + { return; } let location = st @@ -408,8 +416,14 @@ mod tests { ]}] }); let held = Held(vec![ - ("pw/results.json".into(), serde_json::to_vec(&report).unwrap()), - ("pw/test-results/a-shows-it/test-finished-1.png".into(), png.clone()), + ( + "pw/results.json".into(), + serde_json::to_vec(&report).unwrap(), + ), + ( + "pw/test-results/a-shows-it/test-finished-1.png".into(), + png.clone(), + ), ]); let tests = common::e2e::parse::parse_any( "results.json", @@ -418,7 +432,7 @@ mod tests { ) .unwrap(); let id = tests[0].id(); - let got = images(&held, 1, 1, &[id.clone()]).await; + let got = images(&held, 1, 1, std::slice::from_ref(&id)).await; assert_eq!(got.get(&id), Some(&png)); // A test nobody asked for is not read. assert!(images(&held, 1, 1, &["other".into()]).await.is_empty()); From 2bfc0064b76c7f0b062362f2f85ea48745781504 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:57:40 -0500 Subject: [PATCH 03/32] no-mistakes(review): Claim head record, use PR base, align record TTL --- services/common/src/e2e/shots.rs | 89 ++++++++++++++-- services/worker/src/passes/e2e_screens.rs | 124 ++++++++++++++-------- 2 files changed, 159 insertions(+), 54 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 0068f2a6f..d05e6cb43 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -24,10 +24,10 @@ use base64::Engine; use hmac::{Hmac, Mac}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use sha2::Sha256; +use sha2::{Digest, Sha256}; use super::coverage::TestMap; -use super::model::{test_id, Framework, Outcome, ParsedTest}; +use super::model::{test_id, Framework, HistoryEntry, Outcome, ParsedTest}; /// Largest image kept. pub const MAX_IMAGE: usize = 5 * 1024 * 1024; @@ -553,7 +553,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree ), None => ( String::new(), - format!("No screenshot of this test from a passing run on {base}"), + format!("No passing run on {base} with a screenshot of this test yet"), ), }; let runs = [ @@ -578,12 +578,31 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree } } -/// The key an image is kept under in the install's bucket. -pub fn object_key(team: &str, repo: &str, pr: u64, sha: &str, side: &str, ext: &str) -> String { +/// The newest run of a test on `branch` that passed: where its Before +/// screenshot is read. +pub fn newest_passing<'a>(history: &'a [HistoryEntry], branch: &str) -> Option<&'a HistoryEntry> { + history.iter().rev().find(|e| { + e.branch == branch && !e.bad_run && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) + }) +} + +/// The key an image of test `test` is kept under in the install's bucket; +/// two tests never share one. +pub fn object_key( + team: &str, + repo: &str, + pr: u64, + sha: &str, + test: &str, + side: &str, + ext: &str, +) -> String { + let test = hex::encode(Sha256::digest(test.as_bytes())); format!( - "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{side}.{ext}", + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{}/{side}.{ext}", team_folder(team), - sha.get(..12).unwrap_or(sha) + sha.get(..12).unwrap_or(sha), + &test[..16] ) } @@ -890,14 +909,22 @@ mod tests { assert!(before.is_empty()); assert_eq!( before_alt, - "No screenshot of this test from a passing run on main" + "No passing run on main with a screenshot of this test yet" ); } #[test] fn a_link_reads_one_image_of_its_own_team_until_it_expires() { - let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "after", "png"); - assert_eq!(key, "e2e-shots/TEAM_a/o/r/7/0123456789ab/after.png"); + let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "t", "after", "png"); + // sha256("t") = e3b98a4da31a127d... + assert_eq!( + key, + "e2e-shots/TEAM_a/o/r/7/0123456789ab/e3b98a4da31a127d/after.png" + ); + assert_ne!( + key, + object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "u", "after", "png") + ); let t = sign("s", "TEAM#a", &key, 100); assert_eq!(verify("s", &t, 99), Ok(key.clone())); assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); @@ -916,6 +943,48 @@ mod tests { .starts_with("https://api.example.com/webhooks/ci/tests/screenshot?t=")); } + #[test] + fn before_comes_from_the_newest_passing_run_on_the_pull_requests_base() { + let e = |run: &str, branch: &str, outcome, bad_run| HistoryEntry { + run_key: run.into(), + sha: "s".into(), + branch: branch.into(), + pr: None, + at: "t".into(), + outcome, + bad_run, + attempts: vec![], + }; + let history = vec![ + e("1-1", "develop", Outcome::Passed, false), + e("2-1", "develop", Outcome::Failed, false), + e("3-1", "develop", Outcome::Passed, true), + e("4-1", "main", Outcome::Passed, false), + ]; + // A pull request into develop never shows main's newer run. + assert_eq!( + newest_passing(&history, "develop").map(|e| e.run_key.as_str()), + Some("1-1") + ); + assert_eq!( + newest_passing(&history, "main").map(|e| e.run_key.as_str()), + Some("4-1") + ); + assert_eq!(newest_passing(&history, "release"), None); + let k = Kept { + base: "develop".into(), + ..Default::default() + }; + let crate::pr_body::Screens::Images { before_alt, .. } = screens(&k, |key| key.into()) + else { + panic!("images"); + }; + assert_eq!( + before_alt, + "No passing run on develop with a screenshot of this test yet" + ); + } + #[test] fn only_real_images_are_kept() { assert_eq!(image_type(PNG), Some("image/png")); diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 5c339c2d3..833d9ebbc 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -5,11 +5,13 @@ //! When a run on the pull request's head is read (`e2e::ingest`), the //! tests that show the change are chosen ([`shots::pick`]), and the first //! one with a screenshot on the head is kept with its screenshot from the -//! newest passing run on the default branch, when one is kept there too. +//! newest passing run on the pull request's base branch, when one is kept +//! there too. //! The images go to the install's own bucket, the record to the settings //! table for the head, and the description is rebuilt: its table links each //! image through the API with a signed link that expires -//! ([`screens_for`]). A head keeps the first pair found; a later run on the +//! ([`screens_for`]). A head keeps the first pair found: its record is +//! claimed before any image is kept, so a later or concurrent run on the //! same head changes nothing. use std::collections::HashMap; @@ -17,7 +19,7 @@ use std::collections::HashMap; use aws_sdk_dynamodb::types::AttributeValue; use common::e2e::coverage::TestMap; use common::e2e::messages::TestIngest; -use common::e2e::model::{Outcome, ParsedTest}; +use common::e2e::model::ParsedTest; use common::e2e::report_source::Location; use common::e2e::shots::{self, Image, Kept, Side}; use common::e2e::store::Store; @@ -29,8 +31,6 @@ use crate::WorkerState; /// Tests tried for a screenshot on the head. const MAX_TRIED: usize = 3; -/// How long the record of a head is kept. -const RECORD_DAYS: i64 = 90; fn record_sk(repo: &str, sha: &str) -> String { format!("E2E_SHOTS#{repo}#{sha}") @@ -50,9 +50,10 @@ pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> serde_json::from_str(item.get("data")?.as_s().ok()?).ok() } -async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) { - let ttl = (chrono::Utc::now() + chrono::Duration::days(RECORD_DAYS)).timestamp(); - if let Err(e) = state +/// Saves the record of a head unless one is there; whether this one is. +/// The record lives as long as its links work. +async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) -> bool { + state .dynamo .put_item() .table_name(&state.config.settings_table_name) @@ -62,11 +63,26 @@ async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kep "data", super::attr_s(&serde_json::to_string(k).unwrap_or_default()), ) - .item("ttl", AttributeValue::N(ttl.to_string())) + .item("ttl", AttributeValue::N(k.expires_at.to_string())) + .condition_expression("attribute_not_exists(sk)") + .send() + .await + .is_ok() +} + +/// Drops a claimed record whose images could not be kept, so a later run +/// on the head can keep its own. +async fn release(state: &WorkerState, team_id: &str, repo: &str, sha: &str) { + if let Err(e) = state + .dynamo + .delete_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&record_sk(repo, sha))) .send() .await { - warn!(error = %e, "Could not save the end-to-end screenshots of a head"); + warn!(error = %e, "Could not drop the record of a head whose screenshots were not kept"); } } @@ -225,28 +241,25 @@ async fn images( out } -/// Keeps one image in the install's bucket; its key. -async fn put( - state: &WorkerState, - key_of: impl Fn(&str) -> String, - bytes: Vec, -) -> Option { - let content_type = shots::image_type(&bytes)?; - let key = key_of(shots::extension(content_type)); +/// Keeps one image in the install's bucket under `key`; whether it was. +async fn put(state: &WorkerState, key: &str, bytes: Vec) -> bool { + let Some(content_type) = shots::image_type(&bytes) else { + return false; + }; match state .s3 .put_object() .bucket(&state.config.bucket_name) - .key(&key) + .key(key) .content_type(content_type) .body(bytes.into()) .send() .await { - Ok(_) => Some(key), + Ok(_) => true, Err(e) => { warn!(error = %e, "Could not keep an end-to-end screenshot"); - None + false } } } @@ -320,19 +333,24 @@ pub async fn keep( info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); return; }; - // The same test on the default branch: its newest passing run there. + // The same test on the branch the pull request goes into: its newest + // passing run there. + let Some(base) = gh + .get_pull_request(owner, name, h.pr) + .await + .ok() + .and_then(|p| p["base"]["ref"].as_str().map(str::to_string)) + .filter(|b| !b.is_empty()) + else { + warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); + return; + }; let newest = st .record(&msg.team_id, &scoped(t)) .await .ok() .flatten() - .and_then(|r| { - r.history.into_iter().rev().find(|e| { - e.branch == msg.default_branch - && !e.bad_run - && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) - }) - }); + .and_then(|r| shots::newest_passing(&r.history, &base).cloned()); let mut before: Option<(Vec, String)> = None; if let Some(e) = newest { let (src, run_id, attempt, run_url) = if e.run_key.starts_with("up-") { @@ -357,33 +375,51 @@ pub async fn keep( .remove(&t.id()) .map(|b| (b, run_url)); } - let key_of = |side: &'static str| { - let (team, pr, sha) = (msg.team_id.clone(), h.pr, msg.head_sha.clone()); - let repo = repo.clone(); - move |ext: &str| shots::object_key(&team, &repo, pr, &sha, side, ext) + let key_of = |side: &str, bytes: &[u8]| { + shots::image_type(bytes).map(|ct| { + shots::object_key( + &msg.team_id, + &repo, + h.pr, + &msg.head_sha, + &t.id(), + side, + shots::extension(ct), + ) + }) }; - let Some(after_key) = put(state, key_of("after"), after_bytes).await else { + let Some(after_key) = key_of("after", &after_bytes) else { return; }; - let before = match before { - Some((b, run_url)) => put(state, key_of("before"), b) - .await - .map(|key| Side { key, run_url }), - None => None, - }; + let before = + before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); let kept = Kept { pr: h.pr, test: t.full_title(), why: why.words(), - base: msg.default_branch.clone(), - before, + base, + before: before.as_ref().map(|(_, key, run_url)| Side { + key: key.clone(), + run_url: run_url.clone(), + }), after: Side { - key: after_key, + key: after_key.clone(), run_url: msg.html_url.clone(), }, expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, }; - save(state, &msg.team_id, &repo, &msg.head_sha, &kept).await; + if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { + info!(repo = %repo, pr = h.pr, "Another run on this head kept its screenshots first"); + return; + } + let mut kept_all = put(state, &after_key, after_bytes).await; + if let Some((b, key, _)) = before { + kept_all = kept_all && put(state, &key, b).await; + } + if !kept_all { + release(state, &msg.team_id, &repo, &msg.head_sha).await; + return; + } info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); if let super::description::Reconciled::Failed(why) = super::description::rebuild_pr(state, gh, &msg.team_id, owner, name, h.pr).await From 5245e3cea4e2d070764506fe9e2032602c7736cd Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:59:27 -0500 Subject: [PATCH 04/32] no-mistakes(review): Upload screenshots before claiming the head record --- services/common/src/e2e/shots.rs | 30 ++++++++++----- services/worker/src/passes/e2e.rs | 1 + services/worker/src/passes/e2e_screens.rs | 46 +++++++++++------------ 3 files changed, 43 insertions(+), 34 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index d05e6cb43..1c697b2ca 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -586,20 +586,22 @@ pub fn newest_passing<'a>(history: &'a [HistoryEntry], branch: &str) -> Option<& }) } -/// The key an image of test `test` is kept under in the install's bucket; -/// two tests never share one. +/// The key an image of test `test` from run `run` is kept under in the +/// install's bucket; two tests or two runs never share one. +#[allow(clippy::too_many_arguments)] pub fn object_key( team: &str, repo: &str, pr: u64, sha: &str, + run: &str, test: &str, side: &str, ext: &str, ) -> String { let test = hex::encode(Sha256::digest(test.as_bytes())); format!( - "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{}/{side}.{ext}", + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{run}/{}/{side}.{ext}", team_folder(team), sha.get(..12).unwrap_or(sha), &test[..16] @@ -915,16 +917,26 @@ mod tests { #[test] fn a_link_reads_one_image_of_its_own_team_until_it_expires() { - let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "t", "after", "png"); + let key = object_key( + "TEAM#a", + "o/r", + 7, + "0123456789abcdef", + "12-1", + "t", + "after", + "png", + ); // sha256("t") = e3b98a4da31a127d... assert_eq!( key, - "e2e-shots/TEAM_a/o/r/7/0123456789ab/e3b98a4da31a127d/after.png" - ); - assert_ne!( - key, - object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "u", "after", "png") + "e2e-shots/TEAM_a/o/r/7/0123456789ab/12-1/e3b98a4da31a127d/after.png" ); + let other = |run: &str, test: &str| { + object_key("TEAM#a", "o/r", 7, "0123456789abcdef", run, test, "after", "png") + }; + assert_ne!(key, other("12-1", "u")); + assert_ne!(key, other("13-1", "t")); let t = sign("s", "TEAM#a", &key, 100); assert_eq!(verify("s", &t, 99), Ok(key.clone())); assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index 22e1e98c2..d67135a65 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -636,6 +636,7 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { &st, super::e2e_screens::Head { msg: &msg, + run_key: &run_key, pr, tests: &tests, reports: &reports, diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 833d9ebbc..643ef469a 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -10,9 +10,9 @@ //! The images go to the install's own bucket, the record to the settings //! table for the head, and the description is rebuilt: its table links each //! image through the API with a signed link that expires -//! ([`screens_for`]). A head keeps the first pair found: its record is -//! claimed before any image is kept, so a later or concurrent run on the -//! same head changes nothing. +//! ([`screens_for`]). A head keeps the first pair found: each run keeps its +//! images under its own keys, then saves the head's record only when none +//! is there, so a later or concurrent run on the same head changes nothing. use std::collections::HashMap; @@ -53,7 +53,7 @@ pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> /// Saves the record of a head unless one is there; whether this one is. /// The record lives as long as its links work. async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) -> bool { - state + match state .dynamo .put_item() .table_name(&state.config.settings_table_name) @@ -67,22 +67,16 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke .condition_expression("attribute_not_exists(sk)") .send() .await - .is_ok() -} - -/// Drops a claimed record whose images could not be kept, so a later run -/// on the head can keep its own. -async fn release(state: &WorkerState, team_id: &str, repo: &str, sha: &str) { - if let Err(e) = state - .dynamo - .delete_item() - .table_name(&state.config.settings_table_name) - .key("pk", super::attr_s(team_id)) - .key("sk", super::attr_s(&record_sk(repo, sha))) - .send() - .await { - warn!(error = %e, "Could not drop the record of a head whose screenshots were not kept"); + Ok(_) => true, + Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => { + info!(repo, "Another run on this head kept its screenshots first"); + false + } + Err(e) => { + warn!(error = %e, repo, "Could not save the end-to-end screenshots of a head"); + false + } } } @@ -267,6 +261,8 @@ async fn put(state: &WorkerState, key: &str, bytes: Vec) -> bool { /// Everything a run on a pull request's head brings for its table. pub struct Head<'a> { pub msg: &'a TestIngest, + /// This run's key in the store. + pub run_key: &'a str, pub pr: u64, pub tests: &'a [ParsedTest], /// The reports this run was read from (an upload's report). @@ -382,6 +378,7 @@ pub async fn keep( &repo, h.pr, &msg.head_sha, + h.run_key, &t.id(), side, shots::extension(ct), @@ -408,16 +405,15 @@ pub async fn keep( }, expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, }; - if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { - info!(repo = %repo, pr = h.pr, "Another run on this head kept its screenshots first"); + if !put(state, &after_key, after_bytes).await { return; } - let mut kept_all = put(state, &after_key, after_bytes).await; if let Some((b, key, _)) = before { - kept_all = kept_all && put(state, &key, b).await; + if !put(state, &key, b).await { + return; + } } - if !kept_all { - release(state, &msg.team_id, &repo, &msg.head_sha).await; + if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { return; } info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); From 0c1b46080153a96ed0a886c3d45fb0c9a19198bc Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 02:01:02 -0500 Subject: [PATCH 05/32] no-mistakes(review): Detect lost claim race with the typed DynamoDB error --- services/worker/src/passes/e2e_screens.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 643ef469a..a0d786bfa 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -69,7 +69,10 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke .await { Ok(_) => true, - Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => { + Err(e) + if e.as_service_error() + .is_some_and(|s| s.is_conditional_check_failed_exception()) => + { info!(repo, "Another run on this head kept its screenshots first"); false } From 442d4ce24d1b448832be4cf01368e88bad55dd4d Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:12:40 -0500 Subject: [PATCH 06/32] Format the screenshot fixes with cargo fmt --- services/common/src/e2e/shots.rs | 11 ++++++++++- services/worker/src/passes/e2e_screens.rs | 3 +-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 1c697b2ca..1380f3949 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -933,7 +933,16 @@ mod tests { "e2e-shots/TEAM_a/o/r/7/0123456789ab/12-1/e3b98a4da31a127d/after.png" ); let other = |run: &str, test: &str| { - object_key("TEAM#a", "o/r", 7, "0123456789abcdef", run, test, "after", "png") + object_key( + "TEAM#a", + "o/r", + 7, + "0123456789abcdef", + run, + test, + "after", + "png", + ) }; assert_ne!(key, other("12-1", "u")); assert_ne!(key, other("13-1", "t")); diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index a0d786bfa..af447b5e1 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -391,8 +391,7 @@ pub async fn keep( let Some(after_key) = key_of("after", &after_bytes) else { return; }; - let before = - before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); + let before = before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); let kept = Kept { pr: h.pr, test: t.full_title(), From 3d54939f0fe6c4a473daac611a1839b7108e3e57 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:16:47 -0500 Subject: [PATCH 07/32] no-mistakes(review): Pick screenshot test against PR base, fetch PR once --- services/worker/src/passes/e2e.rs | 20 +++++----- services/worker/src/passes/e2e_screens.rs | 47 ++++++++++++++--------- 2 files changed, 38 insertions(+), 29 deletions(-) diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index d67135a65..9eeceaaa5 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -622,7 +622,11 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { if run.rescued { note_rescued(&st, &gh, &msg, &run, pr).await; } - let own = is_own_pr(&gh, &msg, pr).await; + let pull = gh + .get_pull_request(&msg.repo_owner, &msg.repo_name, pr) + .await + .ok(); + let own = is_own_pr(&msg, pull.as_ref()); // A run that failed only on quarantined tests needs no fix or re-run. if failed > 0 && !run.rescued && own { own_pr_failures(state, &gh, &msg, &run, pr, &lines, &tests).await; @@ -640,6 +644,7 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { pr, tests: &tests, reports: &reports, + pull: pull.as_ref(), changed: &changed, map: map.as_ref(), }, @@ -2380,16 +2385,9 @@ async fn recommend(st: &Store<'_>, team: &str, rec: Recommendation) { /// Whether the PR is one CoderHelm opened: a branch in the default shape, or /// a PR whose author is CoderHelm's app (a team's own branch pattern). -async fn is_own_pr(gh: &GitHubClient, msg: &TestIngest, pr: u64) -> bool { - if msg - .head_branch - .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) - { - return true; - } - gh.get_pull_request(&msg.repo_owner, &msg.repo_name, pr) - .await - .is_ok_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) +fn is_own_pr(msg: &TestIngest, pull: Option<&serde_json::Value>) -> bool { + msg.head_branch.starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) + || pull.is_some_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) } async fn recommend_from_pr( diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index af447b5e1..08561b3a5 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -270,7 +270,9 @@ pub struct Head<'a> { pub tests: &'a [ParsedTest], /// The reports this run was read from (an upload's report). pub reports: &'a [(String, Vec)], - /// The files the pull request changes. + /// The pull request, as GitHub returns it. + pub pull: Option<&'a serde_json::Value>, + /// The files the head changes against the default branch. pub changed: &'a [String], pub map: Option<&'a TestMap>, } @@ -291,14 +293,34 @@ pub async fn keep( if state.secrets.jwt_secret.is_empty() || msg.head_sha.is_empty() { return; } - let picked = shots::pick(h.tests, h.changed, h.map); - if picked.is_empty() - || load(state, &msg.team_id, &repo, &msg.head_sha) - .await - .is_some() + if load(state, &msg.team_id, &repo, &msg.head_sha) + .await + .is_some() { return; } + // The branch the pull request goes into: the tests its change touches + // are read against it, and the Before image comes from it. + let Some(base) = h + .pull + .and_then(|p| p["base"]["ref"].as_str()) + .filter(|b| !b.is_empty()) + .map(str::to_string) + else { + warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); + return; + }; + let changed = if base == msg.default_branch { + h.changed.to_vec() + } else { + gh.compare_changed_files(owner, name, &base, &msg.head_sha) + .await + .unwrap_or_default() + }; + let picked = shots::pick(h.tests, &changed, h.map); + if picked.is_empty() { + return; + } let location = st .settings(&msg.team_id) .await @@ -332,18 +354,7 @@ pub async fn keep( info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); return; }; - // The same test on the branch the pull request goes into: its newest - // passing run there. - let Some(base) = gh - .get_pull_request(owner, name, h.pr) - .await - .ok() - .and_then(|p| p["base"]["ref"].as_str().map(str::to_string)) - .filter(|b| !b.is_empty()) - else { - warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); - return; - }; + // The same test on the base branch: its newest passing run there. let newest = st .record(&msg.team_id, &scoped(t)) .await From 3f5abda4d4d3e1a258e57090e8c96737f3f39a08 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:51:57 -0500 Subject: [PATCH 08/32] no-mistakes(document): Format is_own_pr with cargo fmt --- services/worker/src/passes/e2e.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index 9eeceaaa5..5b362a761 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -2386,7 +2386,8 @@ async fn recommend(st: &Store<'_>, team: &str, rec: Recommendation) { /// Whether the PR is one CoderHelm opened: a branch in the default shape, or /// a PR whose author is CoderHelm's app (a team's own branch pattern). fn is_own_pr(msg: &TestIngest, pull: Option<&serde_json::Value>) -> bool { - msg.head_branch.starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) + msg.head_branch + .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) || pull.is_some_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) } From 994afbf41972f6dcd7837c24d47016c7f5f4e08e Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 00:02:05 -0500 Subject: [PATCH 09/32] Fill the Before and After table from the end-to-end run's screenshots CoderHelm's own pull request now shows the screenshots its end-to-end run already took, instead of "No screenshot". - common::e2e::shots reads the images Cucumber JSON embeds, Playwright JSON attaches and Playwright's HTML report keeps under data/, keyed by the test's id, and picks the test that shows the change: one the change edits, one the test map ties to the changed files, or one whose name shares a word with a changed UI file. - e2e_screens keeps that test's screenshot on the head and on the default branch's newest passing run in the install's own bucket, records it for the head and rebuilds the description. - The table links each image through the API with a signed link that works for a year (GET /webhooks/ci/tests/screenshot); the bucket keeps the images 395 days. --- infra/lib/storage-stack.ts | 7 + services/common/src/e2e/mod.rs | 4 + services/common/src/e2e/shots.rs | 867 ++++++++++++++++++ services/common/src/pr_body.rs | 18 +- services/gateway/src/main.rs | 3 + services/gateway/src/routes/tests.rs | 60 ++ services/worker/src/passes/description.rs | 31 + .../worker/src/passes/description_eval.rs | 1 + services/worker/src/passes/e2e.rs | 22 +- services/worker/src/passes/e2e_screens.rs | 426 +++++++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/test_fix.rs | 24 + 12 files changed, 1461 insertions(+), 3 deletions(-) create mode 100644 services/common/src/e2e/shots.rs create mode 100644 services/worker/src/passes/e2e_screens.rs diff --git a/infra/lib/storage-stack.ts b/infra/lib/storage-stack.ts index e15166b02..b467b1b2c 100644 --- a/infra/lib/storage-stack.ts +++ b/infra/lib/storage-stack.ts @@ -133,6 +133,13 @@ export class StorageStack extends cdk.Stack { expiration: cdk.Duration.days(2), noncurrentVersionExpiration: cdk.Duration.days(1), }, + { + // End-to-end screenshots in pull request descriptions: their links + // work for a year (common::e2e::shots), the images a month longer. + prefix: "e2e-shots/", + expiration: cdk.Duration.days(395), + noncurrentVersionExpiration: cdk.Duration.days(1), + }, { // Move old run artifacts to Infrequent Access after 90 days transitions: [ diff --git a/services/common/src/e2e/mod.rs b/services/common/src/e2e/mod.rs index 76a699773..d093148c5 100644 --- a/services/common/src/e2e/mod.rs +++ b/services/common/src/e2e/mod.rs @@ -33,6 +33,9 @@ //! holds end-to-end selectors to it. //! - [`branches`] finds test branches on a page's state and which of them a //! recorded run, or the page as it is now, would run. +//! - [`shots`] finds the screenshots a report carries for the tests that +//! show a change, for the Before and After table of CoderHelm's own pull +//! request. pub mod attribution; pub mod branches; @@ -54,6 +57,7 @@ pub mod parse; pub mod probe; pub mod quarantine; pub mod report_source; +pub mod shots; pub mod signature; pub mod stats; pub mod store; diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs new file mode 100644 index 000000000..1d323f61b --- /dev/null +++ b/services/common/src/e2e/shots.rs @@ -0,0 +1,867 @@ +//! Screenshots the end-to-end reports already carry, for the Before and +//! After table of CoderHelm's own pull request. +//! +//! A pull request whose whole change was visual showed no screenshot, while +//! the team's end-to-end run on it had taken some. The reports CoderHelm +//! reads (`parse`, `attribution`) keep them: +//! +//! - Cucumber JSON (WebdriverIO, Appium): images embedded in a scenario's +//! steps and hooks, base64 in the report itself; +//! - Playwright JSON: image attachments of a test's result, a file in the +//! run's artifacts (`path`) or the image itself (`body`); +//! - Playwright's HTML report: image attachments under its `data/` folder. +//! +//! [`shots_in`] reads them per test, keyed by the test's id +//! ([`ParsedTest::id`]), and [`pick`] chooses the tests that show the change: +//! a test the change edits, a test the repository's test map ties to the +//! changed files, or a test whose name shares a word with a changed UI file. +//! The worker keeps the images in the install's own bucket +//! ([`object_key`]); the description links them with a signed link +//! ([`sign`]) that the API serves at [`LINK_PATH`] until it expires. + +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::Engine; +use hmac::{Hmac, Mac}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::Sha256; + +use super::coverage::TestMap; +use super::model::{test_id, Framework, Outcome, ParsedTest}; + +/// Largest image kept. +pub const MAX_IMAGE: usize = 5 * 1024 * 1024; +/// Where the images are kept in the install's bucket. +pub const KEY_PREFIX: &str = "e2e-shots"; +/// How long an image link works (the bucket keeps the images a little +/// longer, see `infra/lib/storage-stack.ts`). +pub const LINK_VALID_SECS: i64 = 365 * 86_400; +/// The path the API serves an image at. +pub const LINK_PATH: &str = "/webhooks/ci/tests/screenshot"; +const MAX_TOKEN_LEN: usize = 2048; + +/// One test's screenshot in one report. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Shot { + /// The test's id ([`ParsedTest::id`]). + pub test_id: String, + pub image: Image, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Image { + /// The image itself (a Cucumber embedding, a Playwright `body`). + Inline(Vec), + /// A file of the run, as the report wrote its path. + File(String), +} + +/// The image's type, from its first bytes. Only PNG, JPEG and WebP are +/// kept. +pub fn image_type(bytes: &[u8]) -> Option<&'static str> { + if bytes.starts_with(&[0x89, b'P', b'N', b'G']) { + Some("image/png") + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + Some("image/jpeg") + } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + Some("image/webp") + } else { + None + } +} + +/// The file extension for an image type. +pub fn extension(content_type: &str) -> &'static str { + match content_type { + "image/jpeg" => "jpg", + "image/webp" => "webp", + _ => "png", + } +} + +fn is_image(content_type: &str) -> bool { + matches!( + content_type.trim().to_ascii_lowercase().as_str(), + "image/png" | "image/jpeg" | "image/jpg" | "image/webp" + ) +} + +fn decoded(data: &str) -> Option> { + let clean: String = data.chars().filter(|c| !c.is_whitespace()).collect(); + let bytes = STANDARD.decode(clean).ok()?; + (bytes.len() <= MAX_IMAGE && image_type(&bytes).is_some()).then_some(bytes) +} + +/// The screenshots in one report file, the last one of each test (its last +/// attempt, its final state). Empty when the file is not a report this +/// reads or carries no image. +pub fn shots_in(name: &str, bytes: &[u8]) -> Vec { + if bytes.len() > super::parse::MAX_REPORT_BYTES { + return Vec::new(); + } + let lower = name.to_lowercase(); + let found = if lower.ends_with(".html") { + playwright_html(bytes) + } else if lower.ends_with(".json") { + match serde_json::from_slice::(bytes) { + Ok(v) if v.get("suites").is_some() && v.get("config").is_some() => playwright(&v), + Ok(v) if v + .as_array() + .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => + { + cucumber(&v) + } + _ => Vec::new(), + } + } else { + Vec::new() + }; + last_per_test(found) +} + +fn last_per_test(found: Vec) -> Vec { + let mut out: Vec = Vec::new(); + for s in found { + match out.iter_mut().find(|x| x.test_id == s.test_id) { + Some(x) => *x = s, + None => out.push(s), + } + } + out +} + +// ── Cucumber JSON ───────────────────────────────────────────────────────── + +fn cucumber(report: &Value) -> Vec { + let mut out = Vec::new(); + for feature in report.as_array().into_iter().flatten() { + let file = feature["uri"].as_str().unwrap_or(""); + let feature_name = feature["name"].as_str().unwrap_or(""); + let suite: Vec = if feature_name.is_empty() { + vec![] + } else { + vec![feature_name.to_string()] + }; + for el in feature["elements"].as_array().into_iter().flatten() { + if el["type"].as_str() == Some("background") { + continue; + } + let last = ["before", "steps", "after"] + .iter() + .flat_map(|k| el[*k].as_array().into_iter().flatten()) + .flat_map(|s| s["embeddings"].as_array().into_iter().flatten()) + .filter(|e| { + is_image( + e["mime_type"] + .as_str() + .or_else(|| e["media"]["type"].as_str()) + .unwrap_or(""), + ) + }) + .filter_map(|e| e["data"].as_str().and_then(decoded)) + .last(); + if let Some(bytes) = last { + out.push(Shot { + test_id: test_id( + Framework::Cucumber, + file, + &suite, + el["name"].as_str().unwrap_or(""), + None, + ), + image: Image::Inline(bytes), + }); + } + } + } + out +} + +// ── Playwright ──────────────────────────────────────────────────────────── + +/// The last image attachment of a test's last result. +fn pw_image(results: &Value) -> Option { + let last = results.as_array()?.last()?; + last["attachments"] + .as_array()? + .iter() + .filter(|a| is_image(a["contentType"].as_str().unwrap_or(""))) + .filter_map(|a| match (a["body"].as_str(), a["path"].as_str()) { + (Some(b), _) if !b.is_empty() => decoded(b).map(Image::Inline), + (_, Some(p)) if !p.is_empty() && !p.contains("..") => Some(Image::File(p.to_string())), + _ => None, + }) + .last() +} + +fn project_of(test: &Value) -> Option<&str> { + test["projectName"].as_str().filter(|p| !p.is_empty()) +} + +/// The same walk as `parse::parse_playwright`, so ids match. +fn pw_walk(suite: &Value, path: &mut Vec, out: &mut Vec) { + let title = suite["title"].as_str().unwrap_or(""); + let file = suite["file"].as_str().unwrap_or(""); + let pushed = !title.is_empty() && title != file; + if pushed { + path.push(title.to_string()); + } + for spec in suite["specs"].as_array().into_iter().flatten() { + let spec_file = spec["file"].as_str().unwrap_or(file); + for test in spec["tests"].as_array().into_iter().flatten() { + if let Some(image) = pw_image(&test["results"]) { + out.push(Shot { + test_id: test_id( + Framework::Playwright, + spec_file, + path, + spec["title"].as_str().unwrap_or(""), + project_of(test), + ), + image, + }); + } + } + } + for child in suite["suites"].as_array().into_iter().flatten() { + pw_walk(child, path, out); + } + if pushed { + path.pop(); + } +} + +fn playwright(report: &Value) -> Vec { + let mut out = Vec::new(); + for suite in report["suites"].as_array().into_iter().flatten() { + pw_walk(suite, &mut Vec::new(), &mut out); + } + out +} + +/// The same reading as `parse::parse_playwright_html`, so ids match. The +/// attachments' paths are relative to the report (`data/.png`). +fn playwright_html(bytes: &[u8]) -> Vec { + use std::io::Read; + let Some(zip_bytes) = super::parse::html_report_zip(bytes) else { + return Vec::new(); + }; + let Ok(mut zip) = zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)) else { + return Vec::new(); + }; + let limit = super::parse::MAX_REPORT_BYTES as u64; + let mut read = |name: &str| -> Option { + let f = zip.by_name(name).ok()?; + if f.size() > limit { + return None; + } + let mut buf = Vec::new(); + f.take(limit).read_to_end(&mut buf).ok()?; + serde_json::from_slice(&buf).ok() + }; + let Some(report) = read("report.json") else { + return Vec::new(); + }; + let mut out = Vec::new(); + for summary in report["files"].as_array().into_iter().flatten() { + let Some(file) = summary["fileId"] + .as_str() + .and_then(|id| read(&format!("{id}.json"))) + else { + continue; + }; + let file_name = file["fileName"].as_str().unwrap_or(""); + for t in file["tests"].as_array().into_iter().flatten() { + let Some(image) = pw_image(&t["results"]) else { + continue; + }; + let suite: Vec = t["path"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p.as_str().map(str::to_string)) + .collect(); + out.push(Shot { + test_id: test_id( + Framework::Playwright, + t["location"]["file"].as_str().unwrap_or(file_name), + &suite, + t["title"].as_str().unwrap_or(""), + project_of(t), + ), + image, + }); + } + } + out +} + +/// The run's file an image attachment names. `report` is the report's own +/// name in the run's folder, `names` every file there. A relative path is +/// read next to the report; an absolute one (the runner's disk) is the file +/// whose name ends with the most of its trailing folders, at least the +/// image's own folder: every Playwright test writes `test-finished-1.png`, +/// in a folder of its own. +pub fn resolve(report: &str, path: &str, names: &[String]) -> Option { + let p = path.replace('\\', "/"); + if p.split('/').any(|s| s == "..") { + return None; + } + let absolute = p.starts_with('/') || p.get(1..2) == Some(":"); + if !absolute { + let dir = report + .rsplit_once('/') + .map(|(d, _)| format!("{d}/")) + .unwrap_or_default(); + let near = format!("{dir}{}", p.trim_start_matches("./")); + if names.contains(&near) { + return Some(near); + } + } + let segs: Vec<&str> = p.split('/').filter(|s| !s.is_empty()).collect(); + for k in (2..=segs.len()).rev() { + let tail = segs[segs.len() - k..].join("/"); + if let Some(n) = names + .iter() + .find(|n| **n == tail || n.ends_with(&format!("/{tail}"))) + { + return Some(n.clone()); + } + } + None +} + +// ── Which tests show the change ─────────────────────────────────────────── + +/// Why a test's screenshot is shown for a change. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Why { + /// The change edits the test itself. + TestChanged, + /// The repository's test map ties the test's area to a changed file. + Mapped, + /// The test's name shares this word with a changed UI file. + Named(String), +} + +impl Why { + /// Stronger evidence first. + fn rank(&self) -> u8 { + match self { + Why::TestChanged => 0, + Why::Mapped => 1, + Why::Named(_) => 2, + } + } + + pub fn words(&self) -> String { + match self { + Why::TestChanged => "this change edits the test".into(), + Why::Mapped => "the repository's test map ties it to the changed files".into(), + Why::Named(w) => format!("its name and a changed UI file share the word \"{w}\""), + } + } +} + +/// Folder and file names that say nothing about what a file shows. +const GENERIC: &[&str] = &[ + "src", "app", "apps", "lib", "libs", "packages", "package", "components", "component", + "screens", "screen", "pages", "page", "views", "view", "styles", "style", "index", "main", + "common", "shared", "utils", "util", "hooks", "assets", "features", "feature", "layout", + "layouts", "containers", "container", "modules", "module", "default", "mobile", "native", + "client", "public", "test", "tests", "spec", "specs", "e2e", "ui", "tsx", "jsx", "scss", + "css", "vue", "svelte", "html", "styled", "theme", "types", "button", "text", "item", + "list", "card", "modal", +]; + +/// The words of a path or title: split on anything but letters and digits +/// and at camelCase humps, lowercased, at least four letters, none of +/// [`GENERIC`]. +fn words(s: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut cur = String::new(); + let mut prev_lower = false; + let mut push = |w: &mut String| { + let l = w.to_ascii_lowercase(); + if l.len() >= 4 && !GENERIC.contains(&l.as_str()) && !out.contains(&l) { + out.push(l); + } + w.clear(); + }; + for c in s.chars() { + if !c.is_ascii_alphanumeric() { + push(&mut cur); + prev_lower = false; + continue; + } + if c.is_ascii_uppercase() && prev_lower { + push(&mut cur); + } + prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit(); + cur.push(c); + } + push(&mut cur); + out +} + +fn same_file(a: &str, b: &str) -> bool { + let (a, b) = (a.trim_start_matches("./"), b.trim_start_matches("./")); + !a.is_empty() + && !b.is_empty() + && (a == b || a.ends_with(&format!("/{b}")) || b.ends_with(&format!("/{a}"))) +} + +/// Why `t`'s screenshot shows the change to `changed`, if it does. +pub fn why_shown(t: &ParsedTest, changed: &[String], map: Option<&TestMap>) -> Option { + if changed.iter().any(|f| same_file(f, &t.file)) { + return Some(Why::TestChanged); + } + if map.is_some() && !super::triage::related_changes(t, changed, map).is_empty() { + return Some(Why::Mapped); + } + let named = words(&format!("{} {}", t.full_title(), t.file)); + changed + .iter() + .filter(|f| crate::pr_facts::is_ui(f)) + .flat_map(|f| words(f)) + .find(|w| named.contains(w)) + .map(Why::Named) +} + +/// The tests whose screenshots show the change, best first: the tests that +/// passed in the end, a test the change edits before one the test map +/// names, before one that only shares a word. +pub fn pick<'a>( + tests: &'a [ParsedTest], + changed: &[String], + map: Option<&TestMap>, +) -> Vec<(&'a ParsedTest, Why)> { + let mut out: Vec<(&ParsedTest, Why)> = tests + .iter() + .filter(|t| matches!(Outcome::of(&t.attempts), Outcome::Passed | Outcome::Flaky)) + .filter_map(|t| why_shown(t, changed, map).map(|w| (t, w))) + .collect(); + out.sort_by_key(|(_, w)| w.rank()); + out +} + +// ── What the description shows ──────────────────────────────────────────── + +/// One side of the table: the kept image and the run it came from. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Side { + /// The image's key in the install's bucket. + pub key: String, + /// The run's page; empty for an upload with no run page. + #[serde(default)] + pub run_url: String, +} + +/// The screenshots kept for one head of a pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Kept { + pub pr: u64, + /// The test's full title. + pub test: String, + /// Why this test shows the change ([`Why::words`]). + pub why: String, + /// The branch the Before side was taken on. + pub base: String, + /// The test on the base branch, when a run there kept one. + #[serde(default)] + pub before: Option, + /// The test on the head. + pub after: Side, + /// When the links stop working (unix seconds); fixed when kept, so the + /// description is the same text on every rebuild. + pub expires_at: i64, +} + +fn md_link(text: &str, url: &str) -> String { + if url.starts_with("https://") { + format!("[{text}]({url})") + } else { + text.to_string() + } +} + +/// The table for `k`; `link` gives an image's link from its key. +pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Screens { + let test = k.test.replace('`', "'"); + let base: &str = if k.base.is_empty() { + "the base branch" + } else { + &k.base + }; + let (before, before_alt) = match &k.before { + Some(s) => (link(&s.key), format!("{test} on {base}, before this change")), + None => ( + String::new(), + format!("No screenshot of this test on {base} yet"), + ), + }; + let runs = [ + k.before + .as_ref() + .map(|s| md_link(&format!("{base}'s run"), &s.run_url)), + Some(md_link("this head's run", &k.after.run_url)), + ] + .into_iter() + .flatten() + .collect::>() + .join(", "); + crate::pr_body::Screens::Images { + before, + before_alt, + after: link(&k.after.key), + after_alt: format!("{test} on this head"), + caption: format!( + "From the end-to-end test `{test}` ({runs}), shown because {}.", + k.why.trim_end_matches('.') + ), + } +} + +/// The key an image is kept under in the install's bucket. +pub fn object_key(team: &str, repo: &str, pr: u64, sha: &str, side: &str, ext: &str) -> String { + format!( + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{side}.{ext}", + team_folder(team), + sha.get(..12).unwrap_or(sha) + ) +} + +fn team_folder(team: &str) -> String { + team.replace(['#', '/'], "_") +} + +// ── Signed links ────────────────────────────────────────────────────────── + +type HmacSha256 = Hmac; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TokenError { + Malformed, + BadSignature, + Expired, +} + +fn mac(secret: &str, payload: &str) -> HmacSha256 { + // A key for screenshot links only, so a link never stands in for a + // session or for any other signed link. + let mut kdf = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC takes any key"); + kdf.update(b"coderhelm/e2e-screenshot/v1"); + let key = kdf.finalize().into_bytes(); + let mut m = HmacSha256::new_from_slice(&key).expect("HMAC takes any key"); + m.update(payload.as_bytes()); + m +} + +/// A token that reads one kept image of one team until `expires_at`. The +/// token is `base64url(team \n key \n expiry) . base64url(HMAC-SHA256)`. +pub fn sign(secret: &str, team: &str, key: &str, expires_at: i64) -> String { + let payload = format!("{team}\n{key}\n{expires_at}"); + let sig = mac(secret, &payload).finalize().into_bytes(); + format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(payload.as_bytes()), + URL_SAFE_NO_PAD.encode(sig) + ) +} + +/// The image key a token reads, if it is genuine, current, and names one of +/// its own team's kept images. +pub fn verify(secret: &str, token: &str, now: i64) -> Result { + if token.is_empty() || token.len() > MAX_TOKEN_LEN { + return Err(TokenError::Malformed); + } + let (body, sig) = token.split_once('.').ok_or(TokenError::Malformed)?; + let payload = URL_SAFE_NO_PAD + .decode(body) + .ok() + .and_then(|b| String::from_utf8(b).ok()) + .ok_or(TokenError::Malformed)?; + let sig = URL_SAFE_NO_PAD + .decode(sig) + .map_err(|_| TokenError::Malformed)?; + mac(secret, &payload) + .verify_slice(&sig) + .map_err(|_| TokenError::BadSignature)?; + let p: Vec<&str> = payload.split('\n').collect(); + let [team, key, exp] = p.as_slice() else { + return Err(TokenError::Malformed); + }; + let exp: i64 = exp.parse().map_err(|_| TokenError::Malformed)?; + let own = format!("{KEY_PREFIX}/{}/", team_folder(team)); + if team.is_empty() || !key.starts_with(&own) || key.split('/').any(|s| s == "..") { + return Err(TokenError::Malformed); + } + if now >= exp { + return Err(TokenError::Expired); + } + Ok(key.to_string()) +} + +/// The link for a token on this deployment's API. +pub fn url(api: &str, token: &str) -> String { + format!("{}{LINK_PATH}?t={token}", api.trim_end_matches('/')) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::e2e::model::{Attempt, AttemptStatus}; + use serde_json::json; + + const PNG: &[u8] = &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3]; + + fn b64(b: &[u8]) -> String { + STANDARD.encode(b) + } + + fn ids(report: &str, bytes: &[u8]) -> Vec { + let tests = super::super::parse::parse_any(report, bytes, &Default::default()).unwrap(); + tests.iter().map(ParsedTest::id).collect() + } + + #[test] + fn cucumber_embeddings_give_each_scenario_its_last_image_under_the_test_id() { + let report = json!([{ + "uri": "features/checkout.feature", + "name": "Checkout", + "elements": [ + {"type": "background", "name": "", "steps": [ + {"keyword": "Given ", "name": "signed in", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "image/png", "data": b64(PNG)}]} + ]}, + {"type": "scenario", "name": "Pays by card", "steps": [ + {"keyword": "When ", "name": "pay", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "image/png", "data": b64(b"\x89PNG first")}]}, + {"keyword": "Then ", "name": "paid", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "text/plain", "data": b64(b"log")}]} + ], "after": [ + {"keyword": "After", "result": {"status": "passed"}, + "embeddings": [{"media": {"type": "image/png"}, "data": b64(PNG)}]} + ]}, + {"type": "scenario", "name": "No image", "steps": [ + {"keyword": "When ", "name": "x", "result": {"status": "passed"}} + ]} + ] + }]); + let bytes = serde_json::to_vec(&report).unwrap(); + let shots = shots_in("wdio/cucumber.json", &bytes); + assert_eq!(shots.len(), 1); + assert_eq!(shots[0].image, Image::Inline(PNG.to_vec())); + // The id is the one the parser gives the scenario. + assert!(ids("wdio/cucumber.json", &bytes).contains(&shots[0].test_id)); + } + + #[test] + fn playwright_attachments_are_a_body_or_a_file_of_the_last_attempt() { + let report = json!({ + "config": {}, + "suites": [{"title": "home.spec.ts", "file": "home.spec.ts", "specs": [], "suites": [{ + "title": "Home", "file": "home.spec.ts", + "specs": [ + {"title": "shows the hero", "file": "home.spec.ts", "tests": [{ + "projectName": "chromium", + "results": [ + {"retry": 0, "status": "failed", "attachments": [ + {"name": "screenshot", "contentType": "image/png", "path": "/runner/test-results/home-hero/test-failed-1.png"}]}, + {"retry": 1, "status": "passed", "attachments": [ + {"name": "trace", "contentType": "application/zip", "path": "/runner/test-results/home-hero/trace.zip"}, + {"name": "screenshot", "contentType": "image/png", "path": "/runner/test-results/home-hero/test-finished-1.png"}]} + ]}]}, + {"title": "inline", "file": "home.spec.ts", "tests": [{ + "projectName": "chromium", + "results": [{"retry": 0, "status": "passed", "attachments": [ + {"name": "after", "contentType": "image/png", "body": b64(PNG)}]}]}]} + ] + }]}] + }); + let bytes = serde_json::to_vec(&report).unwrap(); + let shots = shots_in("results.json", &bytes); + assert_eq!(shots.len(), 2); + assert_eq!( + shots[0].image, + Image::File("/runner/test-results/home-hero/test-finished-1.png".into()) + ); + assert_eq!(shots[1].image, Image::Inline(PNG.to_vec())); + let parsed = ids("results.json", &bytes); + assert!(shots.iter().all(|s| parsed.contains(&s.test_id))); + } + + #[test] + fn an_attachment_is_found_next_to_its_report_or_by_its_own_folder() { + let names: Vec = [ + "report/index.html", + "report/data/abc.png", + "results/home-hero/test-finished-1.png", + "results/cart-total/test-finished-1.png", + ] + .map(String::from) + .to_vec(); + assert_eq!( + resolve("report/index.html", "data/abc.png", &names).as_deref(), + Some("report/data/abc.png") + ); + assert_eq!( + resolve( + "results/results.json", + "/home/runner/work/app/test-results/cart-total/test-finished-1.png", + &names + ) + .as_deref(), + Some("results/cart-total/test-finished-1.png") + ); + // The file name alone is every test's; it never decides. + assert_eq!( + resolve("r.json", "/elsewhere/test-finished-1.png", &names), + None + ); + assert_eq!(resolve("r.json", "../secret/a.png", &names), None); + } + + fn passed(file: &str, suite: &[&str], title: &str) -> ParsedTest { + ParsedTest { + framework: Framework::Playwright, + file: file.into(), + suite: suite.iter().map(|s| s.to_string()).collect(), + title: title.into(), + project: None, + tags: vec![], + attempts: vec![Attempt { + retry: 0, + status: AttemptStatus::Passed, + duration_ms: 1, + error: None, + trace_url: None, + video_url: None, + screenshot_url: None, + }], + } + } + + #[test] + fn the_test_the_change_edits_comes_before_one_that_shares_a_word() { + let mut failed = passed("e2e/checkout.spec.ts", &["Checkout"], "fails"); + failed.attempts[0].status = AttemptStatus::Failed; + let tests = vec![ + passed("e2e/home.spec.ts", &["Home"], "shows the hero"), + passed("e2e/checkout.spec.ts", &["Checkout"], "pays by card"), + failed, + passed("e2e/profile.spec.ts", &["Profile"], "edits the name"), + ]; + let changed: Vec = [ + "src/screens/Checkout/PayButton.tsx", + "e2e/profile.spec.ts", + "README.md", + ] + .map(String::from) + .to_vec(); + let picked = pick(&tests, &changed, None); + let titles: Vec<&str> = picked.iter().map(|(t, _)| t.title.as_str()).collect(); + assert_eq!(titles, vec!["edits the name", "pays by card"]); + assert_eq!(picked[0].1, Why::TestChanged); + assert_eq!(picked[1].1, Why::Named("checkout".into())); + } + + #[test] + fn generic_folders_and_non_ui_files_never_match() { + let tests = vec![passed("e2e/screens.spec.ts", &["Components"], "index page")]; + let changed: Vec = ["src/components/index.tsx", "src/api/screens.ts"] + .map(String::from) + .to_vec(); + assert!(pick(&tests, &changed, None).is_empty()); + } + + #[test] + fn words_split_camel_case_and_drop_short_and_generic_ones() { + assert_eq!( + words("src/screens/CheckoutSummary/PayButton.tsx"), + vec!["checkout", "summary"] + ); + } + + #[test] + fn the_table_names_the_test_its_runs_and_why() { + let k = Kept { + pr: 7, + test: "Checkout › pays by `card`".into(), + why: Why::Named("checkout".into()).words(), + base: "main".into(), + before: Some(Side { + key: "e2e-shots/T/o/r/7/abc/before.png".into(), + run_url: "https://github.com/o/r/actions/runs/1".into(), + }), + after: Side { + key: "e2e-shots/T/o/r/7/abc/after.png".into(), + run_url: "https://github.com/o/r/actions/runs/2".into(), + }, + expires_at: 10, + }; + let s = screens(&k, |key| format!("https://api.example.com/x?k={key}")); + let crate::pr_body::Screens::Images { + before, + after, + caption, + after_alt, + .. + } = s + else { + panic!("images"); + }; + assert!(before.ends_with("before.png")); + assert!(after.ends_with("after.png")); + assert_eq!(after_alt, "Checkout › pays by 'card' on this head"); + assert_eq!( + caption, + "From the end-to-end test `Checkout › pays by 'card'` ([main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)), shown because its name and a changed UI file share the word \"checkout\"." + ); + let none = screens( + &Kept { + before: None, + ..k.clone() + }, + |key| key.to_string(), + ); + let crate::pr_body::Screens::Images { + before, before_alt, .. + } = none + else { + panic!("images"); + }; + assert!(before.is_empty()); + assert_eq!(before_alt, "No screenshot of this test on main yet"); + } + + #[test] + fn a_link_reads_one_image_of_its_own_team_until_it_expires() { + let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "after", "png"); + assert_eq!(key, "e2e-shots/TEAM_a/o/r/7/0123456789ab/after.png"); + let t = sign("s", "TEAM#a", &key, 100); + assert_eq!(verify("s", &t, 99), Ok(key.clone())); + assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); + assert_eq!(verify("other", &t, 99), Err(TokenError::BadSignature)); + // Signed, but for another team's image or anything else in the bucket. + let theirs = sign("s", "TEAM#a", "e2e-shots/TEAM_b/o/r/1/x/after.png", 100); + assert_eq!(verify("s", &theirs, 99), Err(TokenError::Malformed)); + let raw = sign("s", "TEAM#a", "e2e/TEAM_a/o/r/raw/1-1/report.json", 100); + assert_eq!(verify("s", &raw, 99), Err(TokenError::Malformed)); + let up = sign("s", "TEAM#a", "e2e-shots/TEAM_a/../../secret", 100); + assert_eq!(verify("s", &up, 99), Err(TokenError::Malformed)); + // An unsubscribe token never reads an image. + let u = crate::unsubscribe::sign("s", "TEAM#a", "USER#1", "weekly_summary", 100); + assert!(verify("s", &u, 99).is_err()); + assert!(url("https://api.example.com/", &t) + .starts_with("https://api.example.com/webhooks/ci/tests/screenshot?t=")); + } + + #[test] + fn only_real_images_are_kept() { + assert_eq!(image_type(PNG), Some("image/png")); + assert_eq!(image_type(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg")); + assert_eq!(image_type(b""), None); + assert_eq!(decoded(&b64(b"")), None); + } +} diff --git a/services/common/src/pr_body.rs b/services/common/src/pr_body.rs index bdb6c3037..7435e4c37 100644 --- a/services/common/src/pr_body.rs +++ b/services/common/src/pr_body.rs @@ -228,11 +228,16 @@ impl Row { /// The screenshots of a UI change, or why there are none. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum Screens { + /// One Before and After pair. An empty `before` is a side with no + /// image: its cell says `before_alt` instead. Images { before: String, before_alt: String, after: String, after_alt: String, + /// One line under the table: where the images came from. + #[serde(default)] + caption: String, }, /// One line: why there is no screenshot. Missing(String), @@ -798,19 +803,28 @@ fn screens_markdown(s: &Screens) -> String { before_alt, after, after_alt, + caption, } => { let img = |src: &str, alt: &str| { + if src.trim().is_empty() { + return cell(&one_line(alt)); + } format!( "\"{}\"", src.replace('"', "%22"), one_line(alt).replace('"', "'") ) }; - format!( + let mut s = format!( "| Before | After |\n|---|---|\n| {} | {} |", img(before, before_alt), img(after, after_alt) - ) + ); + let caption = one_line(caption); + if !caption.is_empty() { + s.push_str(&format!("\n\n{caption}")); + } + s } Screens::Missing(why) => format!("No screenshot: {}.", part(why)), Screens::Pages(pages) => { diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 6ffc07112..153d41791 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1614,6 +1614,9 @@ fn build_app(state: Arc) -> Router { // CI calls signed with a GitHub Actions OIDC token .route("/ci/tests/results", post(routes::tests::ci_upload)) .route("/ci/tests/quarantine", get(routes::tests::ci_quarantine)) + // A screenshot in the Before and After table of CoderHelm's own pull + // request; the signed link is the credential (routes::tests). + .route("/ci/tests/screenshot", get(routes::tests::ci_screenshot)) // Events CoderHelm's relay forwards to a hybrid install, and its // ownership proof (routes::hybrid_install). .route("/relay", post(routes::hybrid_install::intake)) diff --git a/services/gateway/src/routes/tests.rs b/services/gateway/src/routes/tests.rs index 44bdbb1a9..4fec457c2 100644 --- a/services/gateway/src/routes/tests.rs +++ b/services/gateway/src/routes/tests.rs @@ -1382,6 +1382,66 @@ pub async fn ci_quarantine( })) } +#[derive(Deserialize)] +pub struct ShotQuery { + #[serde(default)] + t: String, +} + +/// GET /webhooks/ci/tests/screenshot?t= — one end-to-end screenshot kept for +/// the Before and After table of CoderHelm's own pull request +/// (`common::e2e::shots`). Public, because GitHub fetches the image for the +/// pull request's readers: the signed token is the credential, and it names +/// one image of one team until it expires. Anything else is a 404 that says +/// nothing. +pub async fn ci_screenshot( + State(state): State>, + Query(q): Query, +) -> axum::response::Response { + use axum::http::header; + use axum::response::IntoResponse; + use common::e2e::shots; + let not_found = || (StatusCode::NOT_FOUND, "Not found").into_response(); + let secret = state.secrets.jwt_secret.as_str(); + if secret.is_empty() { + return not_found(); + } + let key = match shots::verify(secret, q.t.trim(), chrono::Utc::now().timestamp()) { + Ok(k) => k, + Err(e) => { + info!(reason = ?e, "Screenshot link refused"); + return not_found(); + } + }; + let Ok(obj) = state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(&key) + .send() + .await + else { + return not_found(); + }; + let Ok(body) = obj.body.collect().await else { + return not_found(); + }; + let bytes = body.into_bytes(); + let Some(content_type) = shots::image_type(&bytes) else { + return not_found(); + }; + ( + StatusCode::OK, + [ + (header::CONTENT_TYPE, content_type), + (header::CACHE_CONTROL, "public, max-age=86400"), + (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), + ], + bytes, + ) + .into_response() +} + #[cfg(test)] mod unit { use super::*; diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 017326f78..b3b74d046 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -550,6 +550,25 @@ pub async fn rebuild( .await } +/// [`rebuild`] for a pull request, its ticket read from the run that opened +/// it: something its description shows arrived on the same head (the +/// screenshots of the end-to-end run, `e2e_screens`). +pub async fn rebuild_pr( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, +) -> Reconciled { + let ticket = match super::review_pr::lookup_run_by_pr(state, team_id, owner, repo, number).await + { + Some(run_id) => run_ticket(state, team_id, &run_id).await, + None => String::new(), + }; + rebuild(state, github, team_id, owner, repo, number, &ticket).await +} + /// What was read about a pull request for one build. struct Gathered { pr: serde_json::Value, @@ -558,6 +577,9 @@ struct Gathered { checks: Option>, run: RunBits, run_url: String, + /// The Before and After table the end-to-end run on the head filled + /// (`e2e_screens`). + screens: Option, } /// What the run behind a pull request holds for its description. @@ -641,6 +663,9 @@ impl Gathered { super::description_facts::with_preview(&mut f, preview); super::description_facts::with_scope(&mut f, self.run.scope.as_ref(), &self.files); f.waiting = self.run.waiting.clone(); + if self.screens.is_some() { + f.screens = self.screens.clone(); + } f } } @@ -776,6 +801,11 @@ async fn gather( } else { format!("{app}/runs/detail?id={run_id}") }; + let screens = if head.is_empty() { + None + } else { + super::e2e_screens::screens_for(state, team_id, &format!("{owner}/{repo}"), &head).await + }; Ok(Gathered { pr, files, @@ -783,6 +813,7 @@ async fn gather( checks, run, run_url, + screens, }) } diff --git a/services/worker/src/passes/description_eval.rs b/services/worker/src/passes/description_eval.rs index ee9372991..4a314aa34 100644 --- a/services/worker/src/passes/description_eval.rs +++ b/services/worker/src/passes/description_eval.rs @@ -682,6 +682,7 @@ pub fn ui_facts() -> Facts { before_alt: "Sub Title field with a 190-character subtitle and no warning".into(), after: "https://github.com/user-attachments/assets/after-example".into(), after_alt: "Same field showing the warning 'Over 160 characters (190)'".into(), + caption: String::new(), }), run_url: "https://app.example.com/runs/detail?id=run-4812".into(), repo_url: "https://github.com/acme/site".into(), diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index b3d55beb8..ca7a1e5a9 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -622,10 +622,30 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { if run.rescued { note_rescued(&st, &gh, &msg, &run, pr).await; } + let own = is_own_pr(&gh, &msg, pr).await; // A run that failed only on quarantined tests needs no fix or re-run. - if failed > 0 && !run.rescued && is_own_pr(&gh, &msg, pr).await { + if failed > 0 && !run.rescued && own { own_pr_failures(state, &gh, &msg, &run, pr, &lines, &tests).await; } + // CoderHelm's own pull request shows the screenshots this run took + // of the tests its change touches. + if own { + super::e2e_screens::keep( + state, + &gh, + &st, + super::e2e_screens::Head { + msg: &msg, + pr, + tests: &tests, + reports: &reports, + changed: &changed, + map: map.as_ref(), + }, + |t| scoped_id(&repo, t), + ) + .await; + } recommend_from_pr(state, &gh, &msg, pr, &changed, map.as_ref()).await; follow_generated(state, &gh, &msg, &run, &tests).await; } diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs new file mode 100644 index 000000000..4bc649b14 --- /dev/null +++ b/services/worker/src/passes/e2e_screens.rs @@ -0,0 +1,426 @@ +//! The Before and After table of CoderHelm's own pull request, filled from +//! the screenshots its end-to-end run took (the rules are +//! `common::e2e::shots`). +//! +//! When a run on the pull request's head is read (`e2e::ingest`), the +//! tests that show the change are chosen ([`shots::pick`]), and the first +//! one with a screenshot on the head is kept with its screenshot from the +//! newest passing run on the default branch, when one is kept there too. +//! The images go to the install's own bucket, the record to the settings +//! table for the head, and the description is rebuilt: its table links each +//! image through the API with a signed link that expires +//! ([`screens_for`]). A head keeps the first pair found; a later run on the +//! same head changes nothing. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::e2e::coverage::TestMap; +use common::e2e::messages::TestIngest; +use common::e2e::model::{Outcome, ParsedTest}; +use common::e2e::report_source::Location; +use common::e2e::shots::{self, Image, Kept, Side}; +use common::e2e::store::Store; +use tracing::{info, warn}; + +use super::test_fix::{CiReports, KeptRun, Reports, S3Reports}; +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// Tests tried for a screenshot on the head. +const MAX_TRIED: usize = 3; +/// How long the record of a head is kept. +const RECORD_DAYS: i64 = 90; + +fn record_sk(repo: &str, sha: &str) -> String { + format!("E2E_SHOTS#{repo}#{sha}") +} + +pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> Option { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&record_sk(repo, sha))) + .send() + .await + .ok()? + .item?; + serde_json::from_str(item.get("data")?.as_s().ok()?).ok() +} + +async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) { + let ttl = (chrono::Utc::now() + chrono::Duration::days(RECORD_DAYS)).timestamp(); + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", super::attr_s(team_id)) + .item("sk", super::attr_s(&record_sk(repo, sha))) + .item( + "data", + super::attr_s(&serde_json::to_string(k).unwrap_or_default()), + ) + .item("ttl", AttributeValue::N(ttl.to_string())) + .send() + .await + { + warn!(error = %e, "Could not save the end-to-end screenshots of a head"); + } +} + +/// The Before and After table for a pull request's head, when a run on it +/// kept screenshots. `None` without a signing secret or a public API +/// address: GitHub fetches the images from the API, so a link must reach +/// it. +pub async fn screens_for( + state: &WorkerState, + team_id: &str, + repo: &str, + sha: &str, +) -> Option { + let secret = state.secrets.jwt_secret.as_str(); + let api = common::public_urls::api_url(&state.config.stage); + if secret.is_empty() || !api.starts_with("https://") { + return None; + } + let k = load(state, team_id, repo, sha).await?; + Some(shots::screens(&k, |key| { + shots::url(api, &shots::sign(secret, team_id, key, k.expires_at)) + })) +} + +/// Report files held in memory: an uploaded report, or the raw reports kept +/// in the install's bucket for an upload. +struct Held(Vec<(String, Vec)>); + +#[async_trait::async_trait] +impl Reports for Held { + fn label(&self, _run_id: u64, _attempt: u32) -> String { + "the uploaded report".into() + } + + async fn runs(&self) -> Vec { + Vec::new() + } + + async fn reports(&self, _run_id: u64, _attempt: u32) -> Result)>, String> { + Ok(self.0.clone()) + } + + async fn file(&self, _run_id: u64, _attempt: u32, path: &str) -> Option> { + self.0 + .iter() + .find(|(n, _)| n == path) + .map(|(_, b)| b.clone()) + } + + async fn names(&self, _run_id: u64, _attempt: u32) -> Vec { + self.0.iter().map(|(n, _)| n.clone()).collect() + } +} + +/// Where one run's reports are read. +enum Source<'a> { + Held(Held), + S3(Box), + Ci(CiReports<'a>), +} + +impl Source<'_> { + fn reports(&self) -> &dyn Reports { + match self { + Source::Held(r) => r, + Source::S3(r) => r.as_ref(), + Source::Ci(r) => r, + } + } +} + +/// The raw reports kept in the install's bucket for an uploaded run +/// (`e2e::ingest` keeps them within a budget). +async fn kept_raw(state: &WorkerState, team_id: &str, repo: &str, run_key: &str) -> Held { + let marker = common::e2e::store::raw_report_key(team_id, repo, run_key, "x"); + let prefix = marker.trim_end_matches('x').to_string(); + let mut out = Vec::new(); + let Ok(listed) = state + .s3 + .list_objects_v2() + .bucket(&state.config.bucket_name) + .prefix(&prefix) + .max_keys(20) + .send() + .await + else { + return Held(out); + }; + for o in listed.contents() { + let (Some(key), size) = (o.key(), o.size().unwrap_or(0)) else { + continue; + }; + if size < 0 || size as usize > common::e2e::parse::MAX_REPORT_BYTES { + continue; + } + let Ok(obj) = state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(key) + .send() + .await + else { + continue; + }; + if let Ok(body) = obj.body.collect().await { + let name = key.strip_prefix(&prefix).unwrap_or(key).to_string(); + out.push((name, body.into_bytes().to_vec())); + } + } + Held(out) +} + +/// `{run_id}-{attempt}`, the key of a run read from GitHub. +fn run_of(run_key: &str) -> Option<(u64, u32)> { + let (run, attempt) = run_key.split_once('-')?; + Some((run.parse().ok()?, attempt.parse().ok()?)) +} + +/// The screenshots of `wanted` (test ids) in one run, by test id. +async fn images( + r: &dyn Reports, + run_id: u64, + attempt: u32, + wanted: &[String], +) -> HashMap> { + let mut out = HashMap::new(); + let Ok(files) = r.reports(run_id, attempt).await else { + return out; + }; + let mut names: Option> = None; + for (name, bytes) in &files { + for s in shots::shots_in(name, bytes) { + if !wanted.contains(&s.test_id) { + continue; + } + let image = match s.image { + Image::Inline(b) => Some(b), + Image::File(p) => { + if names.is_none() { + names = Some(r.names(run_id, attempt).await); + } + match shots::resolve(name, &p, names.as_deref().unwrap_or_default()) { + Some(n) => r.file(run_id, attempt, &n).await, + None => None, + } + } + }; + if let Some(b) = + image.filter(|b| b.len() <= shots::MAX_IMAGE && shots::image_type(b).is_some()) + { + out.insert(s.test_id, b); + } + } + } + out +} + +/// Keeps one image in the install's bucket; its key. +async fn put(state: &WorkerState, key_of: impl Fn(&str) -> String, bytes: Vec) -> Option { + let content_type = shots::image_type(&bytes)?; + let key = key_of(shots::extension(content_type)); + match state + .s3 + .put_object() + .bucket(&state.config.bucket_name) + .key(&key) + .content_type(content_type) + .body(bytes.into()) + .send() + .await + { + Ok(_) => Some(key), + Err(e) => { + warn!(error = %e, "Could not keep an end-to-end screenshot"); + None + } + } +} + +/// Everything a run on a pull request's head brings for its table. +pub struct Head<'a> { + pub msg: &'a TestIngest, + pub pr: u64, + pub tests: &'a [ParsedTest], + /// The reports this run was read from (an upload's report). + pub reports: &'a [(String, Vec)], + /// The files the pull request changes. + pub changed: &'a [String], + pub map: Option<&'a TestMap>, +} + +/// Keeps the screenshots that show the change of CoderHelm's own pull +/// request from one run on its head, and rebuilds its description with +/// them. `scoped` is a test's id in the store. +pub async fn keep( + state: &WorkerState, + gh: &GitHubClient, + st: &Store<'_>, + h: Head<'_>, + scoped: impl Fn(&ParsedTest) -> String, +) { + let msg = h.msg; + let (owner, name) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); + let repo = format!("{owner}/{name}"); + if state.secrets.jwt_secret.is_empty() || msg.head_sha.is_empty() { + return; + } + let picked = shots::pick(h.tests, h.changed, h.map); + if picked.is_empty() || load(state, &msg.team_id, &repo, &msg.head_sha).await.is_some() { + return; + } + let location = st + .settings(&msg.team_id) + .await + .ok() + .and_then(|s| s.report_source(&repo).and_then(|r| r.location().ok())); + let location = location.as_ref(); + // Where the team keeps the repository's reports, else the run's + // artifacts: the same places the failure attribution reads. + let open = |run_id: u64| async move { + if let Some(l @ Location::S3 { .. }) = location { + let mut tried = Vec::new(); + if let Some(r) = super::test_fix::open_s3(state, &msg.team_id, l, &mut tried).await { + return Source::S3(Box::new(r)); + } + } + Source::Ci(CiReports::new(gh, owner, name, vec![(run_id, 1)])) + }; + // The head's run. + let head = if msg.upload_key.is_some() { + Source::Held(Held(h.reports.to_vec())) + } else { + open(msg.run_id).await + }; + let tried: Vec<&(&ParsedTest, shots::Why)> = picked.iter().take(MAX_TRIED).collect(); + let ids: Vec = tried.iter().map(|(t, _)| t.id()).collect(); + let mut after = images(head.reports(), msg.run_id, msg.run_attempt, &ids).await; + let Some((t, why, after_bytes)) = tried + .into_iter() + .find_map(|(t, w)| after.remove(&t.id()).map(|b| (*t, w, b))) + else { + info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); + return; + }; + // The same test on the default branch: its newest passing run there. + let newest = st + .record(&msg.team_id, &scoped(t)) + .await + .ok() + .flatten() + .and_then(|r| { + r.history.into_iter().rev().find(|e| { + e.branch == msg.default_branch + && !e.bad_run + && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) + }) + }); + let mut before: Option<(Vec, String)> = None; + if let Some(e) = newest { + let (src, run_id, attempt, run_url) = if e.run_key.starts_with("up-") { + ( + Source::Held(kept_raw(state, &msg.team_id, &repo, &e.run_key).await), + 0, + 1, + String::new(), + ) + } else if let Some((run_id, attempt)) = run_of(&e.run_key) { + ( + open(run_id).await, + run_id, + attempt, + format!("https://github.com/{repo}/actions/runs/{run_id}"), + ) + } else { + (Source::Held(Held(Vec::new())), 0, 1, String::new()) + }; + before = images(src.reports(), run_id, attempt, &[t.id()]) + .await + .remove(&t.id()) + .map(|b| (b, run_url)); + } + let key_of = |side: &'static str| { + let (team, pr, sha) = (msg.team_id.clone(), h.pr, msg.head_sha.clone()); + let repo = repo.clone(); + move |ext: &str| shots::object_key(&team, &repo, pr, &sha, side, ext) + }; + let Some(after_key) = put(state, key_of("after"), after_bytes).await else { + return; + }; + let before = match before { + Some((b, run_url)) => put(state, key_of("before"), b) + .await + .map(|key| Side { key, run_url }), + None => None, + }; + let kept = Kept { + pr: h.pr, + test: t.full_title(), + why: why.words(), + base: msg.default_branch.clone(), + before, + after: Side { + key: after_key, + run_url: msg.html_url.clone(), + }, + expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, + }; + save(state, &msg.team_id, &repo, &msg.head_sha, &kept).await; + info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); + if let super::description::Reconciled::Failed(why) = + super::description::rebuild_pr(state, gh, &msg.team_id, owner, name, h.pr).await + { + warn!(repo = %repo, pr = h.pr, why, "The description was not rebuilt with the screenshots; the next rebuild shows them"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_github_run_key_names_its_run_and_attempt() { + assert_eq!(run_of("123-2"), Some((123, 2))); + assert_eq!(run_of("up-1-1-abcdef"), None); + assert_eq!(run_of("nope"), None); + } + + #[tokio::test] + async fn an_attachment_is_read_from_the_file_its_report_names() { + let png = vec![0x89, b'P', b'N', b'G', 0, 1]; + let report = serde_json::json!({ + "config": {}, + "suites": [{"title": "a.spec.ts", "file": "a.spec.ts", "specs": [ + {"title": "shows it", "file": "a.spec.ts", "tests": [{"results": [ + {"status": "passed", "attachments": [ + {"name": "screenshot", "contentType": "image/png", + "path": "/runner/work/test-results/a-shows-it/test-finished-1.png"}]}]}]} + ]}] + }); + let held = Held(vec![ + ("pw/results.json".into(), serde_json::to_vec(&report).unwrap()), + ("pw/test-results/a-shows-it/test-finished-1.png".into(), png.clone()), + ]); + let tests = common::e2e::parse::parse_any( + "results.json", + &serde_json::to_vec(&report).unwrap(), + &Default::default(), + ) + .unwrap(); + let id = tests[0].id(); + let got = images(&held, 1, 1, &[id.clone()]).await; + assert_eq!(got.get(&id), Some(&png)); + // A test nobody asked for is not read. + assert!(images(&held, 1, 1, &["other".into()]).await.is_empty()); + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 6d43d8302..bdd1166db 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1276,6 +1276,7 @@ pub mod dlq_cleanup; pub mod e2e; pub mod e2e_attribution; pub mod e2e_reads; +pub mod e2e_screens; pub mod e2e_setup; pub mod email_events; mod explore_guard; diff --git a/services/worker/src/passes/test_fix.rs b/services/worker/src/passes/test_fix.rs index bdc15a028..9e17506d7 100644 --- a/services/worker/src/passes/test_fix.rs +++ b/services/worker/src/passes/test_fix.rs @@ -367,6 +367,12 @@ pub trait Reports: Send + Sync { async fn reports(&self, run_id: u64, attempt: u32) -> Result)>, String>; /// One file of the run's folder (an attachment of an HTML report). async fn file(&self, run_id: u64, attempt: u32, path: &str) -> Option>; + /// Every file of the run's folder, by the path [`Reports::file`] + /// reads: where a report's attachment is found when the report wrote + /// the runner's own path (`e2e_screens`). + async fn names(&self, _run_id: u64, _attempt: u32) -> Vec { + Vec::new() + } } /// What one run's reports say. @@ -694,6 +700,17 @@ impl Reports for S3Reports { .map(|(_, s, _)| *s)?; self.get(&key, size).await } + + async fn names(&self, run_id: u64, attempt: u32) -> Vec { + let attempt = self.attempt_for(run_id, attempt); + let prefix = self.run_prefix(run_id, attempt); + self.index + .get(&(run_id, attempt)) + .into_iter() + .flatten() + .map(|(k, _, _)| k.strip_prefix(&prefix).unwrap_or(k).to_string()) + .collect() + } } /// Reports in a run's GitHub Actions artifacts. @@ -837,6 +854,13 @@ impl Reports for CiReports<'_> { .find(|(n, _)| n == path) .map(|(_, b)| b) } + + async fn names(&self, run_id: u64, _attempt: u32) -> Vec { + self.files(run_id) + .await + .map(|f| f.into_iter().map(|(n, _)| n).collect()) + .unwrap_or_default() + } } /// The team's AWS session that can read `location`: the first connected From cd8f2a99643aa05881216031a9edca1ff7e37031 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:50:44 -0500 Subject: [PATCH 10/32] Say why a screenshot's test was picked, and pass clippy The reason names the test, not only its name (the match reads its title and file); an empty Before cell says no passing run on the base kept one rather than "yet"; the caption gives the reason before the run links. Formatted, and two iterator and one slice lint fixed. --- services/common/src/e2e/shots.rs | 95 ++++++++++++++++++----- services/worker/src/passes/e2e_screens.rs | 24 ++++-- 2 files changed, 96 insertions(+), 23 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 1d323f61b..0068f2a6f 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -105,9 +105,9 @@ pub fn shots_in(name: &str, bytes: &[u8]) -> Vec { } else if lower.ends_with(".json") { match serde_json::from_slice::(bytes) { Ok(v) if v.get("suites").is_some() && v.get("config").is_some() => playwright(&v), - Ok(v) if v - .as_array() - .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => + Ok(v) + if v.as_array() + .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => { cucumber(&v) } @@ -159,7 +159,7 @@ fn cucumber(report: &Value) -> Vec { ) }) .filter_map(|e| e["data"].as_str().and_then(decoded)) - .last(); + .next_back(); if let Some(bytes) = last { out.push(Shot { test_id: test_id( @@ -191,7 +191,7 @@ fn pw_image(results: &Value) -> Option { (_, Some(p)) if !p.is_empty() && !p.contains("..") => Some(Image::File(p.to_string())), _ => None, }) - .last() + .next_back() } fn project_of(test: &Value) -> Option<&str> { @@ -358,20 +358,73 @@ impl Why { match self { Why::TestChanged => "this change edits the test".into(), Why::Mapped => "the repository's test map ties it to the changed files".into(), - Why::Named(w) => format!("its name and a changed UI file share the word \"{w}\""), + Why::Named(w) => format!("the test and a changed UI file share the word \"{w}\""), } } } /// Folder and file names that say nothing about what a file shows. const GENERIC: &[&str] = &[ - "src", "app", "apps", "lib", "libs", "packages", "package", "components", "component", - "screens", "screen", "pages", "page", "views", "view", "styles", "style", "index", "main", - "common", "shared", "utils", "util", "hooks", "assets", "features", "feature", "layout", - "layouts", "containers", "container", "modules", "module", "default", "mobile", "native", - "client", "public", "test", "tests", "spec", "specs", "e2e", "ui", "tsx", "jsx", "scss", - "css", "vue", "svelte", "html", "styled", "theme", "types", "button", "text", "item", - "list", "card", "modal", + "src", + "app", + "apps", + "lib", + "libs", + "packages", + "package", + "components", + "component", + "screens", + "screen", + "pages", + "page", + "views", + "view", + "styles", + "style", + "index", + "main", + "common", + "shared", + "utils", + "util", + "hooks", + "assets", + "features", + "feature", + "layout", + "layouts", + "containers", + "container", + "modules", + "module", + "default", + "mobile", + "native", + "client", + "public", + "test", + "tests", + "spec", + "specs", + "e2e", + "ui", + "tsx", + "jsx", + "scss", + "css", + "vue", + "svelte", + "html", + "styled", + "theme", + "types", + "button", + "text", + "item", + "list", + "card", + "modal", ]; /// The words of a path or title: split on anything but letters and digits @@ -494,10 +547,13 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree &k.base }; let (before, before_alt) = match &k.before { - Some(s) => (link(&s.key), format!("{test} on {base}, before this change")), + Some(s) => ( + link(&s.key), + format!("{test} on {base}, before this change"), + ), None => ( String::new(), - format!("No screenshot of this test on {base} yet"), + format!("No screenshot of this test from a passing run on {base}"), ), }; let runs = [ @@ -516,7 +572,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree after: link(&k.after.key), after_alt: format!("{test} on this head"), caption: format!( - "From the end-to-end test `{test}` ({runs}), shown because {}.", + "Screenshots of the end-to-end test `{test}`, chosen because {}: {runs}.", k.why.trim_end_matches('.') ), } @@ -816,7 +872,7 @@ mod tests { assert_eq!(after_alt, "Checkout › pays by 'card' on this head"); assert_eq!( caption, - "From the end-to-end test `Checkout › pays by 'card'` ([main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)), shown because its name and a changed UI file share the word \"checkout\"." + "Screenshots of the end-to-end test `Checkout › pays by 'card'`, chosen because the test and a changed UI file share the word \"checkout\": [main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)." ); let none = screens( &Kept { @@ -832,7 +888,10 @@ mod tests { panic!("images"); }; assert!(before.is_empty()); - assert_eq!(before_alt, "No screenshot of this test on main yet"); + assert_eq!( + before_alt, + "No screenshot of this test from a passing run on main" + ); } #[test] diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 4bc649b14..5c339c2d3 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -226,7 +226,11 @@ async fn images( } /// Keeps one image in the install's bucket; its key. -async fn put(state: &WorkerState, key_of: impl Fn(&str) -> String, bytes: Vec) -> Option { +async fn put( + state: &WorkerState, + key_of: impl Fn(&str) -> String, + bytes: Vec, +) -> Option { let content_type = shots::image_type(&bytes)?; let key = key_of(shots::extension(content_type)); match state @@ -276,7 +280,11 @@ pub async fn keep( return; } let picked = shots::pick(h.tests, h.changed, h.map); - if picked.is_empty() || load(state, &msg.team_id, &repo, &msg.head_sha).await.is_some() { + if picked.is_empty() + || load(state, &msg.team_id, &repo, &msg.head_sha) + .await + .is_some() + { return; } let location = st @@ -408,8 +416,14 @@ mod tests { ]}] }); let held = Held(vec![ - ("pw/results.json".into(), serde_json::to_vec(&report).unwrap()), - ("pw/test-results/a-shows-it/test-finished-1.png".into(), png.clone()), + ( + "pw/results.json".into(), + serde_json::to_vec(&report).unwrap(), + ), + ( + "pw/test-results/a-shows-it/test-finished-1.png".into(), + png.clone(), + ), ]); let tests = common::e2e::parse::parse_any( "results.json", @@ -418,7 +432,7 @@ mod tests { ) .unwrap(); let id = tests[0].id(); - let got = images(&held, 1, 1, &[id.clone()]).await; + let got = images(&held, 1, 1, std::slice::from_ref(&id)).await; assert_eq!(got.get(&id), Some(&png)); // A test nobody asked for is not read. assert!(images(&held, 1, 1, &["other".into()]).await.is_empty()); From 61047863ed95c8a315799384eaa2ae821aa157d6 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:57:40 -0500 Subject: [PATCH 11/32] no-mistakes(review): Claim head record, use PR base, align record TTL --- services/common/src/e2e/shots.rs | 89 ++++++++++++++-- services/worker/src/passes/e2e_screens.rs | 124 ++++++++++++++-------- 2 files changed, 159 insertions(+), 54 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 0068f2a6f..d05e6cb43 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -24,10 +24,10 @@ use base64::Engine; use hmac::{Hmac, Mac}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use sha2::Sha256; +use sha2::{Digest, Sha256}; use super::coverage::TestMap; -use super::model::{test_id, Framework, Outcome, ParsedTest}; +use super::model::{test_id, Framework, HistoryEntry, Outcome, ParsedTest}; /// Largest image kept. pub const MAX_IMAGE: usize = 5 * 1024 * 1024; @@ -553,7 +553,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree ), None => ( String::new(), - format!("No screenshot of this test from a passing run on {base}"), + format!("No passing run on {base} with a screenshot of this test yet"), ), }; let runs = [ @@ -578,12 +578,31 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree } } -/// The key an image is kept under in the install's bucket. -pub fn object_key(team: &str, repo: &str, pr: u64, sha: &str, side: &str, ext: &str) -> String { +/// The newest run of a test on `branch` that passed: where its Before +/// screenshot is read. +pub fn newest_passing<'a>(history: &'a [HistoryEntry], branch: &str) -> Option<&'a HistoryEntry> { + history.iter().rev().find(|e| { + e.branch == branch && !e.bad_run && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) + }) +} + +/// The key an image of test `test` is kept under in the install's bucket; +/// two tests never share one. +pub fn object_key( + team: &str, + repo: &str, + pr: u64, + sha: &str, + test: &str, + side: &str, + ext: &str, +) -> String { + let test = hex::encode(Sha256::digest(test.as_bytes())); format!( - "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{side}.{ext}", + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{}/{side}.{ext}", team_folder(team), - sha.get(..12).unwrap_or(sha) + sha.get(..12).unwrap_or(sha), + &test[..16] ) } @@ -890,14 +909,22 @@ mod tests { assert!(before.is_empty()); assert_eq!( before_alt, - "No screenshot of this test from a passing run on main" + "No passing run on main with a screenshot of this test yet" ); } #[test] fn a_link_reads_one_image_of_its_own_team_until_it_expires() { - let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "after", "png"); - assert_eq!(key, "e2e-shots/TEAM_a/o/r/7/0123456789ab/after.png"); + let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "t", "after", "png"); + // sha256("t") = e3b98a4da31a127d... + assert_eq!( + key, + "e2e-shots/TEAM_a/o/r/7/0123456789ab/e3b98a4da31a127d/after.png" + ); + assert_ne!( + key, + object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "u", "after", "png") + ); let t = sign("s", "TEAM#a", &key, 100); assert_eq!(verify("s", &t, 99), Ok(key.clone())); assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); @@ -916,6 +943,48 @@ mod tests { .starts_with("https://api.example.com/webhooks/ci/tests/screenshot?t=")); } + #[test] + fn before_comes_from_the_newest_passing_run_on_the_pull_requests_base() { + let e = |run: &str, branch: &str, outcome, bad_run| HistoryEntry { + run_key: run.into(), + sha: "s".into(), + branch: branch.into(), + pr: None, + at: "t".into(), + outcome, + bad_run, + attempts: vec![], + }; + let history = vec![ + e("1-1", "develop", Outcome::Passed, false), + e("2-1", "develop", Outcome::Failed, false), + e("3-1", "develop", Outcome::Passed, true), + e("4-1", "main", Outcome::Passed, false), + ]; + // A pull request into develop never shows main's newer run. + assert_eq!( + newest_passing(&history, "develop").map(|e| e.run_key.as_str()), + Some("1-1") + ); + assert_eq!( + newest_passing(&history, "main").map(|e| e.run_key.as_str()), + Some("4-1") + ); + assert_eq!(newest_passing(&history, "release"), None); + let k = Kept { + base: "develop".into(), + ..Default::default() + }; + let crate::pr_body::Screens::Images { before_alt, .. } = screens(&k, |key| key.into()) + else { + panic!("images"); + }; + assert_eq!( + before_alt, + "No passing run on develop with a screenshot of this test yet" + ); + } + #[test] fn only_real_images_are_kept() { assert_eq!(image_type(PNG), Some("image/png")); diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 5c339c2d3..833d9ebbc 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -5,11 +5,13 @@ //! When a run on the pull request's head is read (`e2e::ingest`), the //! tests that show the change are chosen ([`shots::pick`]), and the first //! one with a screenshot on the head is kept with its screenshot from the -//! newest passing run on the default branch, when one is kept there too. +//! newest passing run on the pull request's base branch, when one is kept +//! there too. //! The images go to the install's own bucket, the record to the settings //! table for the head, and the description is rebuilt: its table links each //! image through the API with a signed link that expires -//! ([`screens_for`]). A head keeps the first pair found; a later run on the +//! ([`screens_for`]). A head keeps the first pair found: its record is +//! claimed before any image is kept, so a later or concurrent run on the //! same head changes nothing. use std::collections::HashMap; @@ -17,7 +19,7 @@ use std::collections::HashMap; use aws_sdk_dynamodb::types::AttributeValue; use common::e2e::coverage::TestMap; use common::e2e::messages::TestIngest; -use common::e2e::model::{Outcome, ParsedTest}; +use common::e2e::model::ParsedTest; use common::e2e::report_source::Location; use common::e2e::shots::{self, Image, Kept, Side}; use common::e2e::store::Store; @@ -29,8 +31,6 @@ use crate::WorkerState; /// Tests tried for a screenshot on the head. const MAX_TRIED: usize = 3; -/// How long the record of a head is kept. -const RECORD_DAYS: i64 = 90; fn record_sk(repo: &str, sha: &str) -> String { format!("E2E_SHOTS#{repo}#{sha}") @@ -50,9 +50,10 @@ pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> serde_json::from_str(item.get("data")?.as_s().ok()?).ok() } -async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) { - let ttl = (chrono::Utc::now() + chrono::Duration::days(RECORD_DAYS)).timestamp(); - if let Err(e) = state +/// Saves the record of a head unless one is there; whether this one is. +/// The record lives as long as its links work. +async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) -> bool { + state .dynamo .put_item() .table_name(&state.config.settings_table_name) @@ -62,11 +63,26 @@ async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kep "data", super::attr_s(&serde_json::to_string(k).unwrap_or_default()), ) - .item("ttl", AttributeValue::N(ttl.to_string())) + .item("ttl", AttributeValue::N(k.expires_at.to_string())) + .condition_expression("attribute_not_exists(sk)") + .send() + .await + .is_ok() +} + +/// Drops a claimed record whose images could not be kept, so a later run +/// on the head can keep its own. +async fn release(state: &WorkerState, team_id: &str, repo: &str, sha: &str) { + if let Err(e) = state + .dynamo + .delete_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&record_sk(repo, sha))) .send() .await { - warn!(error = %e, "Could not save the end-to-end screenshots of a head"); + warn!(error = %e, "Could not drop the record of a head whose screenshots were not kept"); } } @@ -225,28 +241,25 @@ async fn images( out } -/// Keeps one image in the install's bucket; its key. -async fn put( - state: &WorkerState, - key_of: impl Fn(&str) -> String, - bytes: Vec, -) -> Option { - let content_type = shots::image_type(&bytes)?; - let key = key_of(shots::extension(content_type)); +/// Keeps one image in the install's bucket under `key`; whether it was. +async fn put(state: &WorkerState, key: &str, bytes: Vec) -> bool { + let Some(content_type) = shots::image_type(&bytes) else { + return false; + }; match state .s3 .put_object() .bucket(&state.config.bucket_name) - .key(&key) + .key(key) .content_type(content_type) .body(bytes.into()) .send() .await { - Ok(_) => Some(key), + Ok(_) => true, Err(e) => { warn!(error = %e, "Could not keep an end-to-end screenshot"); - None + false } } } @@ -320,19 +333,24 @@ pub async fn keep( info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); return; }; - // The same test on the default branch: its newest passing run there. + // The same test on the branch the pull request goes into: its newest + // passing run there. + let Some(base) = gh + .get_pull_request(owner, name, h.pr) + .await + .ok() + .and_then(|p| p["base"]["ref"].as_str().map(str::to_string)) + .filter(|b| !b.is_empty()) + else { + warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); + return; + }; let newest = st .record(&msg.team_id, &scoped(t)) .await .ok() .flatten() - .and_then(|r| { - r.history.into_iter().rev().find(|e| { - e.branch == msg.default_branch - && !e.bad_run - && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) - }) - }); + .and_then(|r| shots::newest_passing(&r.history, &base).cloned()); let mut before: Option<(Vec, String)> = None; if let Some(e) = newest { let (src, run_id, attempt, run_url) = if e.run_key.starts_with("up-") { @@ -357,33 +375,51 @@ pub async fn keep( .remove(&t.id()) .map(|b| (b, run_url)); } - let key_of = |side: &'static str| { - let (team, pr, sha) = (msg.team_id.clone(), h.pr, msg.head_sha.clone()); - let repo = repo.clone(); - move |ext: &str| shots::object_key(&team, &repo, pr, &sha, side, ext) + let key_of = |side: &str, bytes: &[u8]| { + shots::image_type(bytes).map(|ct| { + shots::object_key( + &msg.team_id, + &repo, + h.pr, + &msg.head_sha, + &t.id(), + side, + shots::extension(ct), + ) + }) }; - let Some(after_key) = put(state, key_of("after"), after_bytes).await else { + let Some(after_key) = key_of("after", &after_bytes) else { return; }; - let before = match before { - Some((b, run_url)) => put(state, key_of("before"), b) - .await - .map(|key| Side { key, run_url }), - None => None, - }; + let before = + before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); let kept = Kept { pr: h.pr, test: t.full_title(), why: why.words(), - base: msg.default_branch.clone(), - before, + base, + before: before.as_ref().map(|(_, key, run_url)| Side { + key: key.clone(), + run_url: run_url.clone(), + }), after: Side { - key: after_key, + key: after_key.clone(), run_url: msg.html_url.clone(), }, expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, }; - save(state, &msg.team_id, &repo, &msg.head_sha, &kept).await; + if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { + info!(repo = %repo, pr = h.pr, "Another run on this head kept its screenshots first"); + return; + } + let mut kept_all = put(state, &after_key, after_bytes).await; + if let Some((b, key, _)) = before { + kept_all = kept_all && put(state, &key, b).await; + } + if !kept_all { + release(state, &msg.team_id, &repo, &msg.head_sha).await; + return; + } info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); if let super::description::Reconciled::Failed(why) = super::description::rebuild_pr(state, gh, &msg.team_id, owner, name, h.pr).await From 9a53e86673ba5ff3a43b9922ae8d620d6b9c39aa Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:59:27 -0500 Subject: [PATCH 12/32] no-mistakes(review): Upload screenshots before claiming the head record --- services/common/src/e2e/shots.rs | 30 ++++++++++----- services/worker/src/passes/e2e.rs | 1 + services/worker/src/passes/e2e_screens.rs | 46 +++++++++++------------ 3 files changed, 43 insertions(+), 34 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index d05e6cb43..1c697b2ca 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -586,20 +586,22 @@ pub fn newest_passing<'a>(history: &'a [HistoryEntry], branch: &str) -> Option<& }) } -/// The key an image of test `test` is kept under in the install's bucket; -/// two tests never share one. +/// The key an image of test `test` from run `run` is kept under in the +/// install's bucket; two tests or two runs never share one. +#[allow(clippy::too_many_arguments)] pub fn object_key( team: &str, repo: &str, pr: u64, sha: &str, + run: &str, test: &str, side: &str, ext: &str, ) -> String { let test = hex::encode(Sha256::digest(test.as_bytes())); format!( - "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{}/{side}.{ext}", + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{run}/{}/{side}.{ext}", team_folder(team), sha.get(..12).unwrap_or(sha), &test[..16] @@ -915,16 +917,26 @@ mod tests { #[test] fn a_link_reads_one_image_of_its_own_team_until_it_expires() { - let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "t", "after", "png"); + let key = object_key( + "TEAM#a", + "o/r", + 7, + "0123456789abcdef", + "12-1", + "t", + "after", + "png", + ); // sha256("t") = e3b98a4da31a127d... assert_eq!( key, - "e2e-shots/TEAM_a/o/r/7/0123456789ab/e3b98a4da31a127d/after.png" - ); - assert_ne!( - key, - object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "u", "after", "png") + "e2e-shots/TEAM_a/o/r/7/0123456789ab/12-1/e3b98a4da31a127d/after.png" ); + let other = |run: &str, test: &str| { + object_key("TEAM#a", "o/r", 7, "0123456789abcdef", run, test, "after", "png") + }; + assert_ne!(key, other("12-1", "u")); + assert_ne!(key, other("13-1", "t")); let t = sign("s", "TEAM#a", &key, 100); assert_eq!(verify("s", &t, 99), Ok(key.clone())); assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index ca7a1e5a9..c40b46dd4 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -636,6 +636,7 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { &st, super::e2e_screens::Head { msg: &msg, + run_key: &run_key, pr, tests: &tests, reports: &reports, diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 833d9ebbc..643ef469a 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -10,9 +10,9 @@ //! The images go to the install's own bucket, the record to the settings //! table for the head, and the description is rebuilt: its table links each //! image through the API with a signed link that expires -//! ([`screens_for`]). A head keeps the first pair found: its record is -//! claimed before any image is kept, so a later or concurrent run on the -//! same head changes nothing. +//! ([`screens_for`]). A head keeps the first pair found: each run keeps its +//! images under its own keys, then saves the head's record only when none +//! is there, so a later or concurrent run on the same head changes nothing. use std::collections::HashMap; @@ -53,7 +53,7 @@ pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> /// Saves the record of a head unless one is there; whether this one is. /// The record lives as long as its links work. async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) -> bool { - state + match state .dynamo .put_item() .table_name(&state.config.settings_table_name) @@ -67,22 +67,16 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke .condition_expression("attribute_not_exists(sk)") .send() .await - .is_ok() -} - -/// Drops a claimed record whose images could not be kept, so a later run -/// on the head can keep its own. -async fn release(state: &WorkerState, team_id: &str, repo: &str, sha: &str) { - if let Err(e) = state - .dynamo - .delete_item() - .table_name(&state.config.settings_table_name) - .key("pk", super::attr_s(team_id)) - .key("sk", super::attr_s(&record_sk(repo, sha))) - .send() - .await { - warn!(error = %e, "Could not drop the record of a head whose screenshots were not kept"); + Ok(_) => true, + Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => { + info!(repo, "Another run on this head kept its screenshots first"); + false + } + Err(e) => { + warn!(error = %e, repo, "Could not save the end-to-end screenshots of a head"); + false + } } } @@ -267,6 +261,8 @@ async fn put(state: &WorkerState, key: &str, bytes: Vec) -> bool { /// Everything a run on a pull request's head brings for its table. pub struct Head<'a> { pub msg: &'a TestIngest, + /// This run's key in the store. + pub run_key: &'a str, pub pr: u64, pub tests: &'a [ParsedTest], /// The reports this run was read from (an upload's report). @@ -382,6 +378,7 @@ pub async fn keep( &repo, h.pr, &msg.head_sha, + h.run_key, &t.id(), side, shots::extension(ct), @@ -408,16 +405,15 @@ pub async fn keep( }, expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, }; - if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { - info!(repo = %repo, pr = h.pr, "Another run on this head kept its screenshots first"); + if !put(state, &after_key, after_bytes).await { return; } - let mut kept_all = put(state, &after_key, after_bytes).await; if let Some((b, key, _)) = before { - kept_all = kept_all && put(state, &key, b).await; + if !put(state, &key, b).await { + return; + } } - if !kept_all { - release(state, &msg.team_id, &repo, &msg.head_sha).await; + if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { return; } info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); From 4ab957e6dfdea6aa1020874a1fdd503102ff794b Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 02:01:02 -0500 Subject: [PATCH 13/32] no-mistakes(review): Detect lost claim race with the typed DynamoDB error --- services/worker/src/passes/e2e_screens.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 643ef469a..a0d786bfa 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -69,7 +69,10 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke .await { Ok(_) => true, - Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => { + Err(e) + if e.as_service_error() + .is_some_and(|s| s.is_conditional_check_failed_exception()) => + { info!(repo, "Another run on this head kept its screenshots first"); false } From 84abe428abe46ad44f508d6917cfe8b2e56df43a Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:12:40 -0500 Subject: [PATCH 14/32] Format the screenshot fixes with cargo fmt --- services/common/src/e2e/shots.rs | 11 ++++++++++- services/worker/src/passes/e2e_screens.rs | 3 +-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 1c697b2ca..1380f3949 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -933,7 +933,16 @@ mod tests { "e2e-shots/TEAM_a/o/r/7/0123456789ab/12-1/e3b98a4da31a127d/after.png" ); let other = |run: &str, test: &str| { - object_key("TEAM#a", "o/r", 7, "0123456789abcdef", run, test, "after", "png") + object_key( + "TEAM#a", + "o/r", + 7, + "0123456789abcdef", + run, + test, + "after", + "png", + ) }; assert_ne!(key, other("12-1", "u")); assert_ne!(key, other("13-1", "t")); diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index a0d786bfa..af447b5e1 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -391,8 +391,7 @@ pub async fn keep( let Some(after_key) = key_of("after", &after_bytes) else { return; }; - let before = - before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); + let before = before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); let kept = Kept { pr: h.pr, test: t.full_title(), From ec2a84c2b05c2220c7958ce9039fece76c533910 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:16:47 -0500 Subject: [PATCH 15/32] no-mistakes(review): Pick screenshot test against PR base, fetch PR once --- services/worker/src/passes/e2e.rs | 20 +++++----- services/worker/src/passes/e2e_screens.rs | 47 ++++++++++++++--------- 2 files changed, 38 insertions(+), 29 deletions(-) diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index c40b46dd4..e27e13f46 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -622,7 +622,11 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { if run.rescued { note_rescued(&st, &gh, &msg, &run, pr).await; } - let own = is_own_pr(&gh, &msg, pr).await; + let pull = gh + .get_pull_request(&msg.repo_owner, &msg.repo_name, pr) + .await + .ok(); + let own = is_own_pr(&msg, pull.as_ref()); // A run that failed only on quarantined tests needs no fix or re-run. if failed > 0 && !run.rescued && own { own_pr_failures(state, &gh, &msg, &run, pr, &lines, &tests).await; @@ -640,6 +644,7 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { pr, tests: &tests, reports: &reports, + pull: pull.as_ref(), changed: &changed, map: map.as_ref(), }, @@ -2382,16 +2387,9 @@ async fn recommend(st: &Store<'_>, team: &str, rec: Recommendation) { /// Whether the PR is one CoderHelm opened: a branch in the default shape, or /// a PR whose author is CoderHelm's app (a team's own branch pattern). -async fn is_own_pr(gh: &GitHubClient, msg: &TestIngest, pr: u64) -> bool { - if msg - .head_branch - .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) - { - return true; - } - gh.get_pull_request(&msg.repo_owner, &msg.repo_name, pr) - .await - .is_ok_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) +fn is_own_pr(msg: &TestIngest, pull: Option<&serde_json::Value>) -> bool { + msg.head_branch.starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) + || pull.is_some_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) } async fn recommend_from_pr( diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index af447b5e1..08561b3a5 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -270,7 +270,9 @@ pub struct Head<'a> { pub tests: &'a [ParsedTest], /// The reports this run was read from (an upload's report). pub reports: &'a [(String, Vec)], - /// The files the pull request changes. + /// The pull request, as GitHub returns it. + pub pull: Option<&'a serde_json::Value>, + /// The files the head changes against the default branch. pub changed: &'a [String], pub map: Option<&'a TestMap>, } @@ -291,14 +293,34 @@ pub async fn keep( if state.secrets.jwt_secret.is_empty() || msg.head_sha.is_empty() { return; } - let picked = shots::pick(h.tests, h.changed, h.map); - if picked.is_empty() - || load(state, &msg.team_id, &repo, &msg.head_sha) - .await - .is_some() + if load(state, &msg.team_id, &repo, &msg.head_sha) + .await + .is_some() { return; } + // The branch the pull request goes into: the tests its change touches + // are read against it, and the Before image comes from it. + let Some(base) = h + .pull + .and_then(|p| p["base"]["ref"].as_str()) + .filter(|b| !b.is_empty()) + .map(str::to_string) + else { + warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); + return; + }; + let changed = if base == msg.default_branch { + h.changed.to_vec() + } else { + gh.compare_changed_files(owner, name, &base, &msg.head_sha) + .await + .unwrap_or_default() + }; + let picked = shots::pick(h.tests, &changed, h.map); + if picked.is_empty() { + return; + } let location = st .settings(&msg.team_id) .await @@ -332,18 +354,7 @@ pub async fn keep( info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); return; }; - // The same test on the branch the pull request goes into: its newest - // passing run there. - let Some(base) = gh - .get_pull_request(owner, name, h.pr) - .await - .ok() - .and_then(|p| p["base"]["ref"].as_str().map(str::to_string)) - .filter(|b| !b.is_empty()) - else { - warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); - return; - }; + // The same test on the base branch: its newest passing run there. let newest = st .record(&msg.team_id, &scoped(t)) .await From a659c729d7ea5e8857ecb96ebed700eca2f794af Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:51:57 -0500 Subject: [PATCH 16/32] no-mistakes(document): Format is_own_pr with cargo fmt --- services/worker/src/passes/e2e.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index e27e13f46..c55b83c51 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -2388,7 +2388,8 @@ async fn recommend(st: &Store<'_>, team: &str, rec: Recommendation) { /// Whether the PR is one CoderHelm opened: a branch in the default shape, or /// a PR whose author is CoderHelm's app (a team's own branch pattern). fn is_own_pr(msg: &TestIngest, pull: Option<&serde_json::Value>) -> bool { - msg.head_branch.starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) + msg.head_branch + .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) || pull.is_some_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) } From 09240ceb85197a8493e965e34a4d25e79e71a586 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Tue, 17 Nov 2026 16:41:17 -0500 Subject: [PATCH 17/32] Keep end-to-end screenshots on the screenshots ref, under the preview's pages Review asked for one hosting model and for the pair not to hide the preview's page captures. - The Before and After images are committed to refs/coderhelm/screenshots beside the preview's captures and linked by commit, so only people who can read the repository see them. The public screenshot route, its signed links, the bucket copies and their lifecycle rule are gone. - preview::keep_on_ref is the one way both write that ref: blobs, a commit on top of the ref, and a move without force (advance_own_ref), tried again on top when another writer moved it, so no writer's commit is dropped and no image link breaks. - The pair is its own fact (e2e_screens), rendered as a table under the preview's pages and never instead of them; it takes the place of a "No screenshot" line. The preview's pages now win over a set screens table. - An ingest reads the pull request only when it needs it: a failure on a branch that is not CoderHelm's shape, or a report that carries screenshots. CiReports gets the run's real attempt. --- infra/lib/storage-stack.ts | 7 - services/common/src/e2e/shots.rs | 225 ++++++---------------- services/common/src/pr_body.rs | 60 +++++- services/common/src/pr_facts.rs | 44 ++++- services/gateway/src/main.rs | 3 - services/gateway/src/routes/tests.rs | 60 ------ services/worker/src/clients/github.rs | 44 +++-- services/worker/src/passes/description.rs | 4 +- services/worker/src/passes/e2e.rs | 34 +++- services/worker/src/passes/e2e_screens.rs | 119 +++++------- services/worker/src/passes/preview.rs | 105 +++++++--- 11 files changed, 331 insertions(+), 374 deletions(-) diff --git a/infra/lib/storage-stack.ts b/infra/lib/storage-stack.ts index b467b1b2c..e15166b02 100644 --- a/infra/lib/storage-stack.ts +++ b/infra/lib/storage-stack.ts @@ -133,13 +133,6 @@ export class StorageStack extends cdk.Stack { expiration: cdk.Duration.days(2), noncurrentVersionExpiration: cdk.Duration.days(1), }, - { - // End-to-end screenshots in pull request descriptions: their links - // work for a year (common::e2e::shots), the images a month longer. - prefix: "e2e-shots/", - expiration: cdk.Duration.days(395), - noncurrentVersionExpiration: cdk.Duration.days(1), - }, { // Move old run artifacts to Infrequent Access after 90 days transitions: [ diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 1380f3949..8ed5ac2dd 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -15,13 +15,13 @@ //! ([`ParsedTest::id`]), and [`pick`] chooses the tests that show the change: //! a test the change edits, a test the repository's test map ties to the //! changed files, or a test whose name shares a word with a changed UI file. -//! The worker keeps the images in the install's own bucket -//! ([`object_key`]); the description links them with a signed link -//! ([`sign`]) that the API serves at [`LINK_PATH`] until it expires. +//! The worker commits the images to the ref CoderHelm keeps its pull +//! request screenshots on in the repository itself (`refs/coderhelm/screenshots`, +//! next to the preview's page captures, at [`ref_path`]) and links them by +//! commit, so only people who can read the repository see them. -use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::engine::general_purpose::STANDARD; use base64::Engine; -use hmac::{Hmac, Mac}; use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest, Sha256}; @@ -31,14 +31,6 @@ use super::model::{test_id, Framework, HistoryEntry, Outcome, ParsedTest}; /// Largest image kept. pub const MAX_IMAGE: usize = 5 * 1024 * 1024; -/// Where the images are kept in the install's bucket. -pub const KEY_PREFIX: &str = "e2e-shots"; -/// How long an image link works (the bucket keeps the images a little -/// longer, see `infra/lib/storage-stack.ts`). -pub const LINK_VALID_SECS: i64 = 365 * 86_400; -/// The path the API serves an image at. -pub const LINK_PATH: &str = "/webhooks/ci/tests/screenshot"; -const MAX_TOKEN_LEN: usize = 2048; /// One test's screenshot in one report. #[derive(Debug, Clone, PartialEq, Eq)] @@ -503,8 +495,9 @@ pub fn pick<'a>( /// One side of the table: the kept image and the run it came from. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Side { - /// The image's key in the install's bucket. - pub key: String, + /// The image's address on the screenshots ref, at the commit that + /// added it. + pub src: String, /// The run's page; empty for an upload with no run page. #[serde(default)] pub run_url: String, @@ -525,9 +518,6 @@ pub struct Kept { pub before: Option, /// The test on the head. pub after: Side, - /// When the links stop working (unix seconds); fixed when kept, so the - /// description is the same text on every rebuild. - pub expires_at: i64, } fn md_link(text: &str, url: &str) -> String { @@ -538,8 +528,8 @@ fn md_link(text: &str, url: &str) -> String { } } -/// The table for `k`; `link` gives an image's link from its key. -pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Screens { +/// The Before and After table for `k`. +pub fn screens(k: &Kept) -> crate::pr_body::Screens { let test = k.test.replace('`', "'"); let base: &str = if k.base.is_empty() { "the base branch" @@ -548,7 +538,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree }; let (before, before_alt) = match &k.before { Some(s) => ( - link(&s.key), + s.src.clone(), format!("{test} on {base}, before this change"), ), None => ( @@ -569,7 +559,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree crate::pr_body::Screens::Images { before, before_alt, - after: link(&k.after.key), + after: k.after.src.clone(), after_alt: format!("{test} on this head"), caption: format!( "Screenshots of the end-to-end test `{test}`, chosen because {}: {runs}.", @@ -586,104 +576,28 @@ pub fn newest_passing<'a>(history: &'a [HistoryEntry], branch: &str) -> Option<& }) } -/// The key an image of test `test` from run `run` is kept under in the -/// install's bucket; two tests or two runs never share one. -#[allow(clippy::too_many_arguments)] -pub fn object_key( - team: &str, - repo: &str, - pr: u64, - sha: &str, - run: &str, - test: &str, - side: &str, - ext: &str, -) -> String { +/// Where an image of test `test` from run `run` is kept on the screenshots +/// ref, beside the preview's captures of the same head (`pr-//`); +/// two tests or two runs never share a path. +pub fn ref_path(pr: u64, sha: &str, run: &str, test: &str, side: &str, ext: &str) -> String { let test = hex::encode(Sha256::digest(test.as_bytes())); + let run: String = run + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect(); format!( - "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{run}/{}/{side}.{ext}", - team_folder(team), + "pr-{pr}/{}/e2e-{}-{run}-{side}.{ext}", sha.get(..12).unwrap_or(sha), &test[..16] ) } -fn team_folder(team: &str) -> String { - team.replace(['#', '/'], "_") -} - -// ── Signed links ────────────────────────────────────────────────────────── - -type HmacSha256 = Hmac; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TokenError { - Malformed, - BadSignature, - Expired, -} - -fn mac(secret: &str, payload: &str) -> HmacSha256 { - // A key for screenshot links only, so a link never stands in for a - // session or for any other signed link. - let mut kdf = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC takes any key"); - kdf.update(b"coderhelm/e2e-screenshot/v1"); - let key = kdf.finalize().into_bytes(); - let mut m = HmacSha256::new_from_slice(&key).expect("HMAC takes any key"); - m.update(payload.as_bytes()); - m -} - -/// A token that reads one kept image of one team until `expires_at`. The -/// token is `base64url(team \n key \n expiry) . base64url(HMAC-SHA256)`. -pub fn sign(secret: &str, team: &str, key: &str, expires_at: i64) -> String { - let payload = format!("{team}\n{key}\n{expires_at}"); - let sig = mac(secret, &payload).finalize().into_bytes(); - format!( - "{}.{}", - URL_SAFE_NO_PAD.encode(payload.as_bytes()), - URL_SAFE_NO_PAD.encode(sig) - ) -} - -/// The image key a token reads, if it is genuine, current, and names one of -/// its own team's kept images. -pub fn verify(secret: &str, token: &str, now: i64) -> Result { - if token.is_empty() || token.len() > MAX_TOKEN_LEN { - return Err(TokenError::Malformed); - } - let (body, sig) = token.split_once('.').ok_or(TokenError::Malformed)?; - let payload = URL_SAFE_NO_PAD - .decode(body) - .ok() - .and_then(|b| String::from_utf8(b).ok()) - .ok_or(TokenError::Malformed)?; - let sig = URL_SAFE_NO_PAD - .decode(sig) - .map_err(|_| TokenError::Malformed)?; - mac(secret, &payload) - .verify_slice(&sig) - .map_err(|_| TokenError::BadSignature)?; - let p: Vec<&str> = payload.split('\n').collect(); - let [team, key, exp] = p.as_slice() else { - return Err(TokenError::Malformed); - }; - let exp: i64 = exp.parse().map_err(|_| TokenError::Malformed)?; - let own = format!("{KEY_PREFIX}/{}/", team_folder(team)); - if team.is_empty() || !key.starts_with(&own) || key.split('/').any(|s| s == "..") { - return Err(TokenError::Malformed); - } - if now >= exp { - return Err(TokenError::Expired); - } - Ok(key.to_string()) -} - -/// The link for a token on this deployment's API. -pub fn url(api: &str, token: &str) -> String { - format!("{}{LINK_PATH}?t={token}", api.trim_end_matches('/')) -} - #[cfg(test)] mod tests { use super::*; @@ -868,16 +782,15 @@ mod tests { why: Why::Named("checkout".into()).words(), base: "main".into(), before: Some(Side { - key: "e2e-shots/T/o/r/7/abc/before.png".into(), + src: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-x-1-1-before.png?raw=true".into(), run_url: "https://github.com/o/r/actions/runs/1".into(), }), after: Side { - key: "e2e-shots/T/o/r/7/abc/after.png".into(), + src: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-x-2-1-after.png?raw=true".into(), run_url: "https://github.com/o/r/actions/runs/2".into(), }, - expires_at: 10, }; - let s = screens(&k, |key| format!("https://api.example.com/x?k={key}")); + let s = screens(&k); let crate::pr_body::Screens::Images { before, after, @@ -888,20 +801,17 @@ mod tests { else { panic!("images"); }; - assert!(before.ends_with("before.png")); - assert!(after.ends_with("after.png")); + assert!(before.ends_with("before.png?raw=true")); + assert!(after.ends_with("after.png?raw=true")); assert_eq!(after_alt, "Checkout › pays by 'card' on this head"); assert_eq!( caption, "Screenshots of the end-to-end test `Checkout › pays by 'card'`, chosen because the test and a changed UI file share the word \"checkout\": [main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)." ); - let none = screens( - &Kept { - before: None, - ..k.clone() - }, - |key| key.to_string(), - ); + let none = screens(&Kept { + before: None, + ..k.clone() + }); let crate::pr_body::Screens::Images { before, before_alt, .. } = none @@ -916,52 +826,26 @@ mod tests { } #[test] - fn a_link_reads_one_image_of_its_own_team_until_it_expires() { - let key = object_key( - "TEAM#a", - "o/r", - 7, - "0123456789abcdef", - "12-1", - "t", - "after", - "png", - ); + fn each_test_and_run_has_its_own_path_beside_the_preview_captures() { + let path = ref_path(7, "0123456789abcdef", "12-1", "t", "after", "png"); // sha256("t") = e3b98a4da31a127d... assert_eq!( - key, - "e2e-shots/TEAM_a/o/r/7/0123456789ab/12-1/e3b98a4da31a127d/after.png" + path, + "pr-7/0123456789ab/e2e-e3b98a4da31a127d-12-1-after.png" + ); + assert_ne!( + path, + ref_path(7, "0123456789abcdef", "12-1", "u", "after", "png") + ); + assert_ne!( + path, + ref_path(7, "0123456789abcdef", "13-1", "t", "after", "png") + ); + // An upload's run key is kept to letters, digits and dashes. + assert_eq!( + ref_path(7, "0123456789abcdef", "up-9/../x", "t", "before", "jpg"), + "pr-7/0123456789ab/e2e-e3b98a4da31a127d-up-9____x-before.jpg" ); - let other = |run: &str, test: &str| { - object_key( - "TEAM#a", - "o/r", - 7, - "0123456789abcdef", - run, - test, - "after", - "png", - ) - }; - assert_ne!(key, other("12-1", "u")); - assert_ne!(key, other("13-1", "t")); - let t = sign("s", "TEAM#a", &key, 100); - assert_eq!(verify("s", &t, 99), Ok(key.clone())); - assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); - assert_eq!(verify("other", &t, 99), Err(TokenError::BadSignature)); - // Signed, but for another team's image or anything else in the bucket. - let theirs = sign("s", "TEAM#a", "e2e-shots/TEAM_b/o/r/1/x/after.png", 100); - assert_eq!(verify("s", &theirs, 99), Err(TokenError::Malformed)); - let raw = sign("s", "TEAM#a", "e2e/TEAM_a/o/r/raw/1-1/report.json", 100); - assert_eq!(verify("s", &raw, 99), Err(TokenError::Malformed)); - let up = sign("s", "TEAM#a", "e2e-shots/TEAM_a/../../secret", 100); - assert_eq!(verify("s", &up, 99), Err(TokenError::Malformed)); - // An unsubscribe token never reads an image. - let u = crate::unsubscribe::sign("s", "TEAM#a", "USER#1", "weekly_summary", 100); - assert!(verify("s", &u, 99).is_err()); - assert!(url("https://api.example.com/", &t) - .starts_with("https://api.example.com/webhooks/ci/tests/screenshot?t=")); } #[test] @@ -996,8 +880,7 @@ mod tests { base: "develop".into(), ..Default::default() }; - let crate::pr_body::Screens::Images { before_alt, .. } = screens(&k, |key| key.into()) - else { + let crate::pr_body::Screens::Images { before_alt, .. } = screens(&k) else { panic!("images"); }; assert_eq!( diff --git a/services/common/src/pr_body.rs b/services/common/src/pr_body.rs index 7435e4c37..653bc4d07 100644 --- a/services/common/src/pr_body.rs +++ b/services/common/src/pr_body.rs @@ -301,6 +301,9 @@ pub struct Body { pub rows: Vec, /// `Some` for a UI change. pub screens: Option, + /// A Before and After pair from the end-to-end run on the head, shown + /// under [`Body::screens`] (never instead of the preview's pages). + pub e2e_screens: Option, /// The first fold's name ([`NOTES`] when empty). pub notes_label: String, /// Generated text at the top of the first fold. @@ -1067,8 +1070,14 @@ fn blocks(b: &Body) -> Blocks { if !how.is_empty() { verification.push_str(&format!("\n\nHow to check: {how}.")); } - if let Some(s) = &b.screens { - out.screens = screens_markdown(s); + // The preview's pages first, then the end-to-end pair under them; a + // "No screenshot" line goes when the pair is there. + let parts: Vec = match (&b.screens, &b.e2e_screens) { + (Some(Screens::Missing(_)), Some(e)) | (None, Some(e)) => vec![screens_markdown(e)], + (s, e) => s.iter().chain(e).map(screens_markdown).collect(), + }; + if !parts.is_empty() { + out.screens = parts.join("\n\n"); verification.push_str(&format!("\n\n{}", out.screens)); } out.verification = verification; @@ -1887,6 +1896,53 @@ mod tests { assert_eq!(defects(&body, "d78bb24"), Vec::::new(), "{body}"); } + /// The end-to-end pair is an addition: under the preview's pages, never + /// instead of them; it takes the place of a "No screenshot" line. + #[test] + fn the_end_to_end_pair_goes_under_the_preview_pages() { + let pair = Screens::Images { + before: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-1-before.png?raw=true".into(), + before_alt: "Checkout on main, before this change".into(), + after: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-1-after.png?raw=true".into(), + after_alt: "Checkout on this head".into(), + caption: "Screenshots of the end-to-end test `Checkout`, chosen because this change edits the test: this head's run.".into(), + }; + let body = |screens: Option| Body { + head: "d78bb24".into(), + summary: "Shows the total on the checkout page.".into(), + level: Level::Low, + risk: "one page's layout only".into(), + rollback: "revert this PR".into(), + rows: vec![Row { + check: "Unit tests (CI)".into(), + outcome: Outcome::Passed, + detail: String::new(), + }], + screens, + e2e_screens: Some(pair.clone()), + ..Default::default() + }; + let r = render(&body(Some(Screens::Pages(vec![( + "/checkout".into(), + "https://img.example.com/d.png".into(), + "https://img.example.com/p.png".into(), + )])))); + let pages = r.visible.clone(); + let at = |v: &str, h: &str| v.find(h).unwrap_or_else(|| panic!("{h}: {v}")); + assert!(at(&pages, "| Page | Desktop | Phone |") < at(&pages, "| Before | After |")); + assert!(pages.contains("Screenshots of the end-to-end test `Checkout`")); + let whole = format!("{pages}\n\n{}", r.footer); + assert_eq!(defects(&whole, "d78bb24"), Vec::::new(), "{whole}"); + let missing = render(&body(Some(Screens::Missing( + "CoderHelm had no runnable preview to capture for this run".into(), + )))) + .visible; + assert!(!missing.contains("No screenshot"), "{missing}"); + assert!(missing.contains("| Before | After |"), "{missing}"); + let alone = render(&body(None)).visible; + assert!(alone.contains("| Before | After |"), "{alone}"); + } + /// The layout: Problem, Changes, (Needed from you), Risk, Verification, /// two or three lines each; the preview's link, its screenshots, what /// the pull request waits on and how to check are in Verification. diff --git a/services/common/src/pr_facts.rs b/services/common/src/pr_facts.rs index 612bc53df..597c9855f 100644 --- a/services/common/src/pr_facts.rs +++ b/services/common/src/pr_facts.rs @@ -373,6 +373,10 @@ pub struct Facts { /// A UI change's screenshots, or why there are none. #[serde(default)] pub screens: Option, + /// A Before and After pair from the end-to-end run on the head + /// (`e2e::shots`): shown under the preview's pages, never instead. + #[serde(default)] + pub e2e_screens: Option, /// What the pull request waits on, one line (`crate::waiting_line`). #[serde(default)] pub waiting: String, @@ -1480,8 +1484,8 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { .iter() .any(|x| crate::preview::is_user_visible(&x.path)); let screens = match (&f.screens, &f.preview) { - (Some(s), _) => Some(s.clone()), - (None, Some(p)) => screens_of(p, visible), + (s, Some(p)) => screens_of(p, visible).or_else(|| s.clone()), + (Some(s), None) => Some(s.clone()), (None, None) if f.files.iter().any(|x| is_ui(&x.path)) => Some(Screens::Missing( "CoderHelm had no runnable preview to capture for this run".into(), )), @@ -1597,6 +1601,7 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { rollback, rows: rows(f), screens, + e2e_screens: f.e2e_screens.clone(), notes_label, notes_top, evidence: evidence.join("\n\n"), @@ -1642,6 +1647,41 @@ mod tests { } } + /// The preview's captured pages are never hidden by another table: the + /// end-to-end pair travels on its own and is shown under them. + #[test] + fn the_preview_pages_win_and_the_end_to_end_pair_is_kept_beside_them() { + use crate::pr_body::Screens; + let pair = Screens::Images { + before: String::new(), + before_alt: "No passing run on main with a screenshot of this test yet".into(), + after: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-1-after.png?raw=true".into(), + after_alt: "Checkout on this head".into(), + caption: String::new(), + }; + let mut f = ticket_facts(); + f.screens = Some(pair.clone()); + f.e2e_screens = Some(pair.clone()); + f.preview = Some(crate::preview::State { + shots: vec![crate::preview::Shot { + page: "/checkout".into(), + width: "desktop".into(), + src: "https://img.example.com/d.png".into(), + }], + ..Default::default() + }); + let b = body_of(&f, &[]); + assert!( + matches!(b.screens, Some(Screens::Pages(_))), + "{:?}", + b.screens + ); + assert_eq!(b.e2e_screens, Some(pair.clone())); + // Without a preview, a table someone set still shows. + f.preview = None; + assert_eq!(body_of(&f, &[]).screens, Some(pair)); + } + fn ticket_facts() -> Facts { Facts { head: "abc1234def".into(), diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 153d41791..6ffc07112 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1614,9 +1614,6 @@ fn build_app(state: Arc) -> Router { // CI calls signed with a GitHub Actions OIDC token .route("/ci/tests/results", post(routes::tests::ci_upload)) .route("/ci/tests/quarantine", get(routes::tests::ci_quarantine)) - // A screenshot in the Before and After table of CoderHelm's own pull - // request; the signed link is the credential (routes::tests). - .route("/ci/tests/screenshot", get(routes::tests::ci_screenshot)) // Events CoderHelm's relay forwards to a hybrid install, and its // ownership proof (routes::hybrid_install). .route("/relay", post(routes::hybrid_install::intake)) diff --git a/services/gateway/src/routes/tests.rs b/services/gateway/src/routes/tests.rs index 4fec457c2..44bdbb1a9 100644 --- a/services/gateway/src/routes/tests.rs +++ b/services/gateway/src/routes/tests.rs @@ -1382,66 +1382,6 @@ pub async fn ci_quarantine( })) } -#[derive(Deserialize)] -pub struct ShotQuery { - #[serde(default)] - t: String, -} - -/// GET /webhooks/ci/tests/screenshot?t= — one end-to-end screenshot kept for -/// the Before and After table of CoderHelm's own pull request -/// (`common::e2e::shots`). Public, because GitHub fetches the image for the -/// pull request's readers: the signed token is the credential, and it names -/// one image of one team until it expires. Anything else is a 404 that says -/// nothing. -pub async fn ci_screenshot( - State(state): State>, - Query(q): Query, -) -> axum::response::Response { - use axum::http::header; - use axum::response::IntoResponse; - use common::e2e::shots; - let not_found = || (StatusCode::NOT_FOUND, "Not found").into_response(); - let secret = state.secrets.jwt_secret.as_str(); - if secret.is_empty() { - return not_found(); - } - let key = match shots::verify(secret, q.t.trim(), chrono::Utc::now().timestamp()) { - Ok(k) => k, - Err(e) => { - info!(reason = ?e, "Screenshot link refused"); - return not_found(); - } - }; - let Ok(obj) = state - .s3 - .get_object() - .bucket(&state.config.bucket_name) - .key(&key) - .send() - .await - else { - return not_found(); - }; - let Ok(body) = obj.body.collect().await else { - return not_found(); - }; - let bytes = body.into_bytes(); - let Some(content_type) = shots::image_type(&bytes) else { - return not_found(); - }; - ( - StatusCode::OK, - [ - (header::CONTENT_TYPE, content_type), - (header::CACHE_CONTROL, "public, max-age=86400"), - (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), - ], - bytes, - ) - .into_response() -} - #[cfg(test)] mod unit { use super::*; diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 449ceca56..34139ce4d 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3278,15 +3278,20 @@ impl GitHubClient { Ok(out) } - /// Points a ref outside `refs/heads/` (no workflow starts on it) at - /// `sha`, creating it when it doesn't exist. Only for CoderHelm's own - /// refs, such as the one its pull request screenshots are kept on. - pub async fn set_own_ref( + /// Moves a ref outside `refs/heads/` (no workflow starts on it; only for + /// CoderHelm's own refs, such as the one its pull request screenshots + /// are kept on) from `from` to `to` without force: GitHub refuses the + /// move when the ref no longer points at an ancestor of `to`, so a + /// commit another writer put on it in the meantime is never dropped. + /// With `from` `None` the ref is + /// created, and creating one that exists is refused the same way. + pub async fn advance_own_ref( &self, owner: &str, repo: &str, name: &str, - sha: &str, + from: Option<&str>, + to: &str, ) -> Result<(), Box> { let name = name.trim_start_matches("refs/"); if name.starts_with("heads/") || name.starts_with("tags/") || !name.contains('/') { @@ -3294,21 +3299,22 @@ impl GitHubClient { format!("`refs/{name}` is not a ref CoderHelm keeps its own files on").into(), ); } - let patched = self - .patch( - &format!("{API_BASE}/repos/{owner}/{repo}/git/refs/{name}"), - &serde_json::json!({"sha": sha, "force": true}), - ) - .await; - if patched.is_ok() { - return Ok(()); + match from { + Some(_) => self + .patch( + &format!("{API_BASE}/repos/{owner}/{repo}/git/refs/{name}"), + &serde_json::json!({"sha": to, "force": false}), + ) + .await + .map(|_| ()), + None => self + .post( + &format!("{API_BASE}/repos/{owner}/{repo}/git/refs"), + &serde_json::json!({"ref": format!("refs/{name}"), "sha": to}), + ) + .await + .map(|_| ()), } - self.post( - &format!("{API_BASE}/repos/{owner}/{repo}/git/refs"), - &serde_json::json!({"ref": format!("refs/{name}"), "sha": sha}), - ) - .await - .map(|_| ()) } /// The commit a ref outside `refs/heads/` points at, if it exists. diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index b3b74d046..0ae8f1aff 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -663,9 +663,7 @@ impl Gathered { super::description_facts::with_preview(&mut f, preview); super::description_facts::with_scope(&mut f, self.run.scope.as_ref(), &self.files); f.waiting = self.run.waiting.clone(); - if self.screens.is_some() { - f.screens = self.screens.clone(); - } + f.e2e_screens = self.screens.clone(); f } } diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index c55b83c51..138eaf569 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -622,18 +622,28 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { if run.rescued { note_rescued(&st, &gh, &msg, &run, pr).await; } - let pull = gh - .get_pull_request(&msg.repo_owner, &msg.repo_name, pr) - .await - .ok(); - let own = is_own_pr(&msg, pull.as_ref()); // A run that failed only on quarantined tests needs no fix or re-run. - if failed > 0 && !run.rescued && own { + let fix = failed > 0 && !run.rescued; + // Screenshots in this run's reports, for the description's table. + let shots = reports + .iter() + .any(|(n, b)| !common::e2e::shots::shots_in(n, b).is_empty()); + // The pull request is read only when one of them needs it: whose it + // is (unless the branch says), and its base for the screenshots. + let pull = if (fix && !own_branch(&msg)) || shots { + gh.get_pull_request(&msg.repo_owner, &msg.repo_name, pr) + .await + .ok() + } else { + None + }; + let own = is_own_pr(&msg, pull.as_ref()); + if fix && own { own_pr_failures(state, &gh, &msg, &run, pr, &lines, &tests).await; } // CoderHelm's own pull request shows the screenshots this run took // of the tests its change touches. - if own { + if shots && own { super::e2e_screens::keep( state, &gh, @@ -2385,11 +2395,17 @@ async fn recommend(st: &Store<'_>, team: &str, rec: Recommendation) { } } +/// Whether the run's branch is in CoderHelm's default shape: its pull +/// request is CoderHelm's without reading it. +fn own_branch(msg: &TestIngest) -> bool { + msg.head_branch + .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) +} + /// Whether the PR is one CoderHelm opened: a branch in the default shape, or /// a PR whose author is CoderHelm's app (a team's own branch pattern). fn is_own_pr(msg: &TestIngest, pull: Option<&serde_json::Value>) -> bool { - msg.head_branch - .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) + own_branch(msg) || pull.is_some_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) } diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 08561b3a5..a1da040f2 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -7,12 +7,14 @@ //! one with a screenshot on the head is kept with its screenshot from the //! newest passing run on the pull request's base branch, when one is kept //! there too. -//! The images go to the install's own bucket, the record to the settings -//! table for the head, and the description is rebuilt: its table links each -//! image through the API with a signed link that expires -//! ([`screens_for`]). A head keeps the first pair found: each run keeps its -//! images under its own keys, then saves the head's record only when none -//! is there, so a later or concurrent run on the same head changes nothing. +//! The images are committed to the screenshots ref in the repository +//! (`preview::SHOTS_REF`, next to the preview's page captures) and linked +//! by commit, so only people who can read the repository see them; the +//! record goes to the settings table for the head and the description is +//! rebuilt, the pair under the preview's pages ([`screens_for`]). A head +//! keeps the first pair found: each run commits its images under its own +//! paths, then saves the head's record only when none is there, so a later +//! or concurrent run on the same head changes nothing. use std::collections::HashMap; @@ -31,6 +33,9 @@ use crate::WorkerState; /// Tests tried for a screenshot on the head. const MAX_TRIED: usize = 3; +/// How long the record of a head is kept: the description of an open pull +/// request is rebuilt from it. +const RECORD_DAYS: i64 = 365; fn record_sk(repo: &str, sha: &str) -> String { format!("E2E_SHOTS#{repo}#{sha}") @@ -51,8 +56,8 @@ pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> } /// Saves the record of a head unless one is there; whether this one is. -/// The record lives as long as its links work. async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) -> bool { + let ttl = (chrono::Utc::now() + chrono::Duration::days(RECORD_DAYS)).timestamp(); match state .dynamo .put_item() @@ -63,7 +68,7 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke "data", super::attr_s(&serde_json::to_string(k).unwrap_or_default()), ) - .item("ttl", AttributeValue::N(k.expires_at.to_string())) + .item("ttl", AttributeValue::N(ttl.to_string())) .condition_expression("attribute_not_exists(sk)") .send() .await @@ -84,24 +89,16 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke } /// The Before and After table for a pull request's head, when a run on it -/// kept screenshots. `None` without a signing secret or a public API -/// address: GitHub fetches the images from the API, so a link must reach -/// it. +/// kept screenshots. pub async fn screens_for( state: &WorkerState, team_id: &str, repo: &str, sha: &str, ) -> Option { - let secret = state.secrets.jwt_secret.as_str(); - let api = common::public_urls::api_url(&state.config.stage); - if secret.is_empty() || !api.starts_with("https://") { - return None; - } - let k = load(state, team_id, repo, sha).await?; - Some(shots::screens(&k, |key| { - shots::url(api, &shots::sign(secret, team_id, key, k.expires_at)) - })) + load(state, team_id, repo, sha) + .await + .map(|k| shots::screens(&k)) } /// Report files held in memory: an uploaded report, or the raw reports kept @@ -238,29 +235,6 @@ async fn images( out } -/// Keeps one image in the install's bucket under `key`; whether it was. -async fn put(state: &WorkerState, key: &str, bytes: Vec) -> bool { - let Some(content_type) = shots::image_type(&bytes) else { - return false; - }; - match state - .s3 - .put_object() - .bucket(&state.config.bucket_name) - .key(key) - .content_type(content_type) - .body(bytes.into()) - .send() - .await - { - Ok(_) => true, - Err(e) => { - warn!(error = %e, "Could not keep an end-to-end screenshot"); - false - } - } -} - /// Everything a run on a pull request's head brings for its table. pub struct Head<'a> { pub msg: &'a TestIngest, @@ -290,7 +264,7 @@ pub async fn keep( let msg = h.msg; let (owner, name) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); let repo = format!("{owner}/{name}"); - if state.secrets.jwt_secret.is_empty() || msg.head_sha.is_empty() { + if msg.head_sha.is_empty() { return; } if load(state, &msg.team_id, &repo, &msg.head_sha) @@ -329,20 +303,20 @@ pub async fn keep( let location = location.as_ref(); // Where the team keeps the repository's reports, else the run's // artifacts: the same places the failure attribution reads. - let open = |run_id: u64| async move { + let open = |run_id: u64, attempt: u32| async move { if let Some(l @ Location::S3 { .. }) = location { let mut tried = Vec::new(); if let Some(r) = super::test_fix::open_s3(state, &msg.team_id, l, &mut tried).await { return Source::S3(Box::new(r)); } } - Source::Ci(CiReports::new(gh, owner, name, vec![(run_id, 1)])) + Source::Ci(CiReports::new(gh, owner, name, vec![(run_id, attempt)])) }; // The head's run. let head = if msg.upload_key.is_some() { Source::Held(Held(h.reports.to_vec())) } else { - open(msg.run_id).await + open(msg.run_id, msg.run_attempt).await }; let tried: Vec<&(&ParsedTest, shots::Why)> = picked.iter().take(MAX_TRIED).collect(); let ids: Vec = tried.iter().map(|(t, _)| t.id()).collect(); @@ -372,7 +346,7 @@ pub async fn keep( ) } else if let Some((run_id, attempt)) = run_of(&e.run_key) { ( - open(run_id).await, + open(run_id, attempt).await, run_id, attempt, format!("https://github.com/{repo}/actions/runs/{run_id}"), @@ -385,11 +359,11 @@ pub async fn keep( .remove(&t.id()) .map(|b| (b, run_url)); } - let key_of = |side: &str, bytes: &[u8]| { + // Both images in one commit on the screenshots ref, each at a path of + // its own test and run. + let path_of = |side: &str, bytes: &[u8]| { shots::image_type(bytes).map(|ct| { - shots::object_key( - &msg.team_id, - &repo, + shots::ref_path( h.pr, &msg.head_sha, h.run_key, @@ -399,33 +373,44 @@ pub async fn keep( ) }) }; - let Some(after_key) = key_of("after", &after_bytes) else { + let Some(after_path) = path_of("after", &after_bytes) else { return; }; - let before = before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); + let before = before.and_then(|(b, run_url)| path_of("before", &b).map(|p| (b, p, run_url))); + let mut files = vec![(after_path.clone(), after_bytes)]; + if let Some((b, p, _)) = &before { + files.push((p.clone(), b.clone())); + } + let short = msg.head_sha.get(..12).unwrap_or(&msg.head_sha); + let commit = match super::preview::keep_on_ref( + gh, + owner, + name, + &format!("End-to-end screenshots of #{} at {short}", h.pr), + &files, + ) + .await + { + Ok(c) => c, + Err(e) => { + warn!(error = %e, repo = %repo, pr = h.pr, "Could not keep the end-to-end screenshots on the screenshots ref"); + return; + } + }; let kept = Kept { pr: h.pr, test: t.full_title(), why: why.words(), base, - before: before.as_ref().map(|(_, key, run_url)| Side { - key: key.clone(), - run_url: run_url.clone(), + before: before.map(|(_, path, run_url)| Side { + src: super::preview::image_url(owner, name, &commit, &path), + run_url, }), after: Side { - key: after_key.clone(), + src: super::preview::image_url(owner, name, &commit, &after_path), run_url: msg.html_url.clone(), }, - expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, }; - if !put(state, &after_key, after_bytes).await { - return; - } - if let Some((b, key, _)) = before { - if !put(state, &key, b).await { - return; - } - } if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { return; } diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs index 3ee18abb0..fbf0ec429 100644 --- a/services/worker/src/passes/preview.rs +++ b/services/worker/src/passes/preview.rs @@ -669,7 +669,7 @@ async fn keep_images( files: &[(String, String)], ) -> Result, Box> { let short = head.get(..12).unwrap_or(head); - let mut entries: Vec<(String, Option)> = Vec::new(); + let mut images: Vec<(String, Vec)> = Vec::new(); let mut shots: Vec<(Shot, String)> = Vec::new(); for c in report.iter().filter(|c| (1..400).contains(&c.status)) { let Some((_, b64)) = files @@ -681,15 +681,7 @@ async fn keep_images( let clean: String = b64.chars().filter(|c| !c.is_whitespace()).collect(); let bytes = base64::engine::general_purpose::STANDARD.decode(clean)?; let path = format!("pr-{}/{short}/{}.png", p.number, c.name); - let sha = gh.put_blob(p.owner, p.repo, &bytes).await?; - entries.push(( - path.clone(), - Some(GitEntry { - mode: "100644".into(), - kind: "blob".into(), - sha, - }), - )); + images.push((path.clone(), bytes)); shots.push(( Shot { page: c.page.clone(), @@ -699,37 +691,88 @@ async fn keep_images( path, )); } - if entries.is_empty() { + if images.is_empty() { return Ok(Vec::new()); } - let parent = gh.own_ref(p.owner, p.repo, SHOTS_REF).await; - let base_tree = match &parent { - Some(c) => gh.commit_tree_parents(p.owner, p.repo, c).await?.0, - None => String::new(), - }; - let tree = gh.put_tree(p.owner, p.repo, &base_tree, &entries).await?; - let commit = gh - .put_commit( - p.owner, - p.repo, - &format!("Screenshots of #{} at {short}", p.number), - &tree, - &parent.into_iter().collect::>(), - ) - .await?; - gh.set_own_ref(p.owner, p.repo, SHOTS_REF, &commit).await?; + let commit = keep_on_ref( + gh, + p.owner, + p.repo, + &format!("Screenshots of #{} at {short}", p.number), + &images, + ) + .await?; Ok(shots .into_iter() .map(|(mut s, path)| { - s.src = format!( - "https://github.com/{}/{}/blob/{commit}/{path}?raw=true", - p.owner, p.repo - ); + s.src = image_url(p.owner, p.repo, &commit, &path); s }) .collect()) } +/// Times a write to [`SHOTS_REF`] is tried again on top of a commit another +/// writer put there first. +const REF_TRIES: usize = 3; + +/// Commits `files` (path and bytes) on top of what [`SHOTS_REF`] holds and +/// moves the ref to the new commit without force, so a commit another +/// writer (another pull request's capture, an end-to-end run) added in the +/// meantime is never dropped; then the commit is built again on top of it. +/// The commit's id, which the images are linked by. +pub async fn keep_on_ref( + gh: &GitHubClient, + owner: &str, + repo: &str, + message: &str, + files: &[(String, Vec)], +) -> Result> { + let mut entries: Vec<(String, Option)> = Vec::new(); + for (path, bytes) in files { + let sha = gh.put_blob(owner, repo, bytes).await?; + entries.push(( + path.clone(), + Some(GitEntry { + mode: "100644".into(), + kind: "blob".into(), + sha, + }), + )); + } + let mut last: Box = "nothing was tried".into(); + for _ in 0..REF_TRIES { + let parent = gh.own_ref(owner, repo, SHOTS_REF).await; + let base_tree = match &parent { + Some(c) => gh.commit_tree_parents(owner, repo, c).await?.0, + None => String::new(), + }; + let tree = gh.put_tree(owner, repo, &base_tree, &entries).await?; + let commit = gh + .put_commit( + owner, + repo, + message, + &tree, + &parent.iter().cloned().collect::>(), + ) + .await?; + match gh + .advance_own_ref(owner, repo, SHOTS_REF, parent.as_deref(), &commit) + .await + { + Ok(()) => return Ok(commit), + Err(e) => last = e, + } + } + Err(format!("{SHOTS_REF} kept moving under this write: {last}").into()) +} + +/// The address of `path` on the screenshots ref at `commit`: it shows only +/// to people who can read the repository. +pub fn image_url(owner: &str, repo: &str, commit: &str, path: &str) -> String { + format!("https://github.com/{owner}/{repo}/blob/{commit}/{path}?raw=true") +} + #[cfg(test)] mod tests { use super::*; From 3dd3c549984132ea04ccae9c3314705470078c1c Mon Sep 17 00:00:00 2001 From: Nam Bok Rodriguez Date: Tue, 17 Nov 2026 19:06:57 -0500 Subject: [PATCH 18/32] Pin the dashboard for the November 17 proof release (#770) --- selfhost/versions.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selfhost/versions.json b/selfhost/versions.json index 442a2c824..77f6fd337 100644 --- a/selfhost/versions.json +++ b/selfhost/versions.json @@ -1,4 +1,4 @@ { "about": "The dashboard commit each platform release ships: a full 40-character commit SHA of CoderHelm/coderhelm, never a branch or tag (scripts/check-dashboard-ref.mjs fails CI and the release otherwise). The release workflow builds exactly this commit (dashboard/) into dashboard.tar.gz. Move it with scripts/bump-dashboard.sh in a reviewed PR, in the same PR as any API change the dashboard needs.", - "dashboardRef": "be377a2939527cca60bf15d025d427a5bf70c29d" + "dashboardRef": "f4a5e35923f195648634e5c2fd00a934fa9c8f72" } From a7047cf51ce5136f3f8026c5daaf2314be70c1cc Mon Sep 17 00:00:00 2001 From: Nam Bok Rodriguez Date: Tue, 17 Nov 2026 19:25:32 -0500 Subject: [PATCH 19/32] The changed tests run both ways: CI's install, a budget of their own, every runner read (#769) * A bug is reproduced on the base before it is planned; people's answers decide scope The planner runs the ticket's inputs through the base code (reproduce_on_base) and writes ## Reproduce: inputs with stored variants, the command and its output, the wrong line. The fix goes in that line's mechanism; questions a lookup answers are looked up first; a diff rewriting a path for a few named records goes back; new tests run on the base the way CI runs them, loops included, and an unproven bug fix says Unverified. A person's answer or comment moves an out-of-scope item in at seed and every round, and a revert of it is a breach. * The changed tests run both ways: CI's install, a budget of their own, every runner read Across the 53 most recent runs, none of the 17 with a test check ran a new test on the base and the head. Six failed the install: a pnpm workspace member was installed on its own (`cd apps/web && pnpm install --ignore-workspace --frozen-lockfile`), where pnpm stops with ERR_PNPM_NO_LOCKFILE. Seven ran out of time: the fresh step ran every other check first and reached the sandbox runs short again, with its one request spent. Two could not read a CI loop and listed fixtures as tests. - A workspace member installs from the workspace root (falling back to the member and its dependencies); the runs use CI's job for the test files, its install lines, Node and pnpm versions, through the cached environment. A failed install says why. - The sandbox runs are owed to a fresh step, which runs them before any other check and records them for the head; up to four asks a run. - One `test_env::narrow` for pytest, unittest, Vitest, Jest, go test and cargo test; package scripts and make targets read to their runner; a file's own package script as the narrow fallback; end-to-end specs and test data are not unit tests; one file without a command no longer stops the rest. - Whether the tests ran, and why not, is counted (`tests_ran`) on the run's checks, its notes and the pull request. Incident: tq_tests_run. --- docs/coder-loop.md | 7 +- docs/incidents/tq_tests_run.md | 22 + services/common/src/e2e/test_package.rs | 120 ++- services/common/src/test_env.rs | 496 +++++++++++- services/worker/src/passes/habits_check.rs | 712 +++++++++++++++--- .../src/passes/incidents/aj_coder_habits.rs | 5 +- .../incidents/rp_reproduce_before_planning.rs | 3 + .../src/passes/incidents/tq_tests_run.rs | 286 +++++++ services/worker/src/passes/mod.rs | 5 +- services/worker/src/passes/run_guard.rs | 20 +- services/worker/src/passes/test_bug.rs | 56 +- 11 files changed, 1608 insertions(+), 124 deletions(-) create mode 100644 docs/incidents/tq_tests_run.md create mode 100644 services/worker/src/passes/incidents/tq_tests_run.rs diff --git a/docs/coder-loop.md b/docs/coder-loop.md index c3e26ff32..c5d4c2995 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -130,7 +130,12 @@ The causes were in the loop, not only in prompt wording: Each new or changed test runs in the sandbox with and without the change (`habits_check`). A test the runner finds nothing in goes back to the - coder, and the coder quotes the run's output in its Evidence. End-to-end code + coder, and the coder quotes the run's output in its Evidence. + These runs install through CI's job for the test files. Without one, a + workspace member installs from the workspace root. They have a budget + of their own: a short step owes them to a fresh step, which runs them + before any other check. How many ran, and why the rest didn't, is + counted on the run and in the pull request (`incidents::tq_tests_run`). End-to-end code against another company's page uses only what a probe observed (#734). A proof fix round that answers a gap by looking (a query, a page, a check diff --git a/docs/incidents/tq_tests_run.md b/docs/incidents/tq_tests_run.md new file mode 100644 index 000000000..07aa55d9c --- /dev/null +++ b/docs/incidents/tq_tests_run.md @@ -0,0 +1,22 @@ +# tq. `tq_tests_run` + +**What happened:** Across the 53 most recent runs, 17 had new or changed tests to run with and without the change. Not one of them ran both ways: + +- **6 runs: the install failed in the sandbox.** All six were in one pnpm workspace. The test files sat in a workspace member (`apps/web`) whose lockfile is the workspace root's, and the sandbox installed the member on its own: `cd 'apps/web' && pnpm install --ignore-workspace --frozen-lockfile`. That folder has no lockfile, so pnpm stopped with `ERR_PNPM_NO_LOCKFILE` before any test ran, on every run. The run's CI install (cached per manifest blob) was never used for these runs, and the failure didn't say why. One of the runs also listed a Playwright spec as a unit test. +- **7 runs: no step had the time.** The check asked once for a step of its own. The fresh step ran every other check first (the proof, the link checks, the new-feature rules, the live probes, the scope ledger), so it reached the sandbox runs with less than their 760 seconds left, and its one request was already spent. One run resumed for the runs at 16:00:42 and only reached them at 16:05:42. +- **2 runs: CI's test command wasn't read.** A data pipeline's CI runs a `python "$t"` loop over its tests. Its fixture JSON files were also listed as tests, and one file without a command stopped every file from running. +- **2 runs: no test to run.** One change was only tests; the other changed no test file. + +**The guarantee:** +- **Install the way CI does.** The sandbox runs use CI's job for the changed files: its install lines in order, its Node and pnpm versions, through the cached environment. Without one, a workspace member installs from the workspace root, falling back to the member and what it depends on. A failed install says why, with its error lines. +- **Unit tests only.** An end-to-end spec and test data (fixtures, snapshots) are never run as unit tests. +- **A budget of their own.** When a step is short, the runs are owed to a fresh step. That step runs them first, before any other check, and records the result for the head. A run asks for such a step up to `MAX_PROOF_STEPS` times; only past that are the tests recorded as not run. +- **Read the test command.** Each file runs with CI's test step narrowed to it. One function narrows pytest, unittest, Vitest, Jest, `go test` and `cargo test`, and package scripts and make targets are read through to their runner. When CI's step can't be narrowed, the file's own package's test script runs it. A file with no command doesn't stop the others. +- **Counted.** Whether the tests ran, and why not, is recorded on the run's checks (`tests_ran`), written to its progress notes, and shown in the pull request. + +**Where it's enforced:** +- `common::e2e::test_package::workspace_member` and `install_cmd`; +- `common::test_env` (`narrow`, `resolve_scripts`, `package_test_command`, `INSTALL_FAILED`); +- `habits_check::bench_plan`, `install_failure`, `proof_time` and `run_owed`; +- the ledger's `proof_runs` and `proof_owed`; +- `habits_check::TestsRan`. diff --git a/services/common/src/e2e/test_package.rs b/services/common/src/e2e/test_package.rs index da3ffdb46..20edecc27 100644 --- a/services/common/src/e2e/test_package.rs +++ b/services/common/src/e2e/test_package.rs @@ -224,7 +224,9 @@ pub fn packages_outside( out.push(TestPackage { dir: dir.clone(), manager: lock.map(|(_, m)| *m).unwrap_or(Manager::Npm), - lockfile: lock.map(|(n, _)| n.to_string()), + // From the repository root, as `package_of` names it: a lockfile + // outside the package's folder is a workspace's. + lockfile: lock.map(|(n, _)| join(&dir, n)), has_tsconfig: tree.iter().any(|p| *p == join(&dir, "tsconfig.json")), lint: has_eslint(tree, &dir, &pj), runner: runner_of(&pj), @@ -316,14 +318,65 @@ pub fn ensure_manager(m: Manager) -> &'static str { } } -/// Installs the package's dependencies on their own, never the parent -/// workspace's, after making its manager available. +/// Whether the package is a member of a workspace whose lockfile sits at the +/// workspace's root (`lockfile` names a file outside the package's folder): +/// its dependencies install from that root, the way its CI installs them. +/// A package with its own lockfile, or none, installs on its own. +pub fn workspace_member(p: &TestPackage) -> bool { + let dir = p.dir.trim_end_matches('/'); + p.lockfile + .as_deref() + .is_some_and(|l| !dir.is_empty() && dir != "." && !l.starts_with(&format!("{dir}/"))) +} + +/// The folder the install runs in: the workspace's root for a member +/// ([`workspace_member`]), else the package's own. +pub fn install_dir(p: &TestPackage) -> String { + if workspace_member(p) { + p.lockfile + .as_deref() + .map(|l| parent(l).to_string()) + .filter(|d| !d.is_empty()) + .unwrap_or_else(|| ".".into()) + } else { + p.dir.clone() + } +} + +/// Installs the package's dependencies, after making its manager +/// available: a package on its own never reaches for the parent +/// workspace's; a workspace member installs the workspace from its root +/// lockfile (run in [`install_dir`]). A member's install that fails as a +/// whole falls back to the narrowest one that still runs its tests: the +/// member and what it depends on. +/// +/// Six pull requests' new tests never ran because a member of a pnpm +/// workspace was installed on its own (`cd apps/web && pnpm install +/// --ignore-workspace --frozen-lockfile`): its folder has no lockfile, so +/// pnpm stopped with `ERR_PNPM_NO_LOCKFILE` before any test. pub fn install_cmd(p: &TestPackage) -> String { format!("{}{}", ensure_manager(p.manager), install_only(p)) } fn install_only(p: &TestPackage) -> String { let frozen = p.lockfile.is_some(); + if workspace_member(p) { + let member = format!("./{}", p.dir.trim_start_matches("./")); + return match p.manager { + Manager::Npm => format!( + "(npm ci --no-audit --no-fund || npm ci --no-audit --no-fund --workspace {})", + q(&member).unwrap_or_else(|| "'.'".into()) + ), + Manager::Pnpm => match q(&format!("{member}...")) { + Some(f) => { + format!("(pnpm install --frozen-lockfile || pnpm install --frozen-lockfile --filter {f})") + } + None => "pnpm install --frozen-lockfile".into(), + }, + Manager::Yarn => "yarn install --ignore-engines --frozen-lockfile".into(), + Manager::Bun => "bun install --frozen-lockfile".into(), + }; + } match p.manager { Manager::Npm if frozen => "npm ci --no-audit --no-fund --workspaces=false".into(), Manager::Npm => "npm install --no-audit --no-fund --workspaces=false".into(), @@ -362,7 +415,7 @@ pub fn check_steps(p: &TestPackage) -> Option> { let dir = q(&p.dir)?; let mut steps = vec![Step { kind: "install", - cmd: format!("cd {dir} && {}", install_cmd(p)), + cmd: format!("cd {} && {}", q(&install_dir(p))?, install_cmd(p)), }]; if p.has_tsconfig { steps.push(Step { @@ -697,7 +750,7 @@ mod tests { let mut p = TestPackage { dir: "tests/e2e".into(), manager: Manager::Pnpm, - lockfile: Some("pnpm-lock.yaml".into()), + lockfile: Some("tests/e2e/pnpm-lock.yaml".into()), has_tsconfig: false, lint: false, runner: None, @@ -710,6 +763,7 @@ mod tests { ensure_manager(Manager::Pnpm) ) ); + assert_eq!(install_dir(&p), "tests/e2e"); p.manager = Manager::Yarn; assert!(install_cmd(&p).contains("--frozen-lockfile")); p.manager = Manager::Npm; @@ -722,6 +776,62 @@ mod tests { assert!(check_steps(&p).is_none()); } + /// A pnpm workspace's member (`apps/web`, lockfile at the root): it + /// installs the workspace from the root, never on its own, where pnpm + /// stops with `ERR_PNPM_NO_LOCKFILE`. + #[test] + fn a_workspace_member_installs_from_the_workspace_root() { + let t = tree(&[ + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "apps/web/package.json", + "apps/web/src/test/a.test.ts", + "e2e/package.json", + "e2e/pnpm-lock.yaml", + "e2e/tests/a.spec.ts", + ]); + let web = package_of(&t, "apps/web/src/test/a.test.ts", &|_| None).unwrap(); + assert_eq!(web.dir, "apps/web"); + assert_eq!(web.lockfile.as_deref(), Some("pnpm-lock.yaml")); + assert!(workspace_member(&web)); + assert_eq!(install_dir(&web), "."); + let steps = check_steps(&web).unwrap(); + assert!(steps[0].cmd.starts_with("cd '.' && "), "{}", steps[0].cmd); + assert!( + !steps[0].cmd.contains("--ignore-workspace"), + "{}", + steps[0].cmd + ); + assert!(steps[0].cmd.contains("pnpm install --frozen-lockfile")); + // The narrowest fallback: the member and what it depends on. + assert!(steps[0].cmd.contains("--filter './apps/web...'")); + // Type-check and lint still run in the member's folder. + assert!(steps + .iter() + .skip(1) + .all(|s| s.cmd.starts_with("cd 'apps/web'"))); + // A package with its own lockfile stays on its own. + let e2e = package_of(&t, "e2e/tests/a.spec.ts", &|_| None).unwrap(); + assert!(!workspace_member(&e2e)); + assert_eq!(install_dir(&e2e), "e2e"); + assert!(check_steps(&e2e).unwrap()[0] + .cmd + .contains("pnpm install --ignore-workspace --frozen-lockfile")); + // As `packages_outside` names it, the same. + let out = packages_outside(&t, &["e2e/tests/a.spec.ts".into()], &[], &|_| None); + assert_eq!(out[0].lockfile.as_deref(), Some("e2e/pnpm-lock.yaml")); + assert!(!workspace_member(&out[0])); + // The root package installs where it is. + let root = package_of( + &tree(&["package.json", "pnpm-lock.yaml", "a.test.ts"]), + "a.test.ts", + &|_| None, + ) + .unwrap(); + assert!(!workspace_member(&root)); + } + #[test] fn repeat_commands_use_the_runner_and_the_target() { let mut p = TestPackage { diff --git a/services/common/src/test_env.rs b/services/common/src/test_env.rs index 1271837c5..bbad89fc9 100644 --- a/services/common/src/test_env.rs +++ b/services/common/src/test_env.rs @@ -35,6 +35,9 @@ pub const ENV_ROOT: &str = "/tmp/coderhelm-env"; pub const RESTORED: &str = "===CODERHELM_ENV_RESTORED==="; pub const INSTALLED: &str = "===CODERHELM_ENV_INSTALLED==="; pub const SAVED: &str = "===CODERHELM_ENV_SAVED==="; +/// Printed with the install's exit code when CI's install failed: what +/// follows ran without it, so a test result after it says nothing. +pub const INSTALL_FAILED: &str = "===CODERHELM_ENV_INSTALL_FAILED==="; /// The language whose packages the install fills. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -57,6 +60,8 @@ pub struct TestEnv { pub kind: Kind, pub python: String, pub node: String, + /// The pnpm version CI's `pnpm/action-setup` pins ("" when none). + pub pnpm: String, /// Plain `NAME=value` settings of the job (never an expression). pub env: Vec<(String, String)>, pub install: Vec, @@ -277,6 +282,9 @@ pub fn from_workflows_for( if uses.starts_with("actions/setup-node") { env.node = s(step.get("with").and_then(|w| w.get("node-version"))); } + if uses.starts_with("pnpm/action-setup") { + env.pnpm = s(step.get("with").and_then(|w| w.get("version"))); + } let run = s(step.get("run")); if run.is_empty() || run.contains("${{") { continue; @@ -433,6 +441,307 @@ fn quote(s: &str) -> String { format!("'{}'", s.replace('\'', "'\\''")) } +/// Whether a path is safe to put on a command line as it is. +fn safe_path(p: &str) -> bool { + !p.is_empty() + && !p.starts_with('-') + && p.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '/')) + && !p.contains("..") +} + +/// A test command narrowed to one test file (`file`, relative to the folder +/// the command runs in), or `None` when its runner can't take one. The one +/// place CoderHelm narrows a runner: pytest and `python -m unittest` take +/// the path, Vitest and Jest take it as a filter (they print "no test files +/// found" when it matches nothing, never a pass), `go test` takes the +/// file's package, `cargo test` an integration test's target. A runner's +/// own flags after it are dropped with the rest of the line. +pub fn narrow(cmd: &str, file: &str) -> Option { + if !safe_path(file) { + return None; + } + let words: Vec<&str> = cmd.split_whitespace().collect(); + let low: Vec = words.iter().map(|w| w.to_ascii_lowercase()).collect(); + // Up to and including word `i`, never across a `&&`, `;` or `|`. + let prefix = |i: usize| -> String { + let start = words[..i] + .iter() + .rposition(|w| matches!(*w, "&&" | ";" | "||" | "|")) + .map_or(0, |p| p + 1); + words[start..=i].join(" ") + }; + for (i, w) in low.iter().enumerate() { + let w = w.trim_matches(['"', '\'']); + let base = w.rsplit('/').next().unwrap_or(w); + if base == "pytest" || (base == "unittest" && i > 0 && low[i - 1] == "-m") { + return Some(format!("{} {file}", prefix(i))); + } + if base == "vitest" { + let run = low.get(i + 1).is_some_and(|n| n == "run"); + let end = if run { i + 1 } else { i }; + let run = if run { "" } else { " run" }; + return Some(format!("{}{run} {file}", prefix(end))); + } + if base == "jest" { + return Some(format!("{} {file}", prefix(i))); + } + if w == "go" && low.get(i + 1).is_some_and(|n| n == "test") && file.ends_with("_test.go") { + let dir = file.rsplit_once('/').map_or(".", |(d, _)| d); + let pre = prefix(i + 1); + return Some(format!("{pre} ./{dir}/")); + } + if w == "cargo" && low.get(i + 1).is_some_and(|n| n == "test") { + // An integration test, `tests/.rs`, is a target of its own. + let name = file + .strip_prefix("tests/") + .and_then(|n| n.strip_suffix(".rs")) + .filter(|n| !n.contains('/'))?; + return Some(format!("{} --test {name}", prefix(i + 1))); + } + } + None +} + +/// What a package script or a make target runs, from the manifests: +/// `npm test`, `npm run `, `pnpm [--filter ] [run] `, `yarn +/// [workspace ] `, `bun run `, `make `, run in `dir`. +/// `(folder, command)` with the command the script or target holds, so a +/// runner in it can be narrowed. `read` gives a file's text; `tree` finds a +/// workspace package by name. `None` when it is no script call or the +/// script can't be read. +pub fn resolve_script( + line: &str, + dir: &str, + tree: &[String], + read: &dyn Fn(&str) -> Option, +) -> Option<(String, String)> { + resolve_depth(line, dir, tree, read, 0) +} + +fn package_dir_named( + tree: &[String], + read: &dyn Fn(&str) -> Option, + name: &str, +) -> Option { + let name = name.trim_matches(['"', '\'']); + if name.starts_with("./") || name.contains('/') && !name.starts_with('@') { + return Some( + name.trim_start_matches("./") + .trim_end_matches('/') + .to_string(), + ); + } + tree.iter() + .filter(|p| *p == "package.json" || p.ends_with("/package.json")) + .filter(|p| !p.contains("node_modules/")) + .find(|p| { + read(p) + .and_then(|t| serde_json::from_str::(&t).ok()) + .is_some_and(|v| v["name"].as_str() == Some(name)) + }) + .map(|p| { + p.trim_end_matches("package.json") + .trim_end_matches('/') + .to_string() + }) +} + +fn resolve_depth( + line: &str, + dir: &str, + tree: &[String], + read: &dyn Fn(&str) -> Option, + depth: u8, +) -> Option<(String, String)> { + if depth > 3 { + return None; + } + let words: Vec<&str> = line.split_whitespace().collect(); + let (tool, rest) = words.split_first()?; + let mut at = dir.to_string(); + let mut args: Vec<&str> = Vec::new(); + let mut i = 0; + while i < rest.len() { + let w = rest[i]; + match (*tool, w) { + ("pnpm", "--filter" | "-F") | ("npm", "--workspace" | "-w") => { + at = package_dir_named(tree, read, rest.get(i + 1)?)?; + i += 2; + continue; + } + ("pnpm" | "npm" | "yarn", "-C" | "--dir" | "--prefix" | "--cwd") | ("make", "-C") => { + let d = rest + .get(i + 1)? + .trim_matches(['"', '\'']) + .trim_end_matches('/'); + at = join(&at, d); + i += 2; + continue; + } + ("yarn", "workspace") => { + at = package_dir_named(tree, read, rest.get(i + 1)?)?; + i += 2; + continue; + } + _ if w.starts_with("--filter=") && *tool == "pnpm" => { + at = package_dir_named(tree, read, &w["--filter=".len()..])?; + } + _ if w.starts_with('-') => {} + _ => args.push(w), + } + i += 1; + } + let script = match (*tool, args.as_slice()) { + ("make", [target, ..]) => { + let mk = read(&join(&at, "Makefile"))?; + let recipe = make_recipe(&mk, target)?; + return resolve_depth(&recipe, &at, tree, read, depth + 1).or(Some((at, recipe))); + } + ("make", []) => return None, + ("npm" | "pnpm" | "yarn" | "bun", ["run" | "run-script", s, ..]) => s.to_string(), + ("npm" | "pnpm" | "yarn", ["test" | "t", ..]) => "test".to_string(), + ("pnpm" | "yarn", [s, ..]) + if !matches!(*s, "install" | "add" | "exec" | "dlx" | "i" | "ci" | "x") => + { + s.to_string() + } + _ => return None, + }; + let pj = read(&join(&at, "package.json"))?; + let v: serde_json::Value = serde_json::from_str(&pj).ok()?; + let body = v["scripts"][script.as_str()].as_str()?.trim().to_string(); + if body.is_empty() { + return None; + } + resolve_depth(&body, &at, tree, read, depth + 1).or(Some((at, body))) +} + +/// A script's command run from a shell: a Node runner a package script +/// finds in `node_modules/.bin` (`vitest`, `jest`) goes through `npx`. +fn via_bin(cmd: &str) -> String { + let first = cmd.split_whitespace().next().unwrap_or(""); + if matches!( + first, + "vitest" | "jest" | "mocha" | "ava" | "tsx" | "ts-node" + ) { + format!("npx --no-install {cmd}") + } else { + cmd.to_string() + } +} + +fn in_folder(at: &str, cmd: &str) -> String { + if at.is_empty() || at == "." { + cmd.to_string() + } else { + format!("(cd {at} && {cmd})") + } +} + +/// The first recipe line of `target` in a Makefile that runs a check, its +/// `@`/`-` prefix dropped. +fn make_recipe(makefile: &str, target: &str) -> Option { + let mut lines = makefile.lines(); + while let Some(l) = lines.next() { + let Some((name, _)) = l.split_once(':') else { + continue; + }; + if l.starts_with('\t') || name.split_whitespace().all(|n| n != target) { + continue; + } + for r in lines.by_ref() { + if !r.starts_with('\t') { + if r.trim().is_empty() { + continue; + } + break; + } + let r = r.trim().trim_start_matches(['@', '-']).trim(); + let says = matches!( + r.split_whitespace().next(), + Some("echo" | "printf" | "true") + ); + if !says && crate::ci_cover::is_check_command(r) { + return Some(r.to_string()); + } + } + return None; + } + None +} + +/// The files [`TestEnv::resolve_scripts`] and [`package_test_command`] may +/// read: the manifests and Makefiles of the folders the test steps run in, +/// the workspace's package manifests (a `--filter` names a package), and +/// each test file's nearest manifest. At most 40. +pub fn script_files(env: Option<&TestEnv>, tree: &[String], files: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + let mut add = |p: String| { + if tree.contains(&p) && !out.contains(&p) && out.len() < 40 { + out.push(p); + } + }; + if let Some(e) = env { + let mut dirs = vec![e.dir.clone()]; + dirs.extend(e.test.iter().map(|t| unwrap_cd(t).0)); + for d in dirs { + add(join(&d, "package.json")); + add(join(&d, "Makefile")); + } + } + for f in files { + if let Some(d) = crate::e2e::test_package::package_dir(tree, f) { + add(join(&d, "package.json")); + } + } + for p in tree + .iter() + .filter(|p| p.ends_with("/package.json") && !p.contains("node_modules/")) + { + add(p.clone()); + } + out +} + +/// The test file run by its own package's test script, narrowed to it: the +/// narrowest command that still runs it when CI's test step can't be +/// narrowed (a `turbo` or a root script running every package). `None` +/// when the package has no test script with a runner that takes a file. +pub fn package_test_command( + file: &str, + tree: &[String], + read: &dyn Fn(&str) -> Option, +) -> Option { + let dir = crate::e2e::test_package::package_dir(tree, file)?; + let pj = read(&join(&dir, "package.json"))?; + let v: serde_json::Value = serde_json::from_str(&pj).ok()?; + let rel = if dir.is_empty() { + file + } else { + file.strip_prefix(&format!("{dir}/"))? + }; + for script in ["test:unit", "test:run", "test"] { + let Some(body) = v["scripts"][script].as_str() else { + continue; + }; + let (at, body) = + resolve_depth(body, &dir, tree, read, 1).unwrap_or((dir.clone(), body.to_string())); + let rel = if at == dir { + rel.to_string() + } else { + match file.strip_prefix(&format!("{at}/")) { + Some(r) => r.to_string(), + None => continue, + } + }; + if let Some(c) = narrow(&via_bin(&body), &rel) { + return Some(in_folder(&at, &c)); + } + } + None +} + impl TestEnv { /// Whether this is another package's job for `focus` (the files a run /// changes): its tests run in a folder none of them is in. @@ -449,6 +758,29 @@ impl TestEnv { .any(|f| f.trim_start_matches("./").starts_with(&format!("{dir}/"))) } + /// Each test step that calls a package script or a make target + /// (`pnpm --filter web test`, `npm run test:unit`, `make test`) put as + /// the command the script holds, in its folder, so its runner can be + /// narrowed to one file ([`Self::file_command`]). `read` gives the + /// manifests' text ([`script_files`]). + pub fn resolve_scripts(&mut self, tree: &[String], read: &dyn Fn(&str) -> Option) { + for line in self.test.iter_mut() { + let (dir, cmd) = unwrap_cd(line); + let dir = if dir.is_empty() { + self.dir.clone() + } else { + dir + }; + if let Some((at, body)) = resolve_script(&cmd, &dir, tree, read) { + let at = at + .strip_prefix(&format!("{}/", self.dir)) + .map(str::to_string) + .unwrap_or(if at == self.dir { String::new() } else { at }); + *line = in_folder(&at, &via_bin(&body)); + } + } + } + /// The install's name: its steps, versions and the manifests' blob ids /// (`shas`: `(path, blob sha)` from the tree at the head). pub fn fingerprint(&self, shas: &[(String, String)]) -> String { @@ -456,6 +788,7 @@ impl TestEnv { h.update(self.dir.as_bytes()); h.update(self.python.as_bytes()); h.update(self.node.as_bytes()); + h.update(self.pnpm.as_bytes()); for l in &self.install { h.update(l.as_bytes()); h.update(b"\n"); @@ -509,6 +842,24 @@ impl TestEnv { quote(&self.node) )); } + // The package manager CI sets up with an action (no `run` + // line installs it), at the version it pins, before any + // install line calls it. + let all = format!("{} {}", self.install.join(" "), self.test.join(" ")); + for (tool, pinned) in [("pnpm", &self.pnpm), ("yarn", &String::new())] { + if !all.split_whitespace().any(|w| w == tool) { + continue; + } + let at = if pinned.is_empty() { + String::new() + } else { + format!("@{pinned}") + }; + out.push(format!( + "command -v {tool} >/dev/null 2>&1 || corepack enable {tool} >/dev/null 2>&1 || npm install -g {} >/dev/null 2>&1 || true; hash -r", + quote(&format!("{tool}{at}")) + )); + } } Kind::Other => {} } @@ -547,6 +898,7 @@ fi {activate} {cd}if [ -z "$RESTORED" ] || [ -z "{complete}" ]; then ( {install} ) >/tmp/coderhelm-install.log 2>&1; ICODE=$?; tail -5 /tmp/coderhelm-install.log + if [ $ICODE -ne 0 ]; then echo "{INSTALL_FAILED} $ICODE"; tail -c 1500 /tmp/coderhelm-install.log; fi if [ $ICODE -eq 0 ] && [ -z "$RESTORED" ]; then echo "{INSTALLED}" if [ -n "$ENV_CACHE_PUT_URL" ] && tar czf /tmp/coderhelm-env-out.tgz -C "$E" . && curl -fsS --retry 2 --noproxy "*" -T /tmp/coderhelm-env-out.tgz "$ENV_CACHE_PUT_URL"; then echo "{SAVED}"; fi @@ -584,16 +936,19 @@ bash -c {cmd}"#, let rel = file.strip_prefix(&format!("{}/", dir.trim_end_matches('/')))?; Some(format!("(cd {dir} && {})", cmd.replace(file, rel))) }; - // A runner that takes file paths. + // A runner that takes file paths (`narrow`). + // The wrapper runs the command from the repository root: a job's + // working directory and a step's folder are both cd'd into. + let job = self.dir.trim_end_matches('/'); for (dir, line) in &steps { - let low = line.to_ascii_lowercase(); - for runner in ["pytest", "-m unittest"] { - if let Some(i) = low.find(runner) { - let prefix = line[..i + runner.len()].trim(); - if let Some(c) = in_dir(dir, format!("{prefix} {file}")) { - return Some(c); - } - } + let at = join(job, dir); + let rel = if at.is_empty() { + Some(file) + } else { + file.strip_prefix(&format!("{}/", at.trim_end_matches('/'))) + }; + if let Some(c) = rel.and_then(|r| narrow(line, r)) { + return Some(in_folder(&at, &c)); } } // A loop over test files, its body running each one. @@ -837,6 +1192,129 @@ jobs: assert_eq!(e.file_command("tests/test_a.py"), None); } + #[test] + fn every_runner_is_narrowed_to_one_file_in_one_place() { + assert_eq!( + narrow("python -m pytest tests -q", "tests/test_a.py").as_deref(), + Some("python -m pytest tests/test_a.py") + ); + assert_eq!( + narrow("python -m unittest discover", "tests/test_a.py").as_deref(), + Some("python -m unittest tests/test_a.py") + ); + assert_eq!( + narrow("pnpm exec vitest run --coverage", "src/a.test.ts").as_deref(), + Some("pnpm exec vitest run src/a.test.ts") + ); + assert_eq!( + narrow("npx --no-install vitest", "src/a.test.ts").as_deref(), + Some("npx --no-install vitest run src/a.test.ts") + ); + assert_eq!( + narrow("npx jest --ci", "src/a.test.ts").as_deref(), + Some("npx jest src/a.test.ts") + ); + assert_eq!( + narrow("go test ./... -race", "pkg/cart/total_test.go").as_deref(), + Some("go test ./pkg/cart/") + ); + assert_eq!( + narrow("cargo test --workspace", "tests/cart.rs").as_deref(), + Some("cargo test --test cart") + ); + // Never across a chain, never a file it can't take. + assert_eq!( + narrow("tsc --noEmit && vitest run", "a.test.ts").as_deref(), + Some("vitest run a.test.ts") + ); + assert_eq!(narrow("cargo test", "src/lib.rs"), None); + assert_eq!(narrow("npm run build", "a.test.ts"), None); + assert_eq!(narrow("pytest", "a; rm -rf /"), None); + } + + #[test] + fn package_scripts_and_make_targets_are_read_to_their_runner() { + let tree: Vec = [ + "package.json", + "apps/web/package.json", + "apps/web/src/a.test.ts", + "Makefile", + "tests/test_a.py", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let read = |p: &str| -> Option { + match p { + "package.json" => { + Some(r#"{"name":"root","scripts":{"test":"turbo run test"}}"#.into()) + } + "apps/web/package.json" => Some( + r#"{"name":"web","scripts":{"test":"vitest","test:run":"vitest run"}}"#.into(), + ), + "Makefile" => Some( + "lint:\n\truff .\ntest: deps\n\t@echo testing\n\tpython -m pytest -q tests\n" + .into(), + ), + _ => None, + } + }; + assert_eq!( + resolve_script("pnpm --filter web test", "", &tree, &read), + Some(("apps/web".into(), "vitest".into())) + ); + assert_eq!( + resolve_script("pnpm -F web run test:run", "", &tree, &read), + Some(("apps/web".into(), "vitest run".into())) + ); + assert_eq!( + resolve_script("make test", "", &tree, &read), + Some((String::new(), "python -m pytest -q tests".into())) + ); + assert_eq!(resolve_script("pnpm install", "", &tree, &read), None); + // A CI step that calls a script is narrowed through it. + let mut e = TestEnv { + test: vec!["pnpm --filter web test".into(), "make test".into()], + ..Default::default() + }; + e.resolve_scripts(&tree, &read); + assert_eq!( + e.file_command("apps/web/src/a.test.ts").as_deref(), + Some("(cd apps/web && npx --no-install vitest run src/a.test.ts)") + ); + assert_eq!( + e.file_command("tests/test_a.py").as_deref(), + Some("python -m pytest tests/test_a.py") + ); + // CI runs every package through turbo: the file's own package's + // script runs it. + assert_eq!( + package_test_command("apps/web/src/a.test.ts", &tree, &read).as_deref(), + Some("(cd apps/web && npx --no-install vitest run src/a.test.ts)") + ); + let wanted = script_files(Some(&e), &tree, &["apps/web/src/a.test.ts".into()]); + assert!(wanted.contains(&"apps/web/package.json".to_string())); + assert!(wanted.contains(&"Makefile".to_string())); + } + + #[test] + fn a_failed_install_and_the_pinned_manager_are_in_the_script() { + let e = TestEnv { + kind: Kind::Node, + pnpm: "10.28.2".into(), + install: vec!["pnpm install --frozen-lockfile".into()], + test: vec!["pnpm test".into()], + ..Default::default() + }; + let w = e.wrap("true"); + assert!(w.contains(INSTALL_FAILED)); + assert!(w.contains("npm install -g 'pnpm@10.28.2'")); + assert!(w.find("corepack enable pnpm").unwrap() < w.find("pnpm install --frozen").unwrap()); + let wf = "jobs:\n t:\n steps:\n - uses: pnpm/action-setup@v4\n with:\n version: 10.28.2\n - run: pnpm install --frozen-lockfile\n - run: pnpm --filter web test\n"; + let e = from_workflows(&[("ci.yml".into(), wf.into())], &[]).unwrap(); + assert_eq!(e.pnpm, "10.28.2"); + } + /// The second round restores the first round's install instead of /// installing again. Runs the real script with bash, tar and curl (file /// URLs stand in for the presigned ones). diff --git a/services/worker/src/passes/habits_check.rs b/services/worker/src/passes/habits_check.rs index 8a4789a4d..3be1b3a85 100644 --- a/services/worker/src/passes/habits_check.rs +++ b/services/worker/src/passes/habits_check.rs @@ -19,12 +19,27 @@ //! ledger), goes back to be taken out, unless a `Scope change:` line //! cites an acceptance criterion or a person's comment. //! -//! The sandbox runs take up to its full wait, so the check asks for a step -//! of its own when this one has too little time left -//! ([`GateStop::NeedsTime`]), once; a run that still has none records the -//! tests as not run, with why. Like every check on the open pull request it -//! runs once on a head, keeps its rounds in the run's ledger, and what it -//! leaves goes under Open items. +//! The sandbox runs take up to its full wait. They have a budget of their +//! own, never the leftovers of the coding step: when this step has too +//! little time left the check asks for a step of its own +//! ([`GateStop::NeedsTime`]) and records the runs as owed; the next step +//! runs them first, before any other check ([`run_owed`]), and the check +//! reads their recorded result ([`RecordedRuns`]). A run asks at most +//! [`MAX_PROOF_STEPS`] times; only past that are the tests recorded as not +//! run, with why. Seven runs had recorded "no step of the run had the time" +//! for every changed test: the fresh step ran every other check first and +//! came to these runs short again, and the one request it had was spent. +//! +//! The runs install the way the repository's CI does: in the CI job that +//! runs the files' tests (`common::test_env`, cached per manifest blob), or, +//! when CI installs nothing CoderHelm can read, each test file's package +//! (a workspace member from the workspace's root). Each test file runs with +//! the command CI's test step runs, narrowed to it, else its own package's +//! test script (`common::test_env::narrow`). Why a test didn't run is kept +//! with it ([`NotRunWhy`]) and counted on the run ([`TestsRan`]). +//! +//! Like every check on the open pull request it runs once on a head, keeps +//! its rounds in the run's ledger, and what it leaves goes under Open items. use serde::{Deserialize, Serialize}; use tracing::{info, warn}; @@ -40,6 +55,9 @@ pub const MAX_TEST_FILES: usize = 8; /// What the two sandbox runs need of a step: the sandbox's longest wait and /// room to record the result. pub const SANDBOX_STEP_SECS: u64 = 760; +/// How many steps of its own the sandbox runs may ask for in a run: one per +/// head a fix round leaves, and room for a step that was cut short. +pub const MAX_PROOF_STEPS: u32 = 4; pub const START: &str = ""; pub const END: &str = ""; @@ -69,6 +87,127 @@ pub struct TestResult { /// The failure it printed without the change, or why it didn't run. #[serde(default)] pub detail: String, + /// Why it didn't run, as a kind to count (`None` when it ran). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub why: Option, +} + +/// Why a changed test wasn't run with and without the change. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NotRunWhy { + /// The dependencies' install failed in the sandbox. + InstallFailed, + /// No step had the time for the two sandbox runs. + NoTime, + /// No command CoderHelm can read runs the file on its own. + NoCommand, + /// An end-to-end spec: it runs against a preview, not in the sandbox. + EndToEnd, + /// The runner found no test in the file. + NoTestsFound, + /// More test files than are run on their own. + TooMany, + /// The sandbox gave no result, or something else stopped it. + Other, +} + +/// Why nothing ran: the install failed in the sandbox. +pub const INSTALL_FAILED: &str = "the package's install failed in the sandbox"; +/// Why nothing ran: past [`MAX_PROOF_STEPS`] steps, still no time. +pub const NO_TIME: &str = "no step of the run had the time for the two sandbox runs"; + +impl NotRunWhy { + /// The kind of a not-run detail line. + pub fn of(detail: &str) -> NotRunWhy { + let d = detail.to_ascii_lowercase(); + if d.contains("install") && d.contains("fail") { + NotRunWhy::InstallFailed + } else if d.contains("had the time") { + NotRunWhy::NoTime + } else if d.contains("end-to-end spec") { + NotRunWhy::EndToEnd + } else if d.contains("found no tests") { + NotRunWhy::NoTestsFound + } else if d.contains("only the first") { + NotRunWhy::TooMany + } else if d.contains("no unit test command") + || d.contains("can't be narrowed") + || d.contains("doesn't run `") + { + NotRunWhy::NoCommand + } else { + NotRunWhy::Other + } + } + + pub fn label(self) -> &'static str { + match self { + NotRunWhy::InstallFailed => "install failed", + NotRunWhy::NoTime => "no time", + NotRunWhy::NoCommand => "no test command", + NotRunWhy::EndToEnd => "end-to-end spec", + NotRunWhy::NoTestsFound => "no tests found", + NotRunWhy::TooMany => "past the file limit", + NotRunWhy::Other => "other", + } + } +} + +/// Whether the changed tests ran with and without the change, and why not: +/// the run's record of it (the ledger keeps the check's facts). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestsRan { + /// Changed test files. + pub files: usize, + /// Of them, run both ways. + pub ran: usize, + /// The rest, by why. + #[serde(default)] + pub not_run: Vec<(NotRunWhy, usize)>, +} + +impl TestsRan { + pub fn of(tests: &[TestResult]) -> TestsRan { + let mut not_run: Vec<(NotRunWhy, usize)> = Vec::new(); + for t in tests.iter().filter(|t| t.verdict == Verdict::NotRun) { + let why = t.why.unwrap_or_else(|| NotRunWhy::of(&t.detail)); + match not_run.iter_mut().find(|(w, _)| *w == why) { + Some((_, n)) => *n += 1, + None => not_run.push((why, 1)), + } + } + let n: usize = not_run.iter().map(|(_, n)| n).sum(); + TestsRan { + files: tests.len(), + ran: tests.len() - n, + not_run, + } + } + + /// One line: "Tests run with and without the change: 2 of 3 (not run: + /// 1 install failed)". Empty with no test files. + pub fn line(&self) -> String { + if self.files == 0 { + return String::new(); + } + let why = if self.not_run.is_empty() { + String::new() + } else { + format!( + " (not run: {})", + self.not_run + .iter() + .map(|(w, n)| format!("{n} {}", w.label())) + .collect::>() + .join(", ") + ) + }; + format!( + "Tests run with and without the change: {} of {}{why}", + self.ran, self.files + ) + } } /// A changed file that is no part of the plan. @@ -118,6 +257,9 @@ pub struct PrFacts { /// took it, files only reformatted. #[serde(default)] pub live: super::live_guard::LiveFacts, + /// Whether the changed tests ran both ways, and why not. + #[serde(default)] + pub tests_ran: TestsRan, } /// Why the check didn't give a result. @@ -130,14 +272,15 @@ pub enum GateStop { } /// One test file's run: its exit code and, when it failed, what it printed. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +/// No code: it didn't run, and the output says why when it is known. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct FileRun { pub code: Option, pub output: String, } /// Both runs of the changed test files, in the files' order. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Runs { pub with: Vec, pub without: Vec, @@ -207,6 +350,7 @@ fn excerpt(output: &str) -> String { /// What one file's two runs show. pub fn verdict(with: &FileRun, without: &FileRun) -> (Verdict, String) { match (with.code, without.code) { + (None, _) if !with.output.is_empty() => (Verdict::NotRun, with.output.clone()), (None, _) | (_, None) => ( Verdict::NotRun, "the sandbox gave no result for it".to_string(), @@ -244,9 +388,11 @@ pub fn scoped_cmd(base_cmd: &str, file: &str) -> Option { if low.contains("pytest") { return Some(format!("{base_cmd} {file}")); } - if low.trim_start().starts_with("go test") { - let dir = file.rsplit_once('/').map_or(".", |(d, _)| d); - return Some(format!("go test ./{dir}/")); + // Runners that take a path or a package: one place narrows them. + if !low.contains("vitest") && !low.contains("jest") { + if let Some(c) = common::test_env::narrow(base_cmd, file) { + return Some(c); + } } super::build_scoped_test_cmd(base_cmd, &[file.to_string()]) .map(|c| c.replace(" --passWithNoTests", "")) @@ -327,6 +473,50 @@ pub fn changed_tests(diff: &Diff) -> Vec { .collect() } +/// Test data, not a test: fixtures, snapshots, recorded responses. Two +/// runs listed a fixture's JSON as a test CoderHelm couldn't run. +fn is_test_data(path: &str) -> bool { + let p = path.to_ascii_lowercase(); + let data_dir = [ + "/fixtures/", + "/__fixtures__/", + "/testdata/", + "/test-data/", + "/__snapshots__/", + "/cassettes/", + ] + .iter() + .any(|d| format!("/{p}").contains(d)); + let ext = p.rsplit_once('.').map_or("", |(_, e)| e); + let data_ext = matches!( + ext, + "json" + | "yaml" + | "yml" + | "csv" + | "txt" + | "snap" + | "md" + | "html" + | "xml" + | "sql" + | "png" + | "jpg" + | "svg" + ); + data_dir || data_ext +} + +/// The changed test files a runner can run: not test data. +pub fn bench_files(diff: &Diff) -> Vec { + let mut tests: Vec = changed_tests(diff) + .into_iter() + .filter(|p| !is_test_data(p)) + .collect(); + tests.truncate(MAX_TEST_FILES); + tests +} + fn changes_code(diff: &Diff) -> bool { diff.iter().any(|(p, _, _)| !is_test_path(p)) } @@ -444,9 +634,14 @@ pub async fn check_once( not_updated: not_updated(&changed, plan, own_repo), ..Default::default() }; - let tests = changed_tests(diff); + let all = changed_tests(diff); + let tests: Vec = all.iter().filter(|p| !is_test_data(p)).cloned().collect(); if tests.is_empty() { - facts.no_tests = "the change adds or changes no test file".to_string(); + facts.no_tests = if all.is_empty() { + "the change adds or changes no test file".to_string() + } else { + "the change adds or changes only test data, no test file to run".to_string() + }; return facts; } if !changes_code(diff) { @@ -462,10 +657,12 @@ pub async fn check_once( runs.with.get(i).unwrap_or(&none), runs.without.get(i).unwrap_or(&none), ); + let why = (verdict == Verdict::NotRun).then(|| NotRunWhy::of(&detail)); facts.tests.push(TestResult { path: path.clone(), verdict, detail, + why, }); } } @@ -475,6 +672,7 @@ pub async fn check_once( path: path.clone(), verdict: Verdict::NotRun, detail: why.clone(), + why: Some(NotRunWhy::of(&why)), }); } } @@ -484,8 +682,10 @@ pub async fn check_once( path: path.clone(), verdict: Verdict::NotRun, detail: format!("only the first {MAX_TEST_FILES} test files are run on their own"), + why: Some(NotRunWhy::TooMany), }); } + facts.tests_ran = TestsRan::of(&facts.tests); facts } @@ -739,6 +939,11 @@ pub fn section(plan: &PlanResult, f: &PrFacts) -> String { out.push_str(&test_line(t)); out.push('\n'); } + // How many ran both ways, and why the rest didn't, counted. + let ran = TestsRan::of(&f.tests); + if ran.ran < ran.files { + out.push_str(&format!("{}.\n", ran.line())); + } // A bug fix no test was shown to fail on the base for says so, in // so many words: it is unverified, never quietly proven by CI. if f.bug && !f.tests.iter().any(|t| t.verdict == Verdict::Proven) { @@ -954,42 +1159,178 @@ pub struct SandboxBench<'a> { const KIND: &str = "unit"; +/// The end-to-end spec's line: it runs against a preview, never in the +/// unit sandbox (CI and the end-to-end proof run it there). +pub const E2E_SPEC: &str = "an end-to-end spec: it runs against a preview, not in the unit sandbox"; + +/// Whether `file` is an end-to-end spec: its package's runner drives a +/// browser, or it sits in the repository's end-to-end suite. +fn is_e2e_spec(tree: &[String], file: &str, texts: &dyn Fn(&str) -> Option) -> bool { + use test_package::Runner as R; + let runner = test_package::package_of(tree, file, texts).and_then(|p| p.runner); + matches!(runner, Some(R::Playwright | R::Cypress | R::Wdio)) + || common::preview::e2e_suite(tree) + .is_some_and(|s| file.starts_with(&format!("{}/", s.dir.trim_end_matches('/')))) +} + +/// How the sandbox runs the files: the installs (none when CI's test job +/// installs, through its environment), one command per file that has one, +/// and why the others don't run. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct BenchPlan { + pub install: Vec, + /// Per file, in order: its command, or why it doesn't run. + pub per_file: Vec>, +} + +/// The sandbox plan for `files`, from the CI test command CoderHelm reads +/// (`ci_cmd`), CI's test environment for these files (`env`, its package +/// scripts already resolved) and the tree's manifests (`texts`). A file +/// with no command is recorded as not run with why; the others still run. +pub fn bench_plan( + files: &[String], + tree: &[String], + ci_cmd: Option<&str>, + env: Option<&common::test_env::TestEnv>, + texts: &dyn Fn(&str) -> Option, +) -> BenchPlan { + let mut plan = BenchPlan::default(); + // CI's own install, in its order, at its versions, in its environment + // (cached per manifest blob); else each file's package's. + let ci_installs = env.is_some_and(|e| !e.install.is_empty()); + let mut installed: Vec = Vec::new(); + for f in files { + if is_e2e_spec(tree, f, texts) { + plan.per_file.push(Err(E2E_SPEC.to_string())); + continue; + } + let cmd = file_cmd(ci_cmd, env, f) + .or_else(|why| common::test_env::package_test_command(f, tree, texts).ok_or(why)); + if cmd.is_ok() && !ci_installs { + let steps = test_package::package_of(tree, f, texts) + .and_then(|p| test_package::check_steps(&p)) + .unwrap_or_default(); + for s in steps.into_iter().filter(|s| s.kind == "install") { + if !installed.contains(&s.cmd) { + installed.push(s.cmd.clone()); + plan.install.push(s); + } + } + } + plan.per_file.push(cmd); + } + plan +} + +/// The runs of the planned commands, per file: a file with no command did +/// not run, and says why. +fn spread(plan: &BenchPlan, runs: Vec) -> Vec { + let mut runs = runs.into_iter(); + plan.per_file + .iter() + .map(|c| match c { + Ok(_) => runs.next().unwrap_or_default(), + Err(why) => FileRun { + code: None, + output: why.clone(), + }, + }) + .collect() +} + +/// Why the install failed, from a sandbox script's output: CI's install in +/// the test environment, or an install step; the error's last lines. +pub fn install_failure(output: &str, codes: &[Option], installs: usize) -> Option { + let tail = |t: &str| -> String { + let lines: Vec<&str> = t.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + let pick: Vec<&str> = lines + .iter() + .filter(|l| { + let low = l.to_ascii_lowercase(); + low.contains("err") || low.contains("error") || low.contains("not found") + }) + .copied() + .collect(); + let pick = if pick.is_empty() { + lines[lines.len().saturating_sub(2)..].to_vec() + } else { + pick[pick.len().saturating_sub(2)..].to_vec() + }; + common::truncate_str(&pick.join(" "), 300).replace('`', "'") + }; + if let Some(at) = output.find(common::test_env::INSTALL_FAILED) { + let rest = &output[at + common::test_env::INSTALL_FAILED.len()..]; + let body = rest.split(test_package::STEP_MARK).next().unwrap_or(rest); + return Some(format!("{INSTALL_FAILED} (CI's install: {})", tail(body))); + } + if codes.iter().take(installs).any(|c| *c != Some(0)) { + let out = failing_outputs(output, "install").join("\n"); + return Some(if out.is_empty() { + INSTALL_FAILED.to_string() + } else { + format!("{INSTALL_FAILED} ({})", tail(&out)) + }); + } + None +} + #[async_trait::async_trait] impl Bench for SandboxBench<'_> { async fn run(&self, files: &[String]) -> Result { let r = &self.runner; let ci_cmd = super::detect_ci_test(r.github, r.owner, r.repo, self.base_branch).await; - let mut steps: Vec = Vec::new(); - let tree: Vec = r + let tree_full = r .github .get_tree(r.owner, r.repo, self.branch) .await - .map_err(|e| e.to_string())? - .into_iter() - .map(|e| e.path) + .map_err(|e| e.to_string())?; + let tree: Vec = tree_full.iter().map(|e| e.path.clone()).collect(); + // CI's job for these files: its install wraps every command, and + // its test steps (package scripts read through) run each file. + let env = super::test_setup::for_run( + r.state, + r.github, + r.team_id, + r.owner, + r.repo, + self.base_branch, + self.branch, + r.run_id, + files, + ) + .await; + let mut texts: std::collections::HashMap = Default::default(); + for p in common::test_env::script_files(env.as_ref().map(|(e, _)| e), &tree, files) { + if let Ok(t) = r.github.read_file(r.owner, r.repo, &p, self.branch).await { + texts.insert(p, t); + } + } + let read = |p: &str| texts.get(p).cloned(); + let resolved = env.as_ref().map(|(e, _)| { + let mut e = e.clone(); + e.resolve_scripts(&tree, &read); + e + }); + let plan = bench_plan(files, &tree, ci_cmd.as_deref(), resolved.as_ref(), &read); + let commands: Vec<&String> = plan + .per_file + .iter() + .filter_map(|c| c.as_ref().ok()) .collect(); - // A test step CoderHelm's runner list doesn't know (a loop running - // each file with `python`) still runs the file the way CI does. - let narrowed = |f: &String| ci_cmd.as_deref().and_then(|c| scoped_cmd(c, f)); - let env = if files.iter().all(|f| narrowed(f).is_some()) { - None - } else { - let workflows = - super::preview::workflows(r.github, r.owner, r.repo, self.base_branch).await; - common::test_env::from_workflows_for(&workflows, &tree, files) - }; - let install: Vec = files - .first() - .and_then(|f| test_package::package_of(&tree, f, &|_| None)) - .and_then(|p| test_package::check_steps(&p)) - .map(|s| s.into_iter().filter(|s| s.kind == "install").collect()) - .unwrap_or_default(); - let installs = install.len(); - steps.extend(install); - for f in files { - let cmd = file_cmd(ci_cmd.as_deref(), env.as_ref(), f)?; - steps.push(Step { kind: KIND, cmd }); + if commands.is_empty() { + // Nothing to run: each file says why. + let none = spread(&plan, Vec::new()); + return Ok(Runs { + with: none.clone(), + without: none, + }); } + let installs = plan.install.len(); + let mut steps: Vec = plan.install.clone(); + steps.extend(commands.iter().map(|c| Step { + kind: KIND, + cmd: (*c).clone(), + })); let head = r .github .get_ref(r.owner, r.repo, self.branch) @@ -1035,8 +1376,8 @@ impl Bench for SandboxBench<'_> { .map_err(|e| e.to_string())?; // Side by side: each waits on its own sandbox build. let (with, without) = tokio::join!( - r.run_at(&head, &steps, None), - r.run_at(&before_sha, &steps, None) + r.run_at_in(&head, &steps, env.clone()), + r.run_at_in(&before_sha, &steps, env.clone()) ); Ok::<_, String>((with?, without?)) } @@ -1045,17 +1386,22 @@ impl Bench for SandboxBench<'_> { warn!(error = %e, branch = %temp, "Could not delete the branch of the test check"); } let ((with_codes, with_out), (without_codes, without_out)) = both?; + for (codes, out) in [(&with_codes, &with_out), (&without_codes, &without_out)] { + if let Some(why) = install_failure(out, codes, installs) { + warn!(run_id = r.run_id, why = %why, "The changed tests' install failed in the sandbox"); + return Err(why); + } + } let per_file = |codes: &[Option], out: &str| { - let failed_installs = codes.iter().take(installs).any(|c| *c != Some(0)); - let runs = file_runs(&codes[installs.min(codes.len())..], out, KIND); - (failed_installs, runs) + spread( + &plan, + file_runs(&codes[installs.min(codes.len())..], out, KIND), + ) }; - let (with_broken, with) = per_file(&with_codes, &with_out); - let (without_broken, without) = per_file(&without_codes, &without_out); - if with_broken || without_broken { - return Err("the package's install failed in the sandbox".to_string()); - } - Ok(Runs { with, without }) + Ok(Runs { + with: per_file(&with_codes, &with_out), + without: per_file(&without_codes, &without_out), + }) } } @@ -1162,17 +1508,190 @@ async fn wider( .collect() } -/// A bench for a step with no time for the sandbox: nothing runs, and each -/// test says so. +/// A bench for a run whose steps never had the time for the sandbox, past +/// [`MAX_PROOF_STEPS`] asks: nothing runs, and each test says so. struct NoTime; #[async_trait::async_trait] impl Bench for NoTime { async fn run(&self, _files: &[String]) -> Result { - Err("no step of the run had the time for the two sandbox runs; the repository's CI runs the tests on this pull request".to_string()) + Err(format!("{NO_TIME} in {MAX_PROOF_STEPS} steps of their own; the repository's CI runs the tests on this pull request")) + } +} + +/// The two sandbox runs of a head's changed test files, kept on the run's +/// ledger: a step that runs them first ([`run_owed`]) leaves them for the +/// check, which reads them instead of running them again. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RecordedRuns { + pub head: String, + pub files: Vec, + pub result: Result, +} + +impl RecordedRuns { + /// Whether these are the runs of `files` on `head`. + pub fn of(&self, head: &str, files: &[String]) -> bool { + !head.is_empty() && self.head == head && self.files == files + } +} + +/// A bench that answers with recorded runs. +struct Recorded(Result); + +#[async_trait::async_trait] +impl Bench for Recorded { + async fn run(&self, _files: &[String]) -> Result { + self.0.clone() } } +/// A bench that keeps what another one gave, for the ledger. +struct Recording<'b> { + inner: &'b dyn Bench, + got: std::sync::Mutex>>, +} + +#[async_trait::async_trait] +impl Bench for Recording<'_> { + async fn run(&self, files: &[String]) -> Result { + let r = self.inner.run(files).await; + *self.got.lock().unwrap() = Some(r.clone()); + r + } +} + +/// What the step does about the sandbox runs for a head. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProofTime { + /// They ran for this head and files: read them. + Recorded(Result), + /// This step has their time: run them now. + Run, + /// Owed to a fresh step, which runs them first. + Owe, + /// No step had the time, past the asks a run has. + NoTime, +} + +/// What a step does about the changed tests' sandbox runs: read the +/// recorded ones, run them, owe them to a fresh step (at most +/// [`MAX_PROOF_STEPS`] times a run, never on a path that has no step to +/// give), or, only past that, record them as not run. +pub fn proof_time( + recorded: Option<&RecordedRuns>, + head: &str, + files: &[String], + secs_left: u64, + steps_asked: u32, + can_hand_off: bool, +) -> ProofTime { + if let Some(r) = recorded.filter(|r| r.of(head, files)) { + return ProofTime::Recorded(r.result.clone()); + } + if secs_left >= SANDBOX_STEP_SECS { + return ProofTime::Run; + } + if can_hand_off && steps_asked < MAX_PROOF_STEPS { + return ProofTime::Owe; + } + ProofTime::NoTime +} + +/// The diff the check reads: the run's work files, with their status. +async fn work_diff(w: &super::proof::Work<'_>) -> Result, String> { + let diff = w + .github + .compare_files_with_patches( + &w.msg.repo_owner, + &w.msg.repo_name, + &w.msg.base_branch, + w.branch, + ) + .await + .map_err(|e| format!("the diff couldn't be read ({e})"))?; + let paths: Vec = diff.iter().map(|(p, _, _)| p.clone()).collect(); + let work = super::run_end::work_files(&paths, &w.msg.ticket_id); + Ok(diff + .into_iter() + .filter(|(p, _, _)| work.contains(p)) + .collect()) +} + +fn sandbox_bench<'a>(w: &'a super::proof::Work<'a>) -> SandboxBench<'a> { + SandboxBench { + runner: super::test_bug::Runner { + state: w.state, + github: w.github, + owner: &w.msg.repo_owner, + repo: &w.msg.repo_name, + team_id: &w.msg.team_id, + run_id: w.run_id, + provider: w.provider, + }, + base_branch: &w.msg.base_branch, + branch: w.branch, + } +} + +/// The sandbox runs a step owed this one, run first, before any other +/// check, with the step's whole budget; their result is recorded for the +/// check ([`RecordedRuns`]). Nothing when none are owed, or the head moved +/// since (the check asks again for the new one). +pub async fn run_owed(w: &super::proof::Work<'_>, secs_left: impl Fn() -> u64) { + let owed = w.ledger.update(|l| l.proof_owed.clone()); + if owed.is_empty() { + return; + } + let head = w.head().await; + if head != owed || secs_left() < SANDBOX_STEP_SECS { + if head != owed { + w.ledger.update(|l| l.proof_owed.clear()); + w.save_ledger().await; + } + return; + } + let files = match work_diff(w).await { + Ok(d) if changes_code(&d) => bench_files(&d), + Ok(_) => Vec::new(), + Err(e) => { + warn!(run_id = w.run_id, error = %e, "The owed sandbox runs couldn't read the diff; the check runs them"); + return; + } + }; + if files.is_empty() { + w.ledger.update(|l| l.proof_owed.clear()); + w.save_ledger().await; + return; + } + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Running the {} changed test file(s) with and without the change first in this step, with its whole time", + files.len() + ), + ) + .await; + let result = sandbox_bench(w).run(&files).await; + info!( + run_id = w.run_id, + ok = result.is_ok(), + files = files.len(), + "The owed sandbox runs ran first in the step" + ); + w.ledger.update(|l| { + l.proof_owed.clear(); + l.proof_runs = Some(RecordedRuns { + head: head.clone(), + files: files.clone(), + result: result.clone(), + }); + }); + w.save_ledger().await; +} + async fn check_and_fix( w: &super::proof::Work<'_>, evidence: &mut super::proof::RunEvidence, @@ -1185,46 +1704,44 @@ async fn check_and_fix( return Ok(None); } loop { - let diff = w - .github - .compare_files_with_patches( - &w.msg.repo_owner, - &w.msg.repo_name, - &w.msg.base_branch, - w.branch, - ) - .await - .map_err(|e| GateStop::Why(format!("the diff couldn't be read ({e})")))?; + let diff = work_diff(w).await.map_err(GateStop::Why)?; let paths: Vec = diff.iter().map(|(p, _, _)| p.clone()).collect(); - let work = super::run_end::work_files(&paths, &w.msg.ticket_id); - let diff: Vec<(String, String, String)> = diff - .into_iter() - .filter(|(p, _, _)| work.contains(p)) - .collect(); - let needs_sandbox = !changed_tests(&diff).is_empty() && changes_code(&diff); - let short = needs_sandbox && secs_left() < SANDBOX_STEP_SECS; - if short - && !w + let files = bench_files(&diff); + let needs_sandbox = !files.is_empty() && changes_code(&diff); + let head = w.head().await; + // The proof runs have a budget of their own: read the recorded + // runs, run them now, or owe them to a fresh step that runs them + // first; only past the asks are they recorded as not run. + let time = if needs_sandbox { + let (recorded, asked, can) = w .ledger - .update(|l| std::mem::replace(&mut l.habits_waited, true)) - { + .update(|l| (l.proof_runs.clone(), l.proof_steps, !l.no_proof_step)); + proof_time(recorded.as_ref(), &head, &files, secs_left(), asked, can) + } else { + ProofTime::Run + }; + if time == ProofTime::Owe { + w.ledger.update(|l| { + l.proof_steps += 1; + l.proof_owed = head.clone(); + }); w.save_ledger().await; return Err(GateStop::NeedsTime); } - let sandbox = SandboxBench { - runner: super::test_bug::Runner { - state: w.state, - github: w.github, - owner: &w.msg.repo_owner, - repo: &w.msg.repo_name, - team_id: &w.msg.team_id, - run_id: w.run_id, - provider: w.provider, - }, - base_branch: &w.msg.base_branch, - branch: w.branch, + let sandbox = sandbox_bench(w); + let recording = Recording { + inner: &sandbox, + got: Default::default(), + }; + let recorded; + let bench: &dyn Bench = match &time { + ProofTime::Recorded(r) => { + recorded = Recorded(r.clone()); + &recorded + } + ProofTime::NoTime => &NoTime, + _ => &recording, }; - let bench: &dyn Bench = if short { &NoTime } else { &sandbox }; let mut facts = check_once( bench, &diff, @@ -1234,6 +1751,19 @@ async fn check_and_fix( &evidence.notes, ) .await; + if let Some(result) = recording.got.lock().unwrap().take() { + w.ledger.update(|l| { + l.proof_runs = Some(RecordedRuns { + head: head.clone(), + files: files.clone(), + result, + }) + }); + } + if !facts.tests_ran.line().is_empty() { + super::add_progress_note(w.state, &w.msg.team_id, w.run_id, &facts.tests_ran.line()) + .await; + } facts.e2e_missing = e2e_missing(w, &paths).await; facts.wider = wider(w, &diff, &evidence.notes).await; // Fixture ids invented while the run looked up the real ones. @@ -1243,7 +1773,13 @@ async fn check_and_fix( .extend(super::minimal_change::made_up_ids(&diff, &looked)); // A page whose state a test branch reads is probed again while // there is time: an arm that couldn't run before is re-checked. - facts.live = super::live_guard::facts_for(w, &diff, &evidence.notes, !short).await; + facts.live = super::live_guard::facts_for( + w, + &diff, + &evidence.notes, + secs_left() >= SANDBOX_STEP_SECS, + ) + .await; let comments = super::scope_ledger::comments(w.github, w.msg, w.branch).await; let people = super::scope_ledger::people(w.msg, &comments); let mut ledger = super::scope_ledger::load_or_seed( diff --git a/services/worker/src/passes/incidents/aj_coder_habits.rs b/services/worker/src/passes/incidents/aj_coder_habits.rs index 8c64b77b0..086de5355 100644 --- a/services/worker/src/passes/incidents/aj_coder_habits.rs +++ b/services/worker/src/passes/incidents/aj_coder_habits.rs @@ -282,8 +282,9 @@ fn the_pipeline_still_does_each_of_these_at_its_place() { let pr_src = include_str!("../pr.rs"); let with_checks = fn_src(pr_src, "fn with_checks("); assert!(with_checks.contains("super::habits_check::shape_body(")); - // It asks for a step once, and the sandbox wait fits a step. + // It owes the runs to a fresh step, which runs them first (see + // `tq_tests_run`), and the sandbox wait fits a step. let check_src = include_str!("../habits_check.rs"); - assert!(check_src.contains("std::mem::replace(&mut l.habits_waited, true)")); + assert!(check_src.contains("l.proof_owed = head.clone();")); const { assert!(habits_check::SANDBOX_STEP_SECS < 900) }; } diff --git a/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs b/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs index 22decfeaf..11d331f87 100644 --- a/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs +++ b/services/worker/src/passes/incidents/rp_reproduce_before_planning.rs @@ -233,6 +233,7 @@ fn the_new_test_runs_on_the_base_the_way_ci_runs_it() { path: "tests/test_camp_sport.py".into(), verdict: habits_check::verdict(&head, &head).0, detail: String::new(), + why: None, }], ..Default::default() }; @@ -246,6 +247,7 @@ fn the_new_test_runs_on_the_base_the_way_ci_runs_it() { path: "tests/test_camp_sport.py".into(), verdict: Verdict::NotRun, detail: "the sandbox gave no result for it".into(), + why: None, }], ..Default::default() }; @@ -256,6 +258,7 @@ fn the_new_test_runs_on_the_base_the_way_ci_runs_it() { path: "tests/test_camp_sport.py".into(), verdict: Verdict::Proven, detail: "AssertionError".into(), + why: None, }], ..Default::default() }; diff --git a/services/worker/src/passes/incidents/tq_tests_run.rs b/services/worker/src/passes/incidents/tq_tests_run.rs new file mode 100644 index 000000000..1f21d8ff4 --- /dev/null +++ b/services/worker/src/passes/incidents/tq_tests_run.rs @@ -0,0 +1,286 @@ +//! tq. Across the 53 most recent runs, 17 had new or changed tests to run +//! with and without the change, and not one ran both ways: +//! +//! - 6 recorded "the package's install failed in the sandbox", all in one +//! pnpm workspace. The test files sat in a member (`apps/web`) whose +//! lockfile is the workspace root's, and the sandbox installed the member +//! on its own: `cd 'apps/web' && pnpm install --ignore-workspace +//! --frozen-lockfile`. With no lockfile in that folder pnpm stops with +//! `ERR_PNPM_NO_LOCKFILE` before any test, on every run. The run's own CI +//! install (`pnpm install --frozen-lockfile` at the root, cached per +//! manifest blob) was never used for these runs, and the failure said +//! nothing of why. One of them also listed a Playwright spec as a unit +//! test. +//! - 7 recorded "no step of the run had the time for the two sandbox +//! runs". The check asked once for a step of its own; the fresh step ran +//! every other check first (the proof, the link checks, the new-feature +//! rules, live probes, the scope ledger) and came to the runs with less +//! than their 760 seconds left, and the one request was spent: one run +//! resumed for the runs at 16:00:42 and reached them at 16:05:42. +//! - 2 recorded "the repository's CI runs no unit test command CoderHelm +//! can read" for a data pipeline whose CI loops `python "$t"` over its +//! tests, and listed fixture JSON files as tests too; one file without a +//! command stopped every file from running. +//! - 2 had no test to run (a change of only tests, or no test file). +//! +//! Guarantee: the runs install the way CI does (its job for the files, its +//! install lines in order, its Node and pnpm versions, through the cached +//! environment); without one a workspace member installs from the +//! workspace root, falling back to the member and what it depends on. A +//! failed install says why (its error lines). An end-to-end spec and test +//! data are never run as unit tests. The runs have a budget of their own: +//! owed to a fresh step, which runs them first, before any other check, +//! and records them for the head; a run asks up to `MAX_PROOF_STEPS` +//! times. Each file runs with CI's test step narrowed to it (one +//! `common::test_env::narrow` for pytest, unittest, Vitest, Jest, go test, +//! cargo test; package scripts and make targets read through), else its +//! own package's test script; a file with none doesn't stop the others. +//! Whether the tests ran, and why not, is counted on the run and in the +//! pull request. + +use crate::passes::habits_check::{ + self, bench_files, bench_plan, install_failure, proof_time, FileRun, NotRunWhy, ProofTime, + RecordedRuns, Runs, TestResult, TestsRan, Verdict, +}; +use common::e2e::test_package::{self, STEP_MARK}; +use common::test_env::{self, TestEnv}; + +fn tree(paths: &[&str]) -> Vec { + paths.iter().map(|p| p.to_string()).collect() +} + +/// A web workspace like the six runs': `apps/web` a member, the lockfile at +/// the root, an end-to-end package with its own lockfile. +fn workspace() -> Vec { + tree(&[ + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "apps/web/package.json", + "apps/web/src/components/drawer.tsx", + "apps/web/src/test/components/drawer-reopen.test.tsx", + "e2e/package.json", + "e2e/pnpm-lock.yaml", + "e2e/tests/browse/registration.spec.ts", + ]) +} + +fn manifests(p: &str) -> Option { + match p { + "package.json" => Some(r#"{"name":"acme","packageManager":"pnpm@10.28.2"}"#.into()), + "apps/web/package.json" => Some( + r#"{"name":"web","scripts":{"test":"vitest","test:run":"vitest run"},"devDependencies":{"vitest":"3.0.0"}}"# + .into(), + ), + "e2e/package.json" => Some(r#"{"devDependencies":{"@playwright/test":"1.48.0"}}"#.into()), + _ => None, + } +} + +#[test] +fn a_workspace_member_installs_from_the_root_and_says_why_when_it_fails() { + let t = workspace(); + let test = "apps/web/src/test/components/drawer-reopen.test.tsx".to_string(); + // What the six runs ran: the member on its own, where pnpm finds no + // lockfile. + let web = test_package::package_of(&t, &test, &manifests).unwrap(); + let install = &test_package::check_steps(&web).unwrap()[0].cmd; + assert!(!install.contains("cd 'apps/web' &&"), "{install}"); + assert!(!install.contains("--ignore-workspace"), "{install}"); + assert!(install.starts_with("cd '.' && "), "{install}"); + // With CI's install for these files read, CI's install runs (in the + // cached environment) and nothing else. + let ci = TestEnv { + kind: test_env::Kind::Node, + install: vec!["pnpm install --frozen-lockfile".into()], + test: vec!["pnpm --filter web run test:run".into()], + ..Default::default() + }; + let mut resolved = ci.clone(); + resolved.resolve_scripts(&t, &manifests); + let plan = bench_plan( + std::slice::from_ref(&test), + &t, + None, + Some(&resolved), + &manifests, + ); + assert!(plan.install.is_empty()); + assert_eq!( + plan.per_file, + vec![Ok( + "(cd apps/web && npx --no-install vitest run src/test/components/drawer-reopen.test.tsx)" + .to_string() + )] + ); + // Without CI's, the member's package installs from the root, once. + let plan = bench_plan(&[test.clone(), test.clone()], &t, None, None, &manifests); + assert_eq!(plan.install.len(), 1); + assert!(plan.install[0] + .cmd + .contains("pnpm install --frozen-lockfile")); + // The Playwright spec one run listed is never a unit test. + let spec = "e2e/tests/browse/registration.spec.ts".to_string(); + let plan = bench_plan(&[spec], &t, None, None, &manifests); + assert!(matches!(&plan.per_file[0], Err(w) if w == habits_check::E2E_SPEC)); + assert_eq!(NotRunWhy::of(habits_check::E2E_SPEC), NotRunWhy::EndToEnd); + // A failed install says why, from its own lines. + let out = format!( + "--- install failed (exit 1) ---\n ERR_PNPM_NO_LOCKFILE Cannot install with \"frozen-lockfile\" because pnpm-lock.yaml is absent\n{STEP_MARK} 1 1\n{STEP_MARK} 2 1\n" + ); + let why = install_failure(&out, &[Some(1), Some(1)], 1).unwrap(); + assert!(why.starts_with(habits_check::INSTALL_FAILED), "{why}"); + assert!(why.contains("ERR_PNPM_NO_LOCKFILE"), "{why}"); + let ci_out = format!( + "{} 1\nERR_PNPM_FETCH_401 GET https://npm.pkg.example/@acme%2fui: Unauthorized\n{STEP_MARK} 1 1\n", + test_env::INSTALL_FAILED + ); + let why = install_failure(&ci_out, &[Some(1)], 0).unwrap(); + assert!( + why.contains("CI's install") && why.contains("ERR_PNPM_FETCH_401"), + "{why}" + ); + assert_eq!(NotRunWhy::of(&why), NotRunWhy::InstallFailed); + assert_eq!(install_failure("ok", &[Some(0), Some(0)], 1), None); + // CI's wrapper prints that marker when its install fails. + assert!(ci.wrap("true").contains(test_env::INSTALL_FAILED)); +} + +#[test] +fn the_runs_have_a_step_of_their_own_and_run_first_in_it() { + let files = vec!["apps/web/src/test/a.test.ts".to_string()]; + // The coding step ends with 300 seconds left: the runs are owed. + assert_eq!(proof_time(None, "h1", &files, 300, 0, true), ProofTime::Owe); + // What the seven runs did next: the fresh step reached them after its + // other checks, short again, with its one request spent. Now the owed + // runs go first, with the step's whole time, and are recorded. + assert_eq!(proof_time(None, "h1", &files, 880, 1, true), ProofTime::Run); + let done = RecordedRuns { + head: "h1".into(), + files: files.clone(), + result: Ok(Runs { + with: vec![FileRun { + code: Some(0), + output: String::new(), + }], + without: vec![FileRun { + code: Some(1), + output: "AssertionError: expected 'pagehide'".into(), + }], + }), + }; + // The check, however late in the step, reads them. + assert!(matches!( + proof_time(Some(&done), "h1", &files, 40, 1, true), + ProofTime::Recorded(Ok(_)) + )); + // A fix round's new head needs its own runs: owed again, up to the cap. + assert_eq!( + proof_time(Some(&done), "h2", &files, 40, 1, true), + ProofTime::Owe + ); + assert_eq!( + proof_time( + Some(&done), + "h2", + &files, + 40, + habits_check::MAX_PROOF_STEPS, + true + ), + ProofTime::NoTime + ); + // A path with no step to give records them as not run. + assert_eq!( + proof_time(None, "h1", &files, 40, 0, false), + ProofTime::NoTime + ); + // The step runs what it owes before every other check. + let src = include_str!("../mod.rs"); + let owed = src + .find("habits_check::run_owed(&work, || remaining_secs(start)).await;") + .expect("the owed runs run in the step"); + let first_check = src + .find("hand_off_unless_time_for!(\n proof,") + .expect("the proof check"); + assert!(owed < first_check); + let check = include_str!("../habits_check.rs"); + assert!(check.contains("l.proof_owed = head.clone();")); + assert!(!check.contains("std::mem::replace(&mut l.habits_waited, true)")); +} + +#[test] +fn a_loop_ci_runs_the_test_and_its_fixtures_are_not_tests() { + // The data pipeline's CI: a loop runs each test file with `python`. + let ci = TestEnv { + kind: test_env::Kind::Python, + install: vec!["uv pip install -r requirement.txt".into()], + test: vec![ + "for t in tests/test_*.py; do".into(), + "python \"$t\" || failed=1".into(), + "done".into(), + ], + ..Default::default() + }; + let diff: Vec<(String, String, String)> = [ + "dags/utils/schedule_common.py", + "tests/fixtures/camp_activities.json", + "tests/fixtures/camp_live_names.json", + "tests/test_camp_sport.py", + ] + .iter() + .map(|p| (p.to_string(), "modified".to_string(), String::new())) + .collect(); + let files = bench_files(&diff); + assert_eq!(files, vec!["tests/test_camp_sport.py"]); + let t = tree(&["tests/test_camp_sport.py", "requirement.txt"]); + let plan = bench_plan(&files, &t, None, Some(&ci), &|_| None); + assert_eq!( + plan.per_file, + vec![Ok("python tests/test_camp_sport.py".to_string())] + ); + // A file no command runs is not run, with why; the others still run. + let plan = bench_plan( + &["tests/test_camp_sport.py".into(), "scripts/check.sh".into()], + &t, + None, + Some(&ci), + &|_| None, + ); + assert!(plan.per_file[0].is_ok()); + assert!(plan.per_file[1].is_err()); + // `make test` and package scripts are read to their runner. + let read = + |p: &str| (p == "Makefile").then(|| "test:\n\tpython -m pytest -q tests\n".to_string()); + let mut make = TestEnv { + test: vec!["make test".into()], + ..Default::default() + }; + make.resolve_scripts(&tree(&["Makefile"]), &read); + assert_eq!( + make.file_command("tests/test_camp_sport.py").as_deref(), + Some("python -m pytest tests/test_camp_sport.py") + ); +} + +#[test] +fn whether_the_tests_ran_is_counted_with_why() { + let t = |path: &str, verdict: Verdict, detail: &str| TestResult { + path: path.into(), + verdict, + detail: detail.into(), + why: None, + }; + let tests = vec![ + t("a.test.ts", Verdict::Proven, "expected 1"), + t("b.test.ts", Verdict::NotRun, habits_check::INSTALL_FAILED), + t("c.spec.ts", Verdict::NotRun, habits_check::E2E_SPEC), + ]; + let ran = TestsRan::of(&tests); + assert_eq!((ran.files, ran.ran), (3, 1)); + assert_eq!( + ran.line(), + "Tests run with and without the change: 1 of 3 (not run: 1 install failed, 1 end-to-end spec)" + ); + assert_eq!(TestsRan::of(&[]).line(), ""); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 4bbdd6432..d09b4c4c7 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -7097,6 +7097,9 @@ async fn run_passes( } }; } + // Sandbox runs a step owed this one run first, with its whole budget, + // never after the other checks spent it. + habits_check::run_owed(&work, || remaining_secs(start)).await; hand_off_unless_time_for!( proof, "The proof check needs more time than this step has left" @@ -8563,7 +8566,7 @@ async fn run_repo_pipeline( }; // This path has no step of its own to give: with too little time the // tests are recorded as not run, with why. - ledger.update(|l| l.habits_waited = true); + ledger.update(|l| l.no_proof_step = true); let habits_pr = match habits_check::gate( &work, &mut evidence, diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index e799e87d2..9105e8780 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -1036,10 +1036,26 @@ pub struct Ledger { /// What the tests and scope check last came to. #[serde(default)] pub habits_outcome: Option, String>>, - /// That check has asked once for a step of its own for its sandbox - /// runs: it never asks twice. + /// Read by nothing now: it made the sandbox runs ask for a step of + /// their own once a run, and a fresh step that came to them short again + /// recorded every changed test as not run. Older checkpoints carry it. #[serde(default)] pub habits_waited: bool, + /// The changed tests' two sandbox runs for a head and its files, run + /// first in a step of their own or by the check (`habits_check`). + #[serde(default)] + pub proof_runs: Option, + /// The head whose sandbox runs are owed to the next step, which runs + /// them before any other check (`habits_check::run_owed`). + #[serde(default)] + pub proof_owed: String, + /// How many steps of their own the sandbox runs have asked for. + #[serde(default)] + pub proof_steps: u32, + /// This path has no step of its own to give the sandbox runs (a run + /// across repositories): short of time, they are recorded as not run. + #[serde(default)] + pub no_proof_step: bool, /// What the proof check last found (`None`: the judge couldn't answer). #[serde(default)] pub proof_findings: Option>, diff --git a/services/worker/src/passes/test_bug.rs b/services/worker/src/passes/test_bug.rs index 05bae27f1..02b81b726 100644 --- a/services/worker/src/passes/test_bug.rs +++ b/services/worker/src/passes/test_bug.rs @@ -57,6 +57,20 @@ impl Runner<'_> { Ok((test_package::step_codes(&output, n), output)) } + /// [`Self::run_at`] in a given test environment (`None`: none), not the + /// run's default one: the CI job that runs these steps' files. + pub async fn run_at_in( + &self, + sha: &str, + steps: &[Step], + env: Option<(common::test_env::TestEnv, String)>, + ) -> Result<(Vec>, String), String> { + let cmds: Vec<&str> = steps.iter().map(|s| s.cmd.as_str()).collect(); + let script = test_package::sandbox_script(steps, None); + let output = self.run_script_in(sha, &cmds, &script, env).await?; + Ok((test_package::step_codes(&output, steps.len()), output)) + } + /// Runs `script` on commit `sha` in the sandbox, in the run's test /// environment, once each of `cmds` (the commands it runs) passes the /// team's agent permissions: the output. `Err` says why nothing ran. @@ -65,6 +79,31 @@ impl Runner<'_> { sha: &str, cmds: &[&str], script: &str, + ) -> Result { + // A failing test's run has no planned files: the job that runs on + // every change from the root comes first. + let env = super::test_setup::for_run( + self.state, + self.github, + self.team_id, + self.owner, + self.repo, + sha, + sha, + self.run_id, + &[], + ) + .await; + self.run_script_in(sha, cmds, script, env).await + } + + /// [`Self::run_script_at`] in the test environment `env`. + pub async fn run_script_in( + &self, + sha: &str, + cmds: &[&str], + script: &str, + env: Option<(common::test_env::TestEnv, String)>, ) -> Result { if !self.sandbox_on() { return Err("no sandbox is set up here".into()); @@ -98,22 +137,7 @@ impl Runner<'_> { ) .with_egress(crate::agent::policy::sandbox_egress(self.state, self.team_id).await) // The proof step runs in the run's test environment too. - .with_test_env( - super::test_setup::for_run( - self.state, - self.github, - self.team_id, - self.owner, - self.repo, - sha, - sha, - self.run_id, - // A failing test's run has no planned files: the job that - // runs on every change from the root comes first. - &[], - ) - .await, - ); + .with_test_env(env); let source = sandbox .ensure_source(self.run_id, sha, || { self.github.download_tarball(self.owner, self.repo, sha) From 715d56207e191d1152385e34d740e6d92fd387bf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:25:46 -0500 Subject: [PATCH 20/32] ci: bump the actions group across 1 directory with 8 updates (#313) Bumps the actions group with 8 updates in the / directory: | Package | From | To | | --- | --- | --- | | [actions/checkout](https://github.com/actions/checkout) | `4.4.0` | `7.0.1` | | [actions/upload-artifact](https://github.com/actions/upload-artifact) | `4.6.2` | `7.0.2` | | [sigstore/cosign-installer](https://github.com/sigstore/cosign-installer) | `3.10.1` | `4.1.3` | | [actions/attest-build-provenance](https://github.com/actions/attest-build-provenance) | `2.4.0` | `4.2.2` | | [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials) | `4.3.1` | `6.3.0` | | [actions/download-artifact](https://github.com/actions/download-artifact) | `4.3.0` | `8.0.2` | | [actions/setup-python](https://github.com/actions/setup-python) | `5.6.0` | `7.1.0` | | [actions/setup-node](https://github.com/actions/setup-node) | `4.4.0` | `7.1.0` | Updates `actions/checkout` from 4.4.0 to 7.0.1 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/11d5960a326750d5838078e36cf38b85af677262...3d3c42e5aac5ba805825da76410c181273ba90b1) Updates `actions/upload-artifact` from 4.6.2 to 7.0.2 - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/ea165f8d65b6e75b540449e92b4886f43607fa02...cf430e030ddbb5b0abf93d22962f4752f3646cd9) Updates `sigstore/cosign-installer` from 3.10.1 to 4.1.3 - [Release notes](https://github.com/sigstore/cosign-installer/releases) - [Commits](https://github.com/sigstore/cosign-installer/compare/7e8b541eb2e61bf99390e1afd4be13a184e9ebc5...756fe2d284c7292c4e9b62c8a28f1e5629c59532) Updates `actions/attest-build-provenance` from 2.4.0 to 4.2.2 - [Release notes](https://github.com/actions/attest-build-provenance/releases) - [Changelog](https://github.com/actions/attest-build-provenance/blob/main/RELEASE.md) - [Commits](https://github.com/actions/attest-build-provenance/compare/e8998f949152b193b063cb0ec769d69d929409be...4d101475d8b20a2381f78447822ac1eab6504dd8) Updates `aws-actions/configure-aws-credentials` from 4.3.1 to 6.3.0 - [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases) - [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md) - [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/7474bc4690e29a8392af63c5b98e7449536d5c3a...e1253824e5c10ff9df46874f81ed3ec929e19cfd) Updates `actions/download-artifact` from 4.3.0 to 8.0.2 - [Release notes](https://github.com/actions/download-artifact/releases) - [Commits](https://github.com/actions/download-artifact/compare/d3f86a106a0bac45b974a628896c90dbdf5c8093...9000827ccba6bdab643e8b6fd33ac0654aef8333) Updates `actions/setup-python` from 5.6.0 to 7.1.0 - [Release notes](https://github.com/actions/setup-python/releases) - [Commits](https://github.com/actions/setup-python/compare/a26af69be951a213d495a4c3e4e4022e16d87065...6d4fd22b20465ccc0f7354476588e8df7c9ca0e0) Updates `actions/setup-node` from 4.4.0 to 7.1.0 - [Release notes](https://github.com/actions/setup-node/releases) - [Commits](https://github.com/actions/setup-node/compare/49933ea5288caeca8642d1e84afbd3f7d6820020...949feb2413d6458794dcd2491c4babbbce0c15c1) --- updated-dependencies: - dependency-name: actions/attest-build-provenance dependency-version: 4.2.2 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/checkout dependency-version: 7.0.1 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/download-artifact dependency-version: 8.0.2 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/setup-node dependency-version: 7.1.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/setup-python dependency-version: 7.1.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/upload-artifact dependency-version: 7.0.2 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: aws-actions/configure-aws-credentials dependency-version: 6.3.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: sigstore/cosign-installer dependency-version: 4.1.2 dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/auto-release.yml | 20 +++++++------- .github/workflows/ci.yml | 36 +++++++++++++------------- .github/workflows/deploy.yml | 12 ++++----- .github/workflows/jira-app-release.yml | 8 +++--- .github/workflows/release.yml | 24 ++++++++--------- .github/workflows/reviewer-evals.yml | 6 ++--- 6 files changed, 53 insertions(+), 53 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 4c2f39131..bf5249045 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -168,7 +168,7 @@ jobs: fi echo "::error::No successful CDK deploy of $COMMIT on main" exit 1 - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} fetch-depth: 0 @@ -191,7 +191,7 @@ jobs: [ -n "$COMMIT" ] && args+=(--commit "$COMMIT") [ "$MODE" = promote ] && [ -n "$VERSION" ] && args+=(--version "$VERSION") python3 .github/scripts/auto_release.py plan "${args[@]}" - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: steps.plan.outputs.count != '0' with: name: release-notes @@ -268,7 +268,7 @@ jobs: if exists "$TAG"; then echo "::error::$TAG exists already; a release tag is never re-cut or moved"; exit 1; fi printf 'coderhelm-release-tag v1\nrepository %s\ntag %s\ncommit %s\n' "$GITHUB_REPOSITORY" "$TAG" "$COMMIT" > "$RUNNER_TEMP/$TAG.release-tag" cat "$RUNNER_TEMP"/*.release-tag - - uses: sigstore/cosign-installer@7e8b541eb2e61bf99390e1afd4be13a184e9ebc5 # v3.10.1 + - uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3 with: cosign-release: v2.4.1 - name: Sign the statements @@ -293,7 +293,7 @@ jobs: } verify "$RUNNER_TEMP/tag.sigstore.json" "$RUNNER_TEMP/$TAG.release-tag" if [ "$KIND" = beta ]; then verify "$RUNNER_TEMP/stable.sigstore.json" "$RUNNER_TEMP/$STABLE_TAG.release-tag"; fi - - uses: actions/attest-build-provenance@e8998f949152b193b063cb0ec769d69d929409be # v2.4.0 + - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 if: matrix.kind != 'promote' with: subject-path: ${{ runner.temp }}/*.release-tag @@ -328,7 +328,7 @@ jobs: echo "Created $TAG ($obj) on $COMMIT" # The tag, fetched back from GitHub, checks out as installs check it # (main's installer code). - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} persist-credentials: false @@ -395,7 +395,7 @@ jobs: done [ "$conclusion" = success ] || { echo "::error::the Release run on $TAG ended: $conclusion"; exit 1; } - - uses: sigstore/cosign-installer@7e8b541eb2e61bf99390e1afd4be13a184e9ebc5 # v3.10.1 + - uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3 with: cosign-release: v2.4.1 # The published release, downloaded from GitHub, checks out as an @@ -422,7 +422,7 @@ jobs: # Only the publish script, at this workflow's own commit: the job runs # nothing from the repository but that file. - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} persist-credentials: false @@ -430,7 +430,7 @@ jobs: sparse-checkout-cone-mode: false # Same roles and same writes as release.yml's maintainer path: templates # are created once and never replaced, the pointers only move forward. - - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 with: role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/coderhelm-prod-release-publisher role-duration-seconds: 900 @@ -464,7 +464,7 @@ jobs: bash .github/scripts/publish-once.sh "$L" curl --proto =https -fsSL "https://$PUBLIC_BUCKET.s3.amazonaws.com/launch/$TAG/coderhelm.json" | cmp -s - "$d/coderhelm.json" \ || { echo "::error::the template in S3 is not the signed coderhelm.json"; exit 1; } - - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 with: role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/coderhelm-prod-release-latest role-duration-seconds: 900 @@ -522,7 +522,7 @@ jobs: echo "$key: $url" done - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-notes path: ${{ runner.temp }}/notes diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 858f3341f..1b96e56dc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,10 +22,10 @@ jobs: name: Workflow security runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - name: Pinned actions and safe triggers @@ -55,7 +55,7 @@ jobs: run: working-directory: services steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false # The merge commit and its first parent (the base it merged onto). @@ -110,7 +110,7 @@ jobs: run: working-directory: services steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false # The merge commit and its first parent (the base it merged onto). @@ -200,8 +200,8 @@ jobs: name: Lambda (Python) runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - run: python3 -m unittest discover -s lambda/tests @@ -216,8 +216,8 @@ jobs: run: working-directory: lambda/mcp-proxy steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: lts/* - run: npm ci @@ -230,14 +230,14 @@ jobs: run: working-directory: coderhelm-jira steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: lts/* # Pure rules only (no Forge runtime); `forge lint` needs a login and # runs in the release workflow (jira-app-release.yml). - run: npm test - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" # The release workflow's permission check (scopes, egress, web triggers). @@ -254,8 +254,8 @@ jobs: run: working-directory: infra steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: lts/* cache: npm @@ -284,8 +284,8 @@ jobs: run: working-directory: installer steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: lts/* - run: npm test @@ -295,13 +295,13 @@ jobs: name: Native release (templates, checker, lint) runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: lts/* # The read-only checker and the release's model list. - run: node --test selfhost/launch/*.test.mjs - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" # One release's parent and part templates from stub code, then cfn-lint diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index fb5511d47..eddd05822 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -81,7 +81,7 @@ jobs: contents: read actions: read # an earlier deploy's build steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - id: inputs @@ -128,7 +128,7 @@ jobs: --arg gw "$(sha256sum rust-build/gateway.zip | cut -d' ' -f1)" --arg wk "$(sha256sum rust-build/worker.zip | cut -d' ' -f1)" \ '{inputs: $inputs, commit: $commit, built_at: $built_at, build_run: $build_run, files: {"gateway.zip": $gw, "worker.zip": $wk}}' > rust-build/rust-build.json cat rust-build/rust-build.json - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: rust-build path: rust-build/ @@ -143,15 +143,15 @@ jobs: id-token: write contents: read steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: lts/* cache: npm cache-dependency-path: | infra/package-lock.json - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: rust-build path: artifacts/ @@ -162,7 +162,7 @@ jobs: echo "$(jq -r --arg f "$f" '.files[$f]' rust-build.json) $f" done | sha256sum -c - - - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 with: role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }} aws-region: ${{ env.AWS_REGION }} diff --git a/.github/workflows/jira-app-release.yml b/.github/workflows/jira-app-release.yml index 80300be51..8ad09eae4 100644 --- a/.github/workflows/jira-app-release.yml +++ b/.github/workflows/jira-app-release.yml @@ -69,12 +69,12 @@ jobs: exit 1 fi - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.ref || github.sha }} fetch-depth: 0 # the permission check reads the last released manifest - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm @@ -82,7 +82,7 @@ jobs: coderhelm-jira/package-lock.json coderhelm-jira/resources/admin/package-lock.json - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" @@ -195,7 +195,7 @@ jobs: cat "$RUNNER_TEMP/versions.err" || true echo "::warning::Could not read the released version from Forge; launch/jira-app.json is left as it is." fi - - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 if: steps.version.outputs.version != '' id: aws continue-on-error: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ddab46d9..98812e391 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -82,7 +82,7 @@ jobs: [ "$REF_TYPE" = tag ] || { echo "::error::Run this on a tag (vX.Y.Z), not a branch"; exit 1; } [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || { echo "::error::$TAG is not vX.Y.Z"; exit 1; } echo "tag=$TAG" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.ref }} fetch-depth: 0 @@ -103,7 +103,7 @@ jobs: # a maintainer's SSH signature (with a key pinned in main's copy of # selfhost/maintainers.json, not the tag's) when the tag has one, or # else the release attestation auto-release.yml on main put in it. - - uses: sigstore/cosign-installer@7e8b541eb2e61bf99390e1afd4be13a184e9ebc5 # v3.10.1 + - uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3 with: cosign-release: v2.4.1 - id: path @@ -188,7 +188,7 @@ jobs: env: TAG: ${{ needs.check.outputs.tag }} steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.ref }} fetch-depth: 0 @@ -241,7 +241,7 @@ jobs: fi sha256sum dist/gateway.zip dist/worker.zip - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: lts/* @@ -258,7 +258,7 @@ jobs: run: | node scripts/check-dashboard-ref.mjs echo "ref=$(node -p 'require("./selfhost/versions.json").dashboardRef')" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: CoderHelm/coderhelm ref: ${{ steps.dash.outputs.ref }} @@ -352,7 +352,7 @@ jobs: (cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh coderhelm.json coderhelm-native.tar.gz models.json coderhelm-log-reader.yaml coderhelm-log-reader-update.yaml coderhelm-bedrock-export.yaml > SHA256SUMS) cat dist/SHA256SUMS - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: release-dist path: dist/ @@ -379,7 +379,7 @@ jobs: TAG: ${{ needs.check.outputs.tag }} PUBLIC_BUCKET: coderhelm-public steps: - - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-dist path: dist @@ -392,7 +392,7 @@ jobs: # Keyless signature of the checksums: installs and updates check it was # made by exactly this workflow on this tag, and logged in Rekor. The # cosign version matches the one the update build verifies with. - - uses: sigstore/cosign-installer@7e8b541eb2e61bf99390e1afd4be13a184e9ebc5 # v3.10.1 + - uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3 with: cosign-release: v2.4.1 - name: Sign the checksums @@ -407,7 +407,7 @@ jobs: --certificate-github-workflow-sha "$GITHUB_SHA" \ dist/SHA256SUMS - - uses: actions/attest-build-provenance@e8998f949152b193b063cb0ec769d69d929409be # v2.4.0 + - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 with: subject-path: | dist/gateway.zip @@ -468,14 +468,14 @@ jobs: # A maintainer's tag only: auto-release.yml publishes these for its own. # Only the publish script, at this workflow's own commit: the job runs # nothing from the repository but that file. - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: needs.check.outputs.path == 'maintainer' with: ref: ${{ github.sha }} persist-credentials: false sparse-checkout: .github/scripts/publish-once.sh sparse-checkout-cone-mode: false - - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 if: needs.check.outputs.path == 'maintainer' with: role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/coderhelm-prod-release-publisher @@ -528,7 +528,7 @@ jobs: (cd "$d" && sha256sum -c SHA256SUMS) curl --proto =https -fsSL "https://$PUBLIC_BUCKET.s3.amazonaws.com/launch/$TAG/coderhelm.json" | cmp -s - "$d/coderhelm.json" \ || { echo "::error::the template in S3 is not the signed coderhelm.json"; exit 1; } - - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 if: ${{ needs.check.outputs.path == 'maintainer' && !contains(needs.check.outputs.tag, '-') }} with: role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/coderhelm-prod-release-latest diff --git a/.github/workflows/reviewer-evals.yml b/.github/workflows/reviewer-evals.yml index 99a3b4823..75b8f6cad 100644 --- a/.github/workflows/reviewer-evals.yml +++ b/.github/workflows/reviewer-evals.yml @@ -80,12 +80,12 @@ jobs: run: working-directory: services steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: services - - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 with: role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/coderhelm-prod-reviewer-evals role-session-name: reviewer-evals-${{ github.run_id }} @@ -114,7 +114,7 @@ jobs: - name: Measurement summary if: always() && inputs.suite != '' && inputs.suite != 'nightly' run: grep -h '^ROUTE_EVAL' eval.log > route-eval.jsonl || true - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: always() && inputs.suite != '' && inputs.suite != 'nightly' with: name: route-eval-${{ github.run_id }} From 6e4010b60b658fcb82218bf91dd7aeebf211253a Mon Sep 17 00:00:00 2001 From: Axel Esquite Date: Tue, 17 Nov 2026 19:43:16 -0500 Subject: [PATCH 21/32] fix(gateway): release a merged plan task's own dependents via its ticket's plan link (#719) * A merged plan task releases its own dependents, found through its ticket's plan link After a pull request merged, the tasks waiting on its plan task were found by issue number alone: the first task row in any of the team's plans with the run's issue number. A Jira ticket's run records issue number 0, so a merged Jira task never released its own dependents and could release those of a task with no issue yet, in any plan. GitHub issue numbers repeat across repositories, so a merge in one repository could release the dependents of a task in another. The merged run's task is now found through its ticket's plan link, the settings row the plan wrote when it opened the ticket (repository and issue number, or Jira key), and issue number 0 never names a ticket. A merge whose ticket has no plan link releases nothing. * Without a plan link, a merged task is found by the ticket its task row records The link from a ticket to its plan task is written best effort, and plans from before links existed have none. A merge on such a task released nothing, so its waiting tasks stayed waiting. Without a link, the merged run's task is now the task row that records the same ticket: the repository and issue number from the issue's URL, or the Jira key. Never issue number 0 and never a number alone. The search stays in the run's plan when the run names one, otherwise covers the team's plans, and a ticket that more than one task names releases nothing. The link is still looked up first. --------- Co-authored-by: Shoyu --- services/common/src/lib.rs | 2 + services/common/src/plan_dependents.rs | 710 ++++++++++++++++++ services/gateway/src/routes/github_webhook.rs | 158 +--- services/worker/src/passes/plan_execute.rs | 4 +- 4 files changed, 743 insertions(+), 131 deletions(-) create mode 100644 services/common/src/plan_dependents.rs diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 90426853a..7c773dc64 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -185,6 +185,8 @@ pub mod own_pr; pub mod paged; /// Placeholder tokens: never learned, never written into a commit or title. pub mod placeholders; +/// Which waiting plan tasks a merged run releases. +pub mod plan_dependents; /// Every body CoderHelm sends GitHub fits GitHub's limit. pub mod pr_body; pub mod pr_body_fit; diff --git a/services/common/src/plan_dependents.rs b/services/common/src/plan_dependents.rs new file mode 100644 index 000000000..2fc977280 --- /dev/null +++ b/services/common/src/plan_dependents.rs @@ -0,0 +1,710 @@ +//! Which waiting plan tasks a merged run releases. +//! +//! A plan's task can wait on another task. When the run of the task it waits +//! on merges its pull request, the waiting task starts. The merged run's +//! task is found through its ticket's plan link ([`link_sk`]), the +//! settings-table row written when the plan opened the ticket, which names +//! the plan and the task. +//! +//! The task was once found by issue number alone. A Jira ticket's run has +//! no issue number (it is recorded as 0), so a merged Jira task never +//! released its own dependents and could release those of the first task +//! with no issue number, in any plan. GitHub issue numbers repeat across +//! repositories, so a merge in one repository could release the dependents +//! of a task in another. +//! +//! The link is written best effort, and plans from before it existed have +//! none. Without a link the task is found by the ticket each task row +//! records ([`task_has_ticket`]): the issue's URL (repository and number) +//! or the Jira key, never a number alone. It is looked for in the run's plan +//! when the run names one, otherwise in all the team's plans, and a ticket +//! that more than one task names releases nothing. + +use aws_sdk_dynamodb::types::AttributeValue; +use std::collections::HashMap; +use std::sync::Mutex; + +/// Settings-table sort key prefix of the link from a ticket to its plan task. +pub const LINK_SK_PREFIX: &str = "PLAN_TICKET#"; +/// Status of a task that waits on another task's merge. +pub const WAITING: &str = "waiting"; + +/// Settings-table sort key of the link from a GitHub issue to its plan task. +pub fn github_link_sk(repo: &str, issue_number: u64) -> String { + format!( + "{LINK_SK_PREFIX}github#{}#{issue_number}", + repo.to_lowercase() + ) +} + +/// Settings-table sort key of the link from a Jira ticket to its plan task. +pub fn jira_link_sk(key: &str) -> String { + format!("{LINK_SK_PREFIX}jira#{}", key.to_uppercase()) +} + +/// The ticket a merged run worked, as its run record holds it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MergedRun { + /// `github`, `jira` or `alert`. + pub source: String, + /// The Jira key, or `GH-` for a GitHub issue. + pub ticket_id: String, + /// `owner/name` the run worked in (a GitHub issue's repository). + pub repo: String, + /// The GitHub issue number; 0 for a ticket that is not a GitHub issue. + pub issue_number: u64, + /// The plan the run's record names ("" for none). + pub plan_id: String, +} + +impl MergedRun { + /// The ticket fields of a run record. + pub fn from_item(item: &HashMap) -> Self { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + MergedRun { + source: s("ticket_source"), + ticket_id: s("ticket_id"), + repo: s("repo"), + issue_number: item + .get("issue_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0), + plan_id: s("plan_id"), + } + } +} + +/// Settings-table sort key of the plan link of the run's ticket, the same +/// key the plan wrote when it opened the ticket. None when the run's ticket +/// cannot have one: issue number 0 names no GitHub issue. +pub fn link_sk(run: &MergedRun) -> Option { + match run.source.as_str() { + "jira" => { + let key = run.ticket_id.trim(); + (!key.is_empty() && key != "UNKNOWN").then(|| jira_link_sk(key)) + } + "github" => (run.issue_number > 0 && !run.repo.trim().is_empty()) + .then(|| github_link_sk(run.repo.trim(), run.issue_number)), + _ => None, + } +} + +/// A task of a plan, as far as releasing it goes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Task { + pub plan_id: String, + pub task_id: String, + pub status: String, + /// The task this one waits on ("" for none). + pub depends_on: String, + /// The GitHub issue the task opened (`https://///issues/`). + pub issue_url: String, + /// The Jira ticket the task opened. + pub jira_ticket_key: String, +} + +/// `(owner/repo lowercased, number)` of a GitHub issue URL. +fn issue_of_url(url: &str) -> Option<(String, u64)> { + let path = url.trim().split_once("://")?.1; + let parts: Vec<&str> = path.trim_end_matches('/').split('/').collect(); + match parts.as_slice() { + [_host, owner, repo, "issues", n] if !owner.is_empty() && !repo.is_empty() => { + let n: u64 = n.parse().ok()?; + (n > 0).then(|| (format!("{owner}/{repo}").to_lowercase(), n)) + } + _ => None, + } +} + +/// Whether the task row records the run's ticket: the same repository and +/// issue number (from the issue's URL), or the same Jira key. Issue number +/// 0, a missing repository or a number alone never match. +pub fn task_has_ticket(task: &Task, run: &MergedRun) -> bool { + match run.source.as_str() { + "jira" => { + let key = run.ticket_id.trim(); + !key.is_empty() + && key != "UNKNOWN" + && task.jira_ticket_key.trim().eq_ignore_ascii_case(key) + } + "github" => { + let repo = run.repo.trim().to_lowercase(); + run.issue_number > 0 + && !repo.is_empty() + && issue_of_url(&task.issue_url) == Some((repo, run.issue_number)) + } + _ => false, + } +} + +/// The waiting tasks a merge releases. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Release { + pub plan_id: String, + /// The merged run's task. + pub task_id: String, + /// The tasks that waited on it. + pub tasks: Vec, +} + +/// Where plan links and plan tasks are read. +#[async_trait::async_trait] +pub trait PlanStore: Send + Sync { + /// `(plan_id, task_id)` the link at `link_sk` names, if it exists. + async fn linked_task( + &self, + team: &str, + link_sk: &str, + ) -> Result, String>; + /// Every task of a plan. + async fn plan_tasks(&self, team: &str, plan_id: &str) -> Result, String>; + /// Every task of every plan of the team. + async fn team_tasks(&self, team: &str) -> Result, String>; +} + +/// The waiting tasks a merged run releases: those that wait on the run's +/// task. The task is the one its ticket's plan link names; without a link, +/// the one task row that records the ticket (see the module docs). None +/// when no task is found for the ticket or no task waits on it. +pub async fn dependents_to_release( + store: &dyn PlanStore, + team: &str, + run: &MergedRun, +) -> Result, String> { + let Some(sk) = link_sk(run) else { + return Ok(None); + }; + let linked = store + .linked_task(team, &sk) + .await? + .filter(|(p, t)| !p.is_empty() && !t.is_empty()); + let (plan_id, task_id) = match linked { + Some(found) => found, + None => { + let scope = if run.plan_id.trim().is_empty() { + store.team_tasks(team).await? + } else { + store.plan_tasks(team, run.plan_id.trim()).await? + }; + let mut named = scope.into_iter().filter(|t| task_has_ticket(t, run)); + match (named.next(), named.next()) { + (Some(t), None) if !t.plan_id.is_empty() && !t.task_id.is_empty() => { + (t.plan_id, t.task_id) + } + _ => return Ok(None), + } + } + }; + let tasks: Vec = store + .plan_tasks(team, &plan_id) + .await? + .into_iter() + .filter(|t| t.status == WAITING && t.depends_on == task_id) + .map(|t| t.task_id) + .collect(); + Ok((!tasks.is_empty()).then_some(Release { + plan_id, + task_id, + tasks, + })) +} + +/// The settings table (plan links) and the plans table (tasks). +pub struct DynamoPlans { + pub dynamo: aws_sdk_dynamodb::Client, + pub settings_table: String, + pub plans_table: String, +} + +#[async_trait::async_trait] +impl PlanStore for DynamoPlans { + async fn linked_task( + &self, + team: &str, + link_sk: &str, + ) -> Result, String> { + let item = self + .dynamo + .get_item() + .table_name(&self.settings_table) + .key("pk", AttributeValue::S(team.to_string())) + .key("sk", AttributeValue::S(link_sk.to_string())) + .projection_expression("plan_id, task_id") + .send() + .await + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string())? + .item; + Ok(item.map(|i| (s_of(&i, "plan_id"), s_of(&i, "task_id")))) + } + + async fn plan_tasks(&self, team: &str, plan_id: &str) -> Result, String> { + self.tasks_under(team, &format!("PLAN#{plan_id}#TASK#")) + .await + } + + async fn team_tasks(&self, team: &str) -> Result, String> { + self.tasks_under(team, "PLAN#").await + } +} + +impl DynamoPlans { + /// The task rows whose sort key starts with `prefix` (`PLAN##TASK#`). + async fn tasks_under(&self, team: &str, prefix: &str) -> Result, String> { + let (items, more) = crate::paged::all_pages( + |start| { + let q = self + .dynamo + .query() + .table_name(&self.plans_table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team.to_string())) + .expression_attribute_values(":p", AttributeValue::S(prefix.to_string())) + .set_exclusive_start_key(start); + async move { + let out = q.send().await.map_err(|e| { + aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string() + })?; + Ok::<_, String>((out.items.unwrap_or_default(), out.last_evaluated_key)) + } + }, + 1_000, + ) + .await?; + // A partial list could make a ticket look named by one task only. + if more { + return Err(format!("{team}: too many plan rows under {prefix} to read")); + } + Ok(items + .iter() + .filter_map(|i| { + let sk = s_of(i, "sk"); + let (plan_id, task_id) = sk.strip_prefix("PLAN#")?.split_once("#TASK#")?; + Some(Task { + plan_id: plan_id.to_string(), + task_id: task_id.to_string(), + status: s_of(i, "status"), + depends_on: s_of(i, "depends_on"), + issue_url: s_of(i, "issue_url"), + jira_ticket_key: s_of(i, "jira_ticket_key"), + }) + }) + .collect()) + } +} + +fn s_of(item: &HashMap, k: &str) -> String { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +/// Plan links and tasks in memory (tests). +#[derive(Default)] +pub struct MemoryPlans { + /// `(team, link_sk)` → `(plan_id, task_id)`. + pub links: Mutex>, + /// `(team, plan_id)` → tasks. + pub tasks: Mutex>>, +} + +impl MemoryPlans { + /// Links a ticket to its plan task. + pub fn link(&self, team: &str, link_sk: &str, plan_id: &str, task_id: &str) { + self.links.lock().unwrap_or_else(|e| e.into_inner()).insert( + (team.to_string(), link_sk.to_string()), + (plan_id.to_string(), task_id.to_string()), + ); + } + + /// Adds a task to a plan. + pub fn task(&self, team: &str, plan_id: &str, task_id: &str, status: &str, depends_on: &str) { + self.add( + team, + Task { + plan_id: plan_id.to_string(), + task_id: task_id.to_string(), + status: status.to_string(), + depends_on: depends_on.to_string(), + ..Task::default() + }, + ); + } + + /// Adds a task to its plan (`task.plan_id`). + pub fn add(&self, team: &str, task: Task) { + self.tasks + .lock() + .unwrap_or_else(|e| e.into_inner()) + .entry((team.to_string(), task.plan_id.clone())) + .or_default() + .push(task); + } +} + +#[async_trait::async_trait] +impl PlanStore for MemoryPlans { + async fn linked_task( + &self, + team: &str, + link_sk: &str, + ) -> Result, String> { + Ok(self + .links + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(&(team.to_string(), link_sk.to_string())) + .cloned()) + } + + async fn plan_tasks(&self, team: &str, plan_id: &str) -> Result, String> { + Ok(self + .tasks + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(&(team.to_string(), plan_id.to_string())) + .cloned() + .unwrap_or_default()) + } + + async fn team_tasks(&self, team: &str) -> Result, String> { + let tasks = self.tasks.lock().unwrap_or_else(|e| e.into_inner()); + let mut plans: Vec<_> = tasks.keys().filter(|(t, _)| t == team).collect(); + plans.sort(); + Ok(plans.into_iter().flat_map(|k| tasks[k].clone()).collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const T: &str = "TEAM#acme"; + + fn jira_run(key: &str) -> MergedRun { + MergedRun { + source: "jira".into(), + ticket_id: key.into(), + repo: "acme/web".into(), + issue_number: 0, + plan_id: String::new(), + } + } + + fn github_run(repo: &str, n: u64) -> MergedRun { + MergedRun { + source: "github".into(), + ticket_id: format!("GH-{n}"), + repo: repo.into(), + issue_number: n, + plan_id: String::new(), + } + } + + /// A task row that opened a ticket, as the plan records it. + fn ticket_task(plan: &str, id: &str, issue_url: &str, jira: &str) -> Task { + Task { + plan_id: plan.into(), + task_id: id.into(), + status: "done".into(), + issue_url: issue_url.into(), + jira_ticket_key: jira.into(), + ..Task::default() + } + } + + fn in_plan(run: MergedRun, plan: &str) -> MergedRun { + MergedRun { + plan_id: plan.into(), + ..run + } + } + + #[tokio::test] + async fn without_a_link_the_runs_plan_is_searched_for_the_issue() { + let s = MemoryPlans::default(); + // One plan, two repositories, both issues #12; no links were written. + s.add( + T, + ticket_task("p1", "t-web", "https://github.com/acme/web/issues/12", ""), + ); + s.add( + T, + ticket_task("p1", "t-api", "https://github.com/Acme/API/issues/12", ""), + ); + s.task(T, "p1", "t-web-next", WAITING, "t-web"); + s.task(T, "p1", "t-api-next", WAITING, "t-api"); + + let got = dependents_to_release(&s, T, &in_plan(github_run("acme/api", 12), "p1")) + .await + .unwrap(); + assert_eq!( + got, + Some(Release { + plan_id: "p1".into(), + task_id: "t-api".into(), + tasks: vec!["t-api-next".into()], + }) + ); + } + + #[tokio::test] + async fn without_a_link_or_a_plan_on_the_run_one_task_naming_the_ticket_is_found() { + // A plan from before links existed: its runs name no plan either. + let s = MemoryPlans::default(); + s.add( + T, + ticket_task("p-old", "t1", "https://github.com/acme/web/issues/7/", ""), + ); + s.task(T, "p-old", "t2", WAITING, "t1"); + s.add(T, ticket_task("p-jira", "j1", "", "PROJ-3")); + s.task(T, "p-jira", "j2", WAITING, "j1"); + // The same number in another repository, in another plan. + s.add( + T, + ticket_task("p-other", "o1", "https://github.com/acme/api/issues/7", ""), + ); + s.task(T, "p-other", "o2", WAITING, "o1"); + + let got = dependents_to_release(&s, T, &github_run("acme/web", 7)) + .await + .unwrap() + .expect("the old plan's waiting task is released"); + assert_eq!( + (got.plan_id.as_str(), got.task_id.as_str()), + ("p-old", "t1") + ); + assert_eq!(got.tasks, vec!["t2".to_string()]); + + let got = dependents_to_release(&s, T, &jira_run("proj-3")) + .await + .unwrap() + .expect("the Jira task's waiting task is released"); + assert_eq!( + (got.plan_id.as_str(), got.task_id.as_str()), + ("p-jira", "j1") + ); + assert_eq!(got.tasks, vec!["j2".to_string()]); + } + + #[tokio::test] + async fn a_ticket_two_tasks_name_releases_nothing_without_a_link() { + let s = MemoryPlans::default(); + for plan in ["p1", "p2"] { + s.add( + T, + ticket_task(plan, "t1", "https://github.com/acme/web/issues/4", "OPS-9"), + ); + s.task(T, plan, "t2", WAITING, "t1"); + } + for run in [github_run("acme/web", 4), jira_run("OPS-9")] { + assert_eq!(dependents_to_release(&s, T, &run).await.unwrap(), None); + } + } + + #[tokio::test] + async fn without_a_link_the_search_stays_in_the_runs_plan() { + let s = MemoryPlans::default(); + s.add( + T, + ticket_task("p-other", "t1", "https://github.com/acme/web/issues/4", ""), + ); + s.task(T, "p-other", "t2", WAITING, "t1"); + s.task(T, "p-mine", "m1", "running", ""); + let run = in_plan(github_run("acme/web", 4), "p-mine"); + assert_eq!(dependents_to_release(&s, T, &run).await.unwrap(), None); + } + + #[tokio::test] + async fn without_a_link_a_bare_number_or_number_zero_never_matches() { + let s = MemoryPlans::default(); + // A task with an issue number but no URL, and one whose URL is #0. + s.add( + T, + Task { + plan_id: "p1".into(), + task_id: "t-bare".into(), + ..Task::default() + }, + ); + s.task(T, "p1", "t-bare-next", WAITING, "t-bare"); + s.add( + T, + ticket_task("p2", "t-zero", "https://github.com/acme/web/issues/0", ""), + ); + s.task(T, "p2", "t-zero-next", WAITING, "t-zero"); + for run in [ + github_run("acme/web", 0), + in_plan(github_run("acme/web", 0), "p2"), + in_plan(github_run("", 5), "p1"), + in_plan(github_run("acme/web", 5), "p1"), + jira_run(""), + ] { + assert_eq!(dependents_to_release(&s, T, &run).await.unwrap(), None); + } + } + + #[tokio::test] + async fn the_link_is_looked_up_before_the_task_rows() { + let s = MemoryPlans::default(); + s.task(T, "p-linked", "t1", "running", ""); + s.task(T, "p-linked", "t2", WAITING, "t1"); + s.link(T, &github_link_sk("acme/web", 8), "p-linked", "t1"); + // Another plan's row also names the issue; the link wins. + s.add( + T, + ticket_task("p-row", "r1", "https://github.com/acme/web/issues/8", ""), + ); + s.task(T, "p-row", "r2", WAITING, "r1"); + let got = dependents_to_release(&s, T, &github_run("acme/web", 8)) + .await + .unwrap() + .unwrap(); + assert_eq!( + (got.plan_id.as_str(), got.task_id.as_str()), + ("p-linked", "t1") + ); + } + + #[test] + fn issue_urls_give_repository_and_number() { + assert_eq!( + issue_of_url("https://github.com/Acme/Web/issues/12"), + Some(("acme/web".into(), 12)) + ); + assert_eq!( + issue_of_url("https://ghe.example.com/acme/web/issues/3/"), + Some(("acme/web".into(), 3)) + ); + for bad in [ + "", + "https://github.com/acme/web/pull/12", + "https://github.com/acme/web/issues/0", + "https://github.com/acme/web/issues/x", + "github.com/acme/web/issues/12", + ] { + assert_eq!(issue_of_url(bad), None, "{bad}"); + } + } + + #[tokio::test] + async fn a_merged_jira_task_releases_its_own_dependents() { + let s = MemoryPlans::default(); + // Another plan's GitHub task that has no issue yet (issue number 0), + // with a task waiting on it. + s.task(T, "p-other", "t-draft", "draft", ""); + s.task(T, "p-other", "t-other-next", WAITING, "t-draft"); + // The Jira plan: t2 waits on t1, whose ticket is PROJ-7. + s.task(T, "p-jira", "t1", "running", ""); + s.task(T, "p-jira", "t2", WAITING, "t1"); + s.link(T, &jira_link_sk("PROJ-7"), "p-jira", "t1"); + + let got = dependents_to_release(&s, T, &jira_run("PROJ-7")) + .await + .unwrap(); + assert_eq!( + got, + Some(Release { + plan_id: "p-jira".into(), + task_id: "t1".into(), + tasks: vec!["t2".into()], + }) + ); + } + + #[tokio::test] + async fn the_same_issue_number_in_another_repository_releases_nothing() { + let s = MemoryPlans::default(); + // One plan spans two repositories; both tasks' issues are #12. + s.task(T, "p1", "t-web", "running", ""); + s.task(T, "p1", "t-web-next", WAITING, "t-web"); + s.task(T, "p1", "t-api", "running", ""); + s.task(T, "p1", "t-api-next", WAITING, "t-api"); + s.link(T, &github_link_sk("acme/web", 12), "p1", "t-web"); + s.link(T, &github_link_sk("acme/api", 12), "p1", "t-api"); + + let got = dependents_to_release(&s, T, &github_run("Acme/API", 12)) + .await + .unwrap() + .expect("the api task's dependents are released"); + assert_eq!(got.task_id, "t-api"); + assert_eq!(got.tasks, vec!["t-api-next".to_string()]); + } + + #[tokio::test] + async fn a_merge_whose_ticket_no_plan_opened_releases_nothing() { + let s = MemoryPlans::default(); + // A plan task whose issue is #5 in acme/web, linked there. + s.task(T, "p1", "t1", "running", ""); + s.task(T, "p1", "t2", WAITING, "t1"); + s.link(T, &github_link_sk("acme/web", 5), "p1", "t1"); + + // Issue #5 in another repository, and a Jira ticket, neither from a plan. + for run in [github_run("acme/api", 5), jira_run("OPS-1")] { + assert_eq!(dependents_to_release(&s, T, &run).await.unwrap(), None); + } + } + + #[tokio::test] + async fn issue_number_zero_never_matches() { + let s = MemoryPlans::default(); + s.task(T, "p1", "t1", "draft", ""); + s.task(T, "p1", "t2", WAITING, "t1"); + s.link(T, &github_link_sk("acme/web", 0), "p1", "t1"); + for run in [ + github_run("acme/web", 0), + MergedRun::default(), + jira_run(""), + MergedRun { + source: "alert".into(), + ..github_run("acme/web", 0) + }, + ] { + assert_eq!(dependents_to_release(&s, T, &run).await.unwrap(), None); + } + } + + #[tokio::test] + async fn only_waiting_tasks_on_the_merged_task_are_released() { + let s = MemoryPlans::default(); + s.task(T, "p1", "t1", "running", ""); + s.task(T, "p1", "t2", WAITING, "t1"); + s.task(T, "p1", "t3", "running", "t1"); + s.task(T, "p1", "t4", WAITING, "t2"); + s.task(T, "p1", "t5", WAITING, "t1"); + s.link(T, &github_link_sk("acme/web", 3), "p1", "t1"); + let got = dependents_to_release(&s, T, &github_run("acme/web", 3)) + .await + .unwrap() + .unwrap(); + assert_eq!(got.tasks, vec!["t2".to_string(), "t5".to_string()]); + } + + #[test] + fn a_run_record_gives_the_link_the_plan_wrote() { + let item: HashMap = [ + ("ticket_source", AttributeValue::S("github".into())), + ("ticket_id", AttributeValue::S("GH-9".into())), + ("repo", AttributeValue::S("Acme/Web".into())), + ("issue_number", AttributeValue::N("9".into())), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + let run = MergedRun::from_item(&item); + assert_eq!( + link_sk(&run).as_deref(), + Some("PLAN_TICKET#github#acme/web#9") + ); + assert_eq!( + link_sk(&jira_run("proj-7")).as_deref(), + Some("PLAN_TICKET#jira#PROJ-7") + ); + } +} diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 78349c1df..fcc0ba57c 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -2193,20 +2193,15 @@ async fn handle_pull_request( .await; // ── Plan task dependency continuation ── - // If this run's issue belongs to a plan task, check for waiting dependents. - if let Some(issue_num) = item - .get("issue_number") - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse::().ok()) - { - if let Err(e) = trigger_plan_dependents(state, team_id, issue_num).await { - warn!( - team_id, - issue_num, - error = %e, - "Failed to check plan task dependents" - ); - } + // If this run's ticket came from a plan task, start the tasks + // waiting on it. + if let Err(e) = trigger_plan_dependents(state, team_id, item).await { + warn!( + team_id, + run_id, + error = %e, + "Failed to check plan task dependents" + ); } } } @@ -4786,133 +4781,38 @@ async fn write_run_event( } } -/// After a PR merges, check if the merged run's issue belongs to a plan task. -/// If so, find waiting tasks that depend on it and dispatch them to the worker. +/// After a PR merges, start the plan tasks waiting on the merged run's task, +/// found through its ticket's plan link, or without one through the task row +/// that records the ticket (see `common::plan_dependents`). async fn trigger_plan_dependents( state: &AppState, team_id: &str, - issue_number: u64, + run: &common::paged::Item, ) -> Result<(), Box> { - use aws_sdk_dynamodb::types::AttributeValue; - - // Query all items in the plans table for this team (plans + tasks share pk) - let mut exclusive_start_key = None; - let mut matched_plan_id = String::new(); - let mut matched_task_id = String::new(); - - 'outer: loop { - let mut query = state - .dynamo - .query() - .table_name(&state.config.plans_table_name) - .key_condition_expression("pk = :pk") - .expression_attribute_values(":pk", AttributeValue::S(team_id.to_string())); - - if let Some(key) = exclusive_start_key.take() { - query = query.set_exclusive_start_key(Some(key)); - } - - let result = query.send().await?; - - for item in result.items() { - // Only look at task items (sk contains #TASK#) - let sk = item - .get("sk") - .and_then(|v| v.as_s().ok()) - .cloned() - .unwrap_or_default(); - if !sk.contains("#TASK#") { - continue; - } - - let item_issue = item - .get("issue_number") - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse::().ok()) - .unwrap_or(0); - if item_issue == issue_number { - // Parse plan_id and task_id from sk: PLAN##TASK# - let parts: Vec<&str> = sk.split('#').collect(); - if parts.len() >= 4 { - matched_plan_id = parts[1].to_string(); - matched_task_id = parts[3].to_string(); - } - break 'outer; - } - } - - match result.last_evaluated_key() { - Some(key) => exclusive_start_key = Some(key.clone()), - None => break, - } - } - - if matched_plan_id.is_empty() || matched_task_id.is_empty() { - return Ok(()); // Not a plan task — nothing to do - } + use common::plan_dependents::{dependents_to_release, DynamoPlans, MergedRun}; - info!( - team_id, - plan_id = %matched_plan_id, - task_id = %matched_task_id, - "Merged PR belongs to plan task — checking for waiting dependents" - ); - - // Query all tasks in this plan to find those waiting on the matched task - let tasks_result = state - .dynamo - .query() - .table_name(&state.config.plans_table_name) - .key_condition_expression("pk = :pk AND begins_with(sk, :sk_prefix)") - .expression_attribute_values(":pk", AttributeValue::S(team_id.to_string())) - .expression_attribute_values( - ":sk_prefix", - AttributeValue::S(format!("PLAN#{}#TASK#", matched_plan_id)), - ) - .send() - .await?; - - let mut tasks_to_continue: Vec = Vec::new(); - for item in tasks_result.items() { - let status = item - .get("status") - .and_then(|v| v.as_s().ok()) - .map(String::as_str) - .unwrap_or(""); - let depends_on = item - .get("depends_on") - .and_then(|v| v.as_s().ok()) - .map(String::as_str) - .unwrap_or(""); - - if status == "waiting" && depends_on == matched_task_id { - let sk = item - .get("sk") - .and_then(|v| v.as_s().ok()) - .map(String::as_str) - .unwrap_or(""); - let parts: Vec<&str> = sk.split('#').collect(); - if parts.len() >= 4 { - tasks_to_continue.push(parts[3].to_string()); - } - } - } - - if tasks_to_continue.is_empty() { - return Ok(()); - } + let store = DynamoPlans { + dynamo: state.dynamo.clone(), + settings_table: state.config.settings_table_name.clone(), + plans_table: state.config.plans_table_name.clone(), + }; + let Some(release) = dependents_to_release(&store, team_id, &MergedRun::from_item(run)).await? + else { + return Ok(()); // Not a plan task, or nothing waits on it + }; info!( team_id, - plan_id = %matched_plan_id, - tasks = tasks_to_continue.len(), - "Triggering waiting plan tasks" + plan_id = %release.plan_id, + task_id = %release.task_id, + tasks = release.tasks.len(), + "Merged PR belongs to plan task — triggering waiting plan tasks" ); let message = WorkerMessage::PlanTaskContinue(PlanTaskContinueMessage { team_id: team_id.to_string(), - plan_id: matched_plan_id, - tasks: tasks_to_continue, + plan_id: release.plan_id, + tasks: release.tasks, }); let body = serde_json::to_string(&message)?; diff --git a/services/worker/src/passes/plan_execute.rs b/services/worker/src/passes/plan_execute.rs index 6723be327..0361f1943 100644 --- a/services/worker/src/passes/plan_execute.rs +++ b/services/worker/src/passes/plan_execute.rs @@ -307,9 +307,9 @@ impl PlanTicket<'_> { pub(crate) fn sk(&self) -> String { match self { PlanTicket::Github { repo, issue_number } => { - format!("PLAN_TICKET#github#{}#{issue_number}", repo.to_lowercase()) + common::plan_dependents::github_link_sk(repo, *issue_number) } - PlanTicket::Jira(key) => format!("PLAN_TICKET#jira#{}", key.to_uppercase()), + PlanTicket::Jira(key) => common::plan_dependents::jira_link_sk(key), } } From 44ed8c5ab6e446541094a89a2f43961c7d85981e Mon Sep 17 00:00:00 2001 From: Nam Bok Rodriguez Date: Tue, 17 Nov 2026 19:57:33 -0500 Subject: [PATCH 22/32] Pin the dashboard for the November 17 test-run release (#771) --- selfhost/versions.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selfhost/versions.json b/selfhost/versions.json index 77f6fd337..1b3b1bcbe 100644 --- a/selfhost/versions.json +++ b/selfhost/versions.json @@ -1,4 +1,4 @@ { "about": "The dashboard commit each platform release ships: a full 40-character commit SHA of CoderHelm/coderhelm, never a branch or tag (scripts/check-dashboard-ref.mjs fails CI and the release otherwise). The release workflow builds exactly this commit (dashboard/) into dashboard.tar.gz. Move it with scripts/bump-dashboard.sh in a reviewed PR, in the same PR as any API change the dashboard needs.", - "dashboardRef": "f4a5e35923f195648634e5c2fd00a934fa9c8f72" + "dashboardRef": "d39bb05853ce0df1fd3609ba916a696b25777422" } From 08820b48a9176fe7f2eb1b567f4d36fdc801b60d Mon Sep 17 00:00:00 2001 From: Nam Bok Rodriguez Date: Wed, 18 Nov 2026 00:27:20 -0500 Subject: [PATCH 23/32] Find each pull request's preview wherever it is published (#772) The preview was found only through a workflow CoderHelm recognized, an address whose host said "preview", and a deployment's first status of any state. A host that publishes its preview through deployments, deploy statuses, check runs or a bot comment was read as having no preview, a protected preview could not be opened, and a preview still building was waited on with no limit. - common::preview_find reads every route a preview is published on (deployment statuses, commit statuses, check runs, bot comments edited in place, the description, the team's address template), counts only what is tied to the head commit first, picks the changed app's preview in a monorepo, and gives one answer: up, building, failed, or nothing. - preview::settle bounds the wait: a short grace when nothing is published, a pending preview looked at every two minutes, at most an hour per commit, and a failed or taken-down deploy said with its source. - common::preview_access and /api/repos/:owner/:name/preview-access: one per-repository Settings item holding the address template and a sealed secret (header lines, query parameters or a password) that the capture sends only to the preview's own host. - The capture keeps a preview's path, retries pages still warming up, and reads a sign-in wall (401, 403, or a redirect to another host) as a wall that points to the setting. - Replay tests with payloads shaped like the code host's listings and common preview bots' comments, one per route. --- docs/coder-loop.md | 16 + services/common/src/lib.rs | 2 + services/common/src/preview.rs | 258 +++-- services/common/src/preview_access.rs | 335 ++++++ .../src/preview_find/fixtures/check_runs.json | 18 + .../preview_find/fixtures/comment_head.json | 8 + .../src/preview_find/fixtures/comments.json | 10 + .../preview_find/fixtures/deployments.json | 55 + .../src/preview_find/fixtures/statuses.json | 12 + .../fixtures/workflow_environment.json | 13 + services/common/src/preview_find/mod.rs | 992 ++++++++++++++++++ services/common/src/preview_find/tests.rs | 356 +++++++ services/gateway/src/main.rs | 6 + services/gateway/src/permissions.rs | 4 + services/gateway/src/routes/mod.rs | 1 + services/gateway/src/routes/preview_access.rs | 251 +++++ services/worker/src/clients/github.rs | 72 +- services/worker/src/passes/ci_repro.rs | 2 +- services/worker/src/passes/pr_watch.rs | 45 +- services/worker/src/passes/preview.rs | 533 ++++++++-- 20 files changed, 2757 insertions(+), 232 deletions(-) create mode 100644 services/common/src/preview_access.rs create mode 100644 services/common/src/preview_find/fixtures/check_runs.json create mode 100644 services/common/src/preview_find/fixtures/comment_head.json create mode 100644 services/common/src/preview_find/fixtures/comments.json create mode 100644 services/common/src/preview_find/fixtures/deployments.json create mode 100644 services/common/src/preview_find/fixtures/statuses.json create mode 100644 services/common/src/preview_find/fixtures/workflow_environment.json create mode 100644 services/common/src/preview_find/mod.rs create mode 100644 services/common/src/preview_find/tests.rs create mode 100644 services/gateway/src/routes/preview_access.rs diff --git a/docs/coder-loop.md b/docs/coder-loop.md index c5d4c2995..088c79697 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -142,6 +142,22 @@ The causes were in the loop, not only in prompt wording: run) is judged again with what it found, even when it wrote no code (`proof::round_answered`, `incidents::cn_proof_answer_judged`). + **The preview, wherever it is published.** The head commit's preview is + found where the team's host or CI already publishes it, never only from + a workflow CoderHelm recognizes (`preview_find`): the commit's + deployments and their newest status, deploy statuses, preview checks, + bot comments (edited in place, read row by row for a monorepo), a + description link, then the team's address template (Settings, + Repositories, Preview access; `{pr}`, `{branch}`, `{branch_slug}`, + `{sha}`, `{short_sha}`). Only what is tied to the head commit counts + first; the changed app's preview is picked when several apps publish + one; a preview still building is waited on, looked at every two minutes, + for at most an hour (`preview::settle`). A protected preview is opened + with the one secret the team saved there (a header, a query parameter or + a password), sealed, handed to the sandbox once and sent only to the + preview's own host (`preview_access`); a sign-in wall is said with where + to give that access. + **Two ways, end to end.** Before the pull request is called done, once its preview is up and its own end-to-end checks passed, the pull request watch runs each criterion's test (the one the criteria map names, else a diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 7c773dc64..bdfcb1d20 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -212,6 +212,8 @@ pub mod pr_steps; /// A repository's pull request template as the description's structure. pub mod pr_template; pub mod preview; +pub mod preview_access; +pub mod preview_find; /// What a fix must show before it is committed and pushed. pub mod push_gate; /// A bug reproduced on the base before code is planned, fixed in the diff --git a/services/common/src/preview.rs b/services/common/src/preview.rs index 5544cacaa..c7fa8342b 100644 --- a/services/common/src/preview.rs +++ b/services/common/src/preview.rs @@ -32,6 +32,9 @@ //! - [`routes`] picks the pages to capture from the repository's page files //! and the changed paths; [`capture_script`] is the sandbox script that //! captures them. +//! - Where the preview is and whether it is up for the head commit is +//! `crate::preview_find`'s: deployments, statuses, checks, bot comments, +//! the description and the team's address template, tied to the head. //! - [`State`] is what the run records ([`FIELD`]) and the description and //! the run page read. @@ -683,6 +686,15 @@ pub struct State { /// says (`crate::e2e::failure_read`), with whether this change caused /// it. pub failures: Vec, + /// Where the preview's address came from (`crate::preview_find`). + pub found: crate::preview_find::Found, + /// When this head's preview was first waited on (RFC 3339): the wait is + /// bounded by `preview_find::WAIT_BUDGET_MINS`. + pub waiting_since: String, + /// When the preview was last looked at (RFC 3339): a pending preview is + /// looked at again every `preview_find::POLL_SECS` even when nothing + /// else on the pull request changed. + pub looked_at: String, } impl State { @@ -740,41 +752,6 @@ pub fn progress(results: &[CheckResult], triggered: bool) -> Stage { Stage::Triggered } -/// A preview address in text (a check's output, a deployment, a comment): -/// the first https URL whose host names a preview. -pub fn url_in(text: &str) -> Option { - for (i, _) in text.match_indices("https://") { - let rest = &text[i..]; - let end = rest - .find(|c: char| { - c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>' | '<' | ']' | '`') - }) - .unwrap_or(rest.len()); - let url = rest[..end].trim_end_matches(['.', ',', ';']); - let host = url["https://".len()..].split('/').next().unwrap_or(""); - if host.to_ascii_lowercase().contains("preview") && !host.contains('@') { - return Some(url.to_string()); - } - } - None -} - -/// The preview address from the head's deployments: (environment, url) -/// pairs, a preview environment first, never a shared one. -pub fn url_from_deployments(deps: &[(String, String)]) -> Option { - let ok = |(env, url): &&(String, String)| { - url.starts_with("https://") && !is_shared_env_label(env) && role_of(env) != Role::Production - }; - deps.iter() - .filter(ok) - .find(|(env, url)| { - env.to_ascii_lowercase().contains("preview") - || url.to_ascii_lowercase().contains("preview") - }) - .or_else(|| deps.iter().find(ok)) - .map(|(_, u)| u.clone()) -} - // ── end-to-end specs ─────────────────────────────────────────────────────── /// The repository's end-to-end suite: the folder its runner's config is in. @@ -1115,12 +1092,37 @@ pub fn shot_name(page: &str, width: &str) -> String { format!("{slug}-{width}") } +/// The address pages are captured under: the preview's address without +/// its query or fragment and without a trailing `/`, its path kept (a +/// preview served under a path, `https://host/pr-12/`, keeps it). +pub fn capture_base(url: &str) -> String { + url.split(['?', '#']) + .next() + .unwrap_or(url) + .trim_end_matches('/') + .to_string() +} + +/// How long the capture waits between tries of a page that is still +/// warming up (404, 502, 503 or 504 on a fresh preview), and how many +/// tries it makes. +pub const WARM_TRIES: u32 = 3; +pub const WARM_WAIT_MS: u32 = 15_000; + /// The sandbox script that captures each page at both widths. It writes /// each image base64-encoded (`.png.b64`) and `shots.json` (each -/// page's status and title) to `$CODERHELM_OUT`; a page that doesn't load -/// is recorded with its status, never retried into a pass. -pub fn capture_script(base: &str, pages: &[String]) -> String { - let base = base.trim_end_matches('/'); +/// page's status, title and, when the browser was sent to another host, +/// that host) to `$CODERHELM_OUT`. A page still warming up is tried +/// [`WARM_TRIES`] times; one that doesn't load is recorded with its status, +/// never retried into a pass. +/// +/// `access` is how the preview is protected (`crate::preview_access`). Its +/// secret is never in the script: the sandbox hands the script its one-time +/// secret in `GH_TOKEN` (the channel every sandbox script's secret takes), +/// the script removes it from its environment at once, sends it only to the +/// preview's own host, and blanks it out of anything it writes. +pub fn capture_script(base: &str, pages: &[String], access: crate::preview_access::Kind) -> String { + let base = capture_base(base); let mut jobs = Vec::new(); for p in pages { for (width, (w, h)) in [("desktop", DESKTOP), ("phone", PHONE)] { @@ -1135,27 +1137,69 @@ pub fn capture_script(base: &str, pages: &[String]) -> String { } } let jobs = serde_json::to_string(&jobs).unwrap_or_else(|_| "[]".into()); + let base_js = serde_json::to_string(&base).unwrap_or_else(|_| "\"\"".into()); + let kind = serde_json::to_string(access.as_str()).unwrap_or_else(|_| "\"none\"".into()); format!( r#"import {{ chromium }} from 'playwright'; import {{ writeFileSync }} from 'node:fs'; const out = process.env.CODERHELM_OUT || '.'; +const secret = (process.env.GH_TOKEN || '').trim(); +delete process.env.GH_TOKEN; delete process.env.GITHUB_TOKEN; +const kind = {kind}; +const host = new URL({base_js}).host; +const hide = (s) => secret ? String(s).split(secret).join('***') : String(s); +const ctxOpts = {{}}; +const headers = {{}}; +if (kind === 'header' && secret) {{ + for (const line of secret.split('\n')) {{ + const i = line.indexOf(':'); + if (i > 0) headers[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim(); + }} +}} +if (kind === 'basic' && secret) {{ + const i = secret.indexOf(':'); + ctxOpts.httpCredentials = {{ username: secret.slice(0, i), password: secret.slice(i + 1), origin: 'https://' + host }}; +}} +const withQuery = (u) => (kind === 'query' && secret) ? u + (u.includes('?') ? '&' : '?') + secret : u; +const warming = (s) => [404, 502, 503, 504].includes(s); const jobs = {jobs}; const results = []; const browser = await chromium.launch(); for (const j of jobs) {{ - const page = await browser.newPage({{ viewport: {{ width: j.w, height: j.h }} }}); - let status = 0, title = '', error = ''; + const context = await browser.newContext({{ viewport: {{ width: j.w, height: j.h }}, ...ctxOpts }}); + if (Object.keys(headers).length) {{ + // The secret goes to the preview's own host only, never to a font, a + // script or an image another host serves. + await context.route('**/*', (route) => {{ + const req = route.request(); + let h = ''; + try {{ h = new URL(req.url()).host; }} catch (e) {{}} + if (h === host) route.continue({{ headers: {{ ...req.headers(), ...headers }} }}); + else route.continue(); + }}); + }} + const page = await context.newPage(); + let status = 0, title = '', error = '', left = ''; + for (let t = 1; t <= {WARM_TRIES}; t++) {{ + error = ''; + try {{ + const res = await page.goto(withQuery(j.url), {{ waitUntil: 'networkidle', timeout: 45000 }}); + status = res ? res.status() : 0; + }} catch (e) {{ status = 0; error = hide(String(e).slice(0, 300)); }} + if (!warming(status) && !(status === 0 && error) || t === {WARM_TRIES}) break; + await new Promise((r) => setTimeout(r, {WARM_WAIT_MS})); + }} try {{ - const res = await page.goto(j.url, {{ waitUntil: 'networkidle', timeout: 45000 }}); - status = res ? res.status() : 0; - title = await page.title(); - if (status > 0 && status < 400) {{ + const now = new URL(page.url()).host; + if (now && now !== host) left = now; + title = hide(await page.title()); + if (status > 0 && status < 400 && !left) {{ const png = await page.screenshot({{ fullPage: false }}); writeFileSync(`${{out}}/${{j.name}}.png.b64`, png.toString('base64')); }} - }} catch (e) {{ error = String(e).slice(0, 300); }} - results.push({{ page: j.page, width: j.width, name: j.name, status, title, error }}); - await page.close(); + }} catch (e) {{ error = error || hide(String(e).slice(0, 300)); }} + results.push({{ page: j.page, width: j.width, name: j.name, status, title, error, left }}); + await context.close(); }} await browser.close(); writeFileSync(`${{out}}/shots.json`, JSON.stringify(results)); @@ -1189,16 +1233,48 @@ pub struct Captured { pub status: u16, pub title: String, pub error: String, + /// The host the browser was sent to instead of the preview's (a + /// sign-in page), "" when it stayed. + pub left: String, +} + +impl Captured { + /// The page loaded on the preview itself. + pub fn shot(&self) -> bool { + (1..400).contains(&self.status) && self.left.is_empty() + } } -/// Why no page was captured, from the capture's report: a login wall, a -/// page that didn't load, or nothing at all. None when one was. -pub fn why_no_shot(report: &[Captured]) -> Option { - if report.iter().any(|c| (1..400).contains(&c.status)) { +/// Where a team gives CoderHelm a protected preview's access. +pub const ACCESS_SETTING: &str = "Settings, Repositories, Preview access"; + +/// Why no page was captured, from the capture's report: a sign-in wall +/// (the preview answered 401 or 403, or sent the browser to another host), +/// a page that didn't load, or nothing at all. None when one was. +/// `has_access`: the team saved the preview's access, so a wall means that +/// access was refused. +pub fn why_no_shot(report: &[Captured], has_access: bool) -> Option { + if report.iter().any(Captured::shot) { return None; } - if report.iter().any(|c| c.status == 401 || c.status == 403) { - return Some("the preview asks for a login, so its pages couldn't be captured".into()); + let wall = report + .iter() + .find(|c| c.status == 401 || c.status == 403 || !c.left.is_empty()); + if let Some(c) = wall { + let how = if c.left.is_empty() { + format!("it answered {}", c.status) + } else { + format!("it sent the browser to `{}`", c.left) + }; + return Some(if has_access { + format!( + "the preview refused the access saved in {ACCESS_SETTING} ({how}), so its pages couldn't be captured" + ) + } else { + format!( + "the preview asks for a sign-in ({how}), so its pages couldn't be captured; give CoderHelm its access in {ACCESS_SETTING}" + ) + }); } if let Some(c) = report.iter().find(|c| c.status >= 400) { return Some(format!( @@ -1597,29 +1673,6 @@ jobs: ); } - #[test] - fn a_preview_address_is_found_in_deployments_and_text() { - let deps = vec![ - ( - "staging".to_string(), - "https://staging.example.com".to_string(), - ), - ( - "pr-12".to_string(), - "https://pr-12.preview-web.example.com".to_string(), - ), - ]; - assert_eq!( - url_from_deployments(&deps).as_deref(), - Some("https://pr-12.preview-web.example.com") - ); - assert_eq!( - url_in("Deployed to https://pr-7.preview-web.example.com/ (ready).").as_deref(), - Some("https://pr-7.preview-web.example.com/") - ); - assert_eq!(url_in("see https://example.com/docs"), None); - } - #[test] fn a_visible_change_needs_an_e2e_spec_in_a_repo_with_a_suite() { let tree = s(&[ @@ -1666,21 +1719,66 @@ jobs: #[test] fn the_capture_script_takes_each_page_at_desktop_and_phone_width() { - let js = capture_script("https://pr-1.preview-web.example.com/", &s(&["/signup"])); + use crate::preview_access::Kind; + let js = capture_script( + "https://pr-1.preview-web.example.com/", + &s(&["/signup"]), + Kind::None, + ); assert!(js.contains("https://pr-1.preview-web.example.com/signup")); assert!(js.contains("signup-desktop") && js.contains("signup-phone")); assert!(js.contains("\"w\":390") && js.contains("\"w\":1280")); + // A preview served under a path keeps it; its query is dropped. + let js = capture_script( + "https://previews.example.com/pr-12/?x=1", + &s(&["/signup"]), + Kind::None, + ); + assert!(js.contains("https://previews.example.com/pr-12/signup")); let report = vec![Captured { status: 401, page: "/signup".into(), ..Default::default() }]; - assert!(why_no_shot(&report).unwrap().contains("login")); + let why = why_no_shot(&report, false).unwrap(); + assert!( + why.contains("sign-in") && why.contains(ACCESS_SETTING), + "{why}" + ); + assert!(why_no_shot(&report, true).unwrap().contains("refused")); + // Sent to a sign-in page on another host: a wall, never a shot. + let sent = vec![Captured { + status: 200, + left: "sso.example.org".into(), + ..Default::default() + }]; + assert!(why_no_shot(&sent, false) + .unwrap() + .contains("sso.example.org")); let ok = vec![Captured { status: 200, ..Default::default() }]; - assert_eq!(why_no_shot(&ok), None); + assert_eq!(why_no_shot(&ok, false), None); + } + + #[test] + fn a_protected_previews_secret_never_enters_the_script_and_goes_only_to_its_host() { + use crate::preview_access::Kind; + for kind in [Kind::Header, Kind::Query, Kind::Basic] { + let js = capture_script("https://pr-1.preview.example.com", &s(&["/"]), kind); + assert!(js.contains(&format!("const kind = \"{}\"", kind.as_str()))); + // Read once from the one-time secret, then removed from the + // environment, and blanked out of what is written. + assert!(js.contains("delete process.env.GH_TOKEN")); + assert!(js.contains("const hide =")); + } + let js = capture_script("https://pr-1.preview.example.com", &s(&["/"]), Kind::Header); + assert!(js.contains("if (h === host) route.continue({ headers:")); + assert!(js.contains("origin: 'https://' + host")); + // A page still warming up is tried again, a bounded number of times. + assert!(js.contains("[404, 502, 503, 504]")); + assert!(js.contains(&format!("t <= {WARM_TRIES}"))); } #[test] diff --git a/services/common/src/preview_access.rs b/services/common/src/preview_access.rs new file mode 100644 index 000000000..c705ee423 --- /dev/null +++ b/services/common/src/preview_access.rs @@ -0,0 +1,335 @@ +//! A repository's preview access: optional, per repository, one Settings +//! item (Settings, Repositories, Preview access). +//! +//! Most previews are found and opened with nothing set (`preview_find` +//! reads deployments, statuses, checks and comments). Two things only a +//! team can give, and they live here: +//! +//! - the preview's address as a template (`https://pr-{pr}.preview.example`), +//! for a host that publishes it nowhere CoderHelm can read +//! (`preview_find::expand`); +//! - how an automated browser gets through a protected preview, with one +//! secret the team stores: +//! - [`Kind::Header`]: one to four `Name: value` lines sent with every +//! request to the preview's host only (a protection bypass header, a +//! sign-in wall's service token pair); +//! - [`Kind::Query`]: `name=value` added to each page's address (a bypass +//! parameter that sets a cookie); +//! - [`Kind::Basic`]: `user:password` answered to the preview host's +//! password prompt. +//! +//! The secret is sealed by KMS bound to the team, the repository and this +//! purpose, never returned by the API, handed to the sandbox's capture +//! through its one-time secret object (never in the script, its environment +//! or its log) and only ever sent to the preview's own host. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; + +/// The settings-table sort key for a repository's preview access. +pub fn sk(repo: &str) -> String { + format!("PREVIEW_ACCESS#REPO#{repo}") +} + +/// Where the sealed secret is kept on the record. +pub const SECRET_ATTR: &str = "secret_sealed"; +const PURPOSE: &str = "preview-access"; +/// The longest secret kept. +pub const MAX_SECRET: usize = 2000; +/// Header lines a header secret may hold. +pub const MAX_HEADERS: usize = 4; + +/// How the preview is protected. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// Open, or only the address is set. + #[default] + None, + Header, + Query, + Basic, +} + +impl Kind { + pub fn parse(s: &str) -> Option { + match s.trim() { + "" | "none" => Some(Kind::None), + "header" => Some(Kind::Header), + "query" => Some(Kind::Query), + "basic" => Some(Kind::Basic), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Kind::None => "none", + Kind::Header => "header", + Kind::Query => "query", + Kind::Basic => "basic", + } + } +} + +/// A repository's preview access, without its secret. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct PreviewAccess { + /// `owner/name`. + pub repo: String, + pub kind: Kind, + /// The preview's address template, "" when the preview publishes its + /// own address. + pub address: String, +} + +/// Headers a secret may not set: the browser owns them. +const OWNED_HEADERS: &[&str] = &[ + "host", + "content-length", + "connection", + "transfer-encoding", + "upgrade", + "te", + "trailer", + "keep-alive", +]; + +fn token_chars(s: &str, extra: &[char]) -> bool { + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || extra.contains(&c)) +} + +/// Checks a secret's shape for its kind; the error is one sentence a person +/// can act on and never repeats the secret. +pub fn check_secret(kind: Kind, secret: &str) -> Result<(), String> { + if secret.len() > MAX_SECRET { + return Err("The secret is too long.".into()); + } + if secret + .chars() + .any(|c| c.is_control() && c != '\n' && c != '\r') + { + return Err("The secret can't hold control characters.".into()); + } + match kind { + Kind::None => Ok(()), + Kind::Header => { + let lines: Vec<&str> = secret + .lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .collect(); + if lines.is_empty() || lines.len() > MAX_HEADERS { + return Err(format!( + "Enter one to {MAX_HEADERS} lines, each `Header-Name: value`." + )); + } + for l in lines { + let Some((name, value)) = l.split_once(':') else { + return Err("Each line is `Header-Name: value`.".into()); + }; + let name = name.trim(); + if !token_chars(name, &['-', '_']) { + return Err(format!("`{name}` isn't a header name.")); + } + if OWNED_HEADERS.contains(&name.to_ascii_lowercase().as_str()) { + return Err(format!("`{name}` is set by the browser itself.")); + } + if value.trim().is_empty() { + return Err(format!("The `{name}` header has no value.")); + } + } + Ok(()) + } + Kind::Query => { + let s = secret.trim(); + if s.contains(char::is_whitespace) || s.starts_with('?') || s.contains('#') { + return Err("Enter the parameters as `name=value` (join several with &).".into()); + } + for pair in s.split('&') { + let Some((name, value)) = pair.split_once('=') else { + return Err( + "Enter the parameters as `name=value` (join several with &).".into(), + ); + }; + if !token_chars(name, &['-', '_', '.']) || value.is_empty() { + return Err( + "Enter the parameters as `name=value` (join several with &).".into(), + ); + } + } + Ok(()) + } + Kind::Basic => match secret.trim().split_once(':') { + Some((user, pass)) if !user.is_empty() && !pass.is_empty() && !user.contains('\n') => { + Ok(()) + } + _ => Err("Enter the user name and password as `user:password`.".into()), + }, + } +} + +impl PreviewAccess { + /// Checks the access as a team entered it. + pub fn validate(&self) -> Result<(), String> { + if !self.repo.contains('/') || self.repo.len() > 200 { + return Err("Pick the repository this is for.".into()); + } + crate::preview_find::check_template(&self.address)?; + if self.kind == Kind::None && self.address.trim().is_empty() { + return Err( + "Set the preview's address, how it is protected, or both. With neither, remove it." + .into(), + ); + } + Ok(()) + } + + /// The record, without the secret. + pub fn item(&self, team_id: &str) -> HashMap { + let s = |v: &str| AttributeValue::S(v.to_string()); + HashMap::from([ + ("pk".to_string(), s(team_id)), + ("sk".to_string(), s(&sk(&self.repo))), + ("repo".to_string(), s(&self.repo)), + ("kind".to_string(), s(self.kind.as_str())), + ("address".to_string(), s(&self.address)), + ]) + } + + /// Reads a record. `None` when it isn't one. + pub fn from_item(item: &HashMap) -> Option { + let s = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let a = PreviewAccess { + repo: s("repo"), + kind: Kind::parse(&s("kind")).unwrap_or_default(), + address: s("address"), + }; + (!a.repo.is_empty()).then_some(a) + } + + /// The API's view: never the secret, only whether one is set. + pub fn view(&self, secret_set: bool) -> serde_json::Value { + serde_json::json!({ + "configured": true, + "repo": self.repo, + "kind": self.kind.as_str(), + "address": self.address, + "secret_set": secret_set, + }) + } +} + +/// The encryption context: the team, the repository and the purpose. +pub fn context(team_id: &str, repo: &str) -> HashMap { + HashMap::from([ + ("team".to_string(), team_id.to_string()), + ("repo".to_string(), repo.to_string()), + ("purpose".to_string(), PURPOSE.to_string()), + ]) +} + +/// Seals a secret for one team's repository. Returns text safe to store. +pub async fn seal( + cipher: &dyn crate::mcp_credentials::Cipher, + team_id: &str, + repo: &str, + secret: &str, +) -> Result { + use base64::Engine; + let blob = cipher + .encrypt(context(team_id, repo), secret.as_bytes()) + .await?; + Ok(base64::engine::general_purpose::STANDARD.encode(blob)) +} + +/// Opens a secret sealed for one team's repository. +pub async fn open( + cipher: &dyn crate::mcp_credentials::Cipher, + team_id: &str, + repo: &str, + sealed: &str, +) -> Result { + use base64::Engine; + let bytes = base64::engine::general_purpose::STANDARD + .decode(sealed) + .map_err(|_| "stored secret is not valid".to_string())?; + let plain = cipher.decrypt(context(team_id, repo), &bytes).await?; + String::from_utf8(plain).map_err(|_| "stored secret is not text".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn secrets_are_checked_for_their_kind_without_repeating_them() { + assert!(check_secret(Kind::Header, "X-Bypass-Token: s3cr3t").is_ok()); + assert!(check_secret( + Kind::Header, + "X-Client-Id: abc.access\nX-Client-Secret: def\n" + ) + .is_ok()); + let e = check_secret(Kind::Header, "no-colon-s3cr3t").unwrap_err(); + assert!(!e.contains("s3cr3t"), "{e}"); + assert!(check_secret(Kind::Header, "Host: evil.example").is_err()); + assert!(check_secret(Kind::Header, "A: 1\nB: 2\nC: 3\nD: 4\nE: 5").is_err()); + assert!(check_secret(Kind::Query, "bypass=abc123").is_ok()); + assert!(check_secret(Kind::Query, "bypass=abc&set-cookie=true").is_ok()); + assert!(check_secret(Kind::Query, "?bypass=abc").is_err()); + assert!(check_secret(Kind::Query, "abc").is_err()); + assert!(check_secret(Kind::Basic, "preview:hunter2").is_ok()); + assert!(check_secret(Kind::Basic, "hunter2").is_err()); + assert!(check_secret(Kind::Basic, &"x".repeat(MAX_SECRET + 1)).is_err()); + } + + #[test] + fn an_access_needs_an_address_or_a_protection_and_a_valid_template() { + let a = |kind, address: &str| PreviewAccess { + repo: "acme/web".into(), + kind, + address: address.into(), + }; + assert!(a(Kind::None, "").validate().is_err()); + assert!(a(Kind::Header, "").validate().is_ok()); + assert!(a(Kind::None, "https://pr-{pr}.preview.example.com") + .validate() + .is_ok()); + assert!(a(Kind::None, "https://staging.example.com") + .validate() + .is_err()); + } + + #[test] + fn the_record_round_trips_without_its_secret() { + let a = PreviewAccess { + repo: "acme/web".into(), + kind: Kind::Query, + address: "https://pr-{pr}.preview.example.com".into(), + }; + let item = a.item("team-1"); + assert!(!item.contains_key(SECRET_ATTR)); + assert_eq!(PreviewAccess::from_item(&item), Some(a.clone())); + let v = a.view(true); + assert_eq!(v["kind"], "query"); + assert_eq!(v["secret_set"], true); + assert!(v.get("secret").is_none()); + } + + #[test] + fn the_seal_is_bound_to_the_team_repository_and_purpose() { + let c = context("team-1", "acme/web"); + assert_eq!(c["purpose"], "preview-access"); + assert_eq!(c["repo"], "acme/web"); + } +} diff --git a/services/common/src/preview_find/fixtures/check_runs.json b/services/common/src/preview_find/fixtures/check_runs.json new file mode 100644 index 000000000..4caf74939 --- /dev/null +++ b/services/common/src/preview_find/fixtures/check_runs.json @@ -0,0 +1,18 @@ +{ + "total_count": 3, + "check_runs": [ + {"id": 11, "name": "Edge preview", "head_sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", + "status": "completed", "conclusion": "success", "started_at": "2026-11-17T10:00:10Z", + "details_url": "https://dash.edge-host.example/acme/pages/view/web/8c1d", + "output": {"title": "Deployed successfully", + "summary": "| Name | Status | Preview URL | Branch Preview URL |\n|---|---|---|---|\n| web | ✅ Deployment successful! | https://8c1d2e3f.web.edge-host.example | https://feature-signup-form.web.edge-host.example |", + "text": null}}, + {"id": 12, "name": "E2E on preview", "head_sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", + "status": "in_progress", "conclusion": null, "started_at": "2026-11-17T10:03:00Z", + "details_url": "https://github.com/acme/web/actions/runs/78/job/2", + "output": {"title": null, "summary": "Testing https://8c1d2e3f.web.edge-host.example", "text": null}}, + {"id": 13, "name": "unit tests", "head_sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", + "status": "completed", "conclusion": "success", "started_at": "2026-11-17T10:00:00Z", + "details_url": "https://github.com/acme/web/actions/runs/79/job/3", "output": {"summary": "", "text": null}} + ] +} diff --git a/services/common/src/preview_find/fixtures/comment_head.json b/services/common/src/preview_find/fixtures/comment_head.json new file mode 100644 index 000000000..7456bb4c7 --- /dev/null +++ b/services/common/src/preview_find/fixtures/comment_head.json @@ -0,0 +1,8 @@ +[ + {"id": 3, "user": {"login": "static-host[bot]", "type": "Bot"}, + "body": "### ✅ Deploy Preview for *acme-web* ready!\n\n| Name | Link |\n|:-:|------------------------|\n|🔨 Latest commit | 4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b |\n|🔍 Latest deploy log | https://app.static-host.example/sites/acme-web/deploys/65ab |\n|😎 Deploy Preview | [https://deploy-preview-12--acme-web.static-host.example](https://deploy-preview-12--acme-web.static-host.example) |", + "created_at": "2026-11-16T15:00:00Z", "updated_at": "2026-11-17T10:02:30Z"}, + {"id": 4, "user": {"login": "ci-bot[bot]", "type": "Bot"}, + "body": "\n🚀 Preview deployed to https://acme.pages.example/web/pr-preview/pr-12/\nBuilt from 4f2c9e1", + "created_at": "2026-11-16T15:00:00Z", "updated_at": "2026-11-17T10:04:00Z"} +] diff --git a/services/common/src/preview_find/fixtures/comments.json b/services/common/src/preview_find/fixtures/comments.json new file mode 100644 index 000000000..64162311c --- /dev/null +++ b/services/common/src/preview_find/fixtures/comments.json @@ -0,0 +1,10 @@ +[ + {"id": 1, "user": {"login": "someone", "type": "User"}, + "body": "Looks good, see https://pr-12.preview.example.com/old", "created_at": "2026-11-17T09:00:00Z", "updated_at": "2026-11-17T09:00:00Z"}, + {"id": 2, "user": {"login": "preview-host[bot]", "type": "Bot"}, + "body": "The latest updates on your projects.\n\n| Name | Status | Preview | Comments | Updated (UTC) |\n| :--- | :----- | :------ | :------- | :------ |\n| **admin** | ✅ Ready ([Inspect](https://console.host.example/team/admin/dpl_9)) | [Visit Preview](https://admin-git-feature-signup-form-team.host.example) | 💬 [**Add feedback**](https://host.example/feedback) | Nov 17, 2026 10:03am |\n| **web** | 🔄 Building ([Inspect](https://console.host.example/team/web/dpl_8)) | [Visit Preview](https://web-git-feature-signup-form-team.host.example) | 💬 [**Add feedback**](https://host.example/feedback) | Nov 17, 2026 10:02am |\n", + "created_at": "2026-11-16T15:00:00Z", "updated_at": "2026-11-17T10:03:30Z"}, + {"id": 3, "user": {"login": "static-host[bot]", "type": "Bot"}, + "body": "### ✅ Deploy Preview for *acme-web* ready!\n\n| Name | Link |\n|:-:|------------------------|\n|🔨 Latest commit | 0aa11bb22cc33dd44ee55ff6677889900aabbccd |\n|🔍 Latest deploy log | https://app.static-host.example/sites/acme-web/deploys/65aa |\n|😎 Deploy Preview | [https://deploy-preview-12--acme-web.static-host.example](https://deploy-preview-12--acme-web.static-host.example) |", + "created_at": "2026-11-16T15:00:00Z", "updated_at": "2026-11-16T15:05:00Z"} +] diff --git a/services/common/src/preview_find/fixtures/deployments.json b/services/common/src/preview_find/fixtures/deployments.json new file mode 100644 index 000000000..3429a4b69 --- /dev/null +++ b/services/common/src/preview_find/fixtures/deployments.json @@ -0,0 +1,55 @@ +[ + { + "deployment": { + "id": 9001, "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", "ref": "feature/signup-form", + "task": "deploy", "environment": "Preview – web", "original_environment": "Preview – web", + "transient_environment": false, "production_environment": false, "payload": {}, + "created_at": "2026-11-17T10:00:05Z" + }, + "statuses": [ + {"id": 3, "state": "success", "environment": "Preview – web", + "environment_url": "https://web-git-feature-signup-form-team.host.example", + "target_url": "https://console.host.example/team/web/dpl_abc", "log_url": "https://console.host.example/team/web/dpl_abc", + "created_at": "2026-11-17T10:02:40Z"}, + {"id": 2, "state": "in_progress", "environment": "Preview – web", "environment_url": "", "target_url": "https://console.host.example/team/web/dpl_abc", + "log_url": "https://console.host.example/team/web/dpl_abc", "created_at": "2026-11-17T10:00:20Z"}, + {"id": 1, "state": "pending", "environment": "Preview – web", "environment_url": "", "target_url": "", "log_url": "", + "created_at": "2026-11-17T10:00:06Z"} + ] + }, + { + "deployment": { + "id": 9002, "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", "ref": "feature/signup-form", + "task": "deploy", "environment": "Preview – admin", + "transient_environment": false, "production_environment": false, "payload": {}, + "created_at": "2026-11-17T10:00:05Z" + }, + "statuses": [ + {"id": 5, "state": "success", "environment_url": "https://admin-git-feature-signup-form-team.host.example", + "target_url": "", "log_url": "", "created_at": "2026-11-17T10:03:10Z"} + ] + }, + { + "deployment": { + "id": 8000, "sha": "0aa11bb22cc33dd44ee55ff6677889900aabbccd", "ref": "feature/signup-form", + "task": "deploy", "environment": "Preview – web", + "transient_environment": false, "production_environment": false, "payload": {}, + "created_at": "2026-11-17T09:00:00Z" + }, + "statuses": [ + {"id": 0, "state": "inactive", "environment_url": "https://web-old-commit-team.host.example", + "created_at": "2026-11-17T10:02:41Z"} + ] + }, + { + "deployment": { + "id": 7000, "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", "ref": "main", + "task": "deploy", "environment": "Production", + "transient_environment": false, "production_environment": true, "payload": {}, + "created_at": "2026-11-17T10:00:05Z" + }, + "statuses": [ + {"id": 9, "state": "success", "environment_url": "https://www.your-domain.example", "created_at": "2026-11-17T10:04:00Z"} + ] + } +] diff --git a/services/common/src/preview_find/fixtures/statuses.json b/services/common/src/preview_find/fixtures/statuses.json new file mode 100644 index 000000000..f28835394 --- /dev/null +++ b/services/common/src/preview_find/fixtures/statuses.json @@ -0,0 +1,12 @@ +{ + "state": "success", + "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", + "statuses": [ + {"context": "site/deploy-preview", "state": "success", "description": "Deploy Preview ready!", + "target_url": "https://deploy-preview-12--acme-web.static-host.example", "created_at": "2026-11-17T10:02:00Z"}, + {"context": "site/header-rules", "state": "success", "description": "No header rules processed", + "target_url": "https://app.static-host.example/sites/acme-web/deploys/65aa", "created_at": "2026-11-17T10:02:00Z"}, + {"context": "ci/build", "state": "success", "description": "Your tests passed", + "target_url": "https://ci.example.org/gh/acme/web/4411", "created_at": "2026-11-17T10:05:00Z"} + ] +} diff --git a/services/common/src/preview_find/fixtures/workflow_environment.json b/services/common/src/preview_find/fixtures/workflow_environment.json new file mode 100644 index 000000000..9e33de184 --- /dev/null +++ b/services/common/src/preview_find/fixtures/workflow_environment.json @@ -0,0 +1,13 @@ +[ + { + "deployment": { + "id": 501, "sha": "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b", "ref": "refs/pull/12/merge", + "task": "deploy", "environment": "pr-12", "transient_environment": true, "production_environment": false + }, + "statuses": [ + {"id": 2, "state": "in_progress", "environment_url": "", "log_url": "https://github.com/acme/web/actions/runs/77/job/1", + "target_url": "https://github.com/acme/web/actions/runs/77/job/1", "created_at": "2026-11-17T10:01:00Z"}, + {"id": 1, "state": "queued", "created_at": "2026-11-17T10:00:30Z"} + ] + } +] diff --git a/services/common/src/preview_find/mod.rs b/services/common/src/preview_find/mod.rs new file mode 100644 index 000000000..bb22d60af --- /dev/null +++ b/services/common/src/preview_find/mod.rs @@ -0,0 +1,992 @@ +//! Where a pull request's preview lives, read from every place teams +//! publish it, tied to the head commit. +//! +//! A preview's address reaches a pull request in one of a handful of ways, +//! and a team uses whichever its host or its CI gives it: +//! +//! - a deployment on the head commit, its newest status carrying the +//! address (`environment_url`, else a `target_url` that isn't a log page); +//! hosting integrations and a workflow job's `environment: {name, url}` +//! both write these ([`deployments`]); +//! - a commit status whose context or description reads as a deploy, its +//! `target_url` the preview ([`statuses`]); +//! - a check run whose name or output reads as a preview deploy, the address +//! in its output or its details link ([`check_runs`]); +//! - a bot's comment on the pull request, usually edited in place on every +//! push, often a table with one row per app ([`comments`]); +//! - a link in the pull request's description ([`body`]); +//! - the team's own address template, filled in from the pull request's +//! number, branch and commit ([`expand`]). +//! +//! Each is read into [`Sighting`]s, and [`resolve`] gives the one answer: +//! +//! 1. Only what is tied to the head commit counts first: a deployment, +//! status or check run on that sha, a comment that names that sha (or, +//! naming none, was written after the commit). A deploy of an older +//! commit is never the preview of this one. +//! 2. When several apps publish previews (a monorepo), the one named after +//! the changed app is kept ([`app_score`]). +//! 3. Of what is up with an address, the most direct source wins +//! ([`Source`] order). A head deploy still building means wait; one that +//! failed or was taken down is said as such. +//! 4. Only when nothing on the head carries an address does an untied one +//! count: the description's link or the team's template. +//! +//! How long to wait is bounded ([`WAIT_BUDGET_MINS`]); nothing here reads +//! the clock, the caller passes the times. + +use serde::{Deserialize, Serialize}; + +/// How long a preview of one head is waited on before the wait is said to +/// have run out. +pub const WAIT_BUDGET_MINS: i64 = 60; +/// How long nothing at all on the head (no deployment, status, check, +/// comment or template) is waited on before there is said to be no preview: +/// hosting integrations start within a minute or two of a push. +pub const GRACE_MINS: i64 = 6; +/// How often a pending preview is looked at again when nothing else on the +/// pull request changed. +pub const POLL_SECS: i64 = 120; + +/// Where an address came from, most direct first: the order breaks ties +/// between two sightings that both say the head's preview is up. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Source { + #[default] + Deployment, + CheckRun, + CommitStatus, + Comment, + Body, + Template, +} + +impl Source { + /// How the source is named in a sentence. + pub fn phrase(self) -> &'static str { + match self { + Source::Deployment => "the head commit's deployment", + Source::CheckRun => "the preview check on the head commit", + Source::CommitStatus => "the deploy status on the head commit", + Source::Comment => "the preview comment on the pull request", + Source::Body => "the link in the pull request's description", + Source::Template => "the team's preview address template", + } + } +} + +/// What a sighting says of the preview. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Ready { + Up, + Building, + Failed, + /// Taken down, expired or replaced. + Gone, +} + +/// One place that says something about the head's preview. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sighting { + pub source: Source, + /// The environment, context, check or table row it names (an app in a + /// monorepo), "" when none. + pub name: String, + /// The address, "" when it says only how the deploy stands. + pub url: String, + pub ready: Ready, + /// Tied to the head commit. + pub tied: bool, +} + +/// The preview the change is checked on. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Found { + pub url: String, + pub source: Source, + /// The environment, check or app it was named under. + pub name: String, + /// Tied to the head commit (false: a description link or the template). + pub tied: bool, +} + +/// The answer [`resolve`] gives. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Answer { + Up(Found), + /// The head's preview is still on its way: what says so. + Building(String), + /// The head's preview failed or was taken down: what says so. + Failed(String), + Nothing, +} + +// ── words ───────────────────────────────────────────────────────────────── + +fn words(s: &str) -> Vec { + s.to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| !w.is_empty()) + .map(str::to_string) + .collect() +} + +fn norm(s: &str) -> String { + s.chars() + .filter(|c| c.is_ascii_alphanumeric()) + .flat_map(|c| c.to_lowercase()) + .collect() +} + +/// Whether a check, status or environment name (with its description) +/// reads as a deploy of the pull request's own preview: it says preview, +/// deploy or review app, and never a shared environment or a cleanup. +pub fn reads_as_preview(name: &str, text: &str) -> bool { + use crate::preview::{role_of, Role}; + if matches!( + role_of(name), + Role::Production | Role::Staging | Role::Cleanup | Role::E2e + ) { + return false; + } + let both = format!("{name} {text}"); + let w = words(&both); + let low = both.to_ascii_lowercase(); + w.iter().any(|x| { + matches!( + x.as_str(), + "preview" | "previews" | "deploy" | "deployment" | "deployed" | "deploying" + ) + }) || low.contains("review app") + || low.contains("review-app") +} + +fn host_of(url: &str) -> &str { + let rest = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://")) + .unwrap_or(""); + rest.split(['/', '?', '#']).next().unwrap_or("") +} + +fn path_of(url: &str) -> &str { + let rest = url + .strip_prefix("https://") + .or_else(|| url.strip_prefix("http://")) + .unwrap_or(""); + match rest.find('/') { + Some(i) => rest[i..].split(['?', '#']).next().unwrap_or(""), + None => "", + } +} + +/// An address on the code host itself (a pull request, a run, a file), never +/// a preview. +pub fn is_code_host(url: &str) -> bool { + let h = host_of(url).to_ascii_lowercase(); + h == "github.com" || h.ends_with(".github.com") || h.ends_with(".githubusercontent.com") +} + +/// An address that is a log, dashboard or build page rather than the site: +/// its host starts with a console's name, or its path is a deploy, build or +/// run record. +pub fn is_console(url: &str) -> bool { + let h = host_of(url).to_ascii_lowercase(); + let first = h.split('.').next().unwrap_or(""); + if matches!( + first, + "app" | "dashboard" | "console" | "admin" | "ci" | "build" | "builds" | "logs" | "status" + ) && h.matches('.').count() >= 2 + { + return true; + } + path_of(url).to_ascii_lowercase().split('/').any(|seg| { + matches!( + seg, + "deploys" + | "deployments" + | "builds" + | "runs" + | "jobs" + | "pipelines" + | "logs" + | "inspect" + | "actions" + ) + }) +} + +fn is_image(url: &str) -> bool { + let p = path_of(url).to_ascii_lowercase(); + let h = host_of(url).to_ascii_lowercase(); + [".png", ".svg", ".gif", ".jpg", ".jpeg", ".webp", ".ico"] + .iter() + .any(|e| p.ends_with(e)) + || h.contains("badge") + || p.contains("/badge") +} + +/// An address that can be a site: https, a host with a dot, never the code +/// host, a console page or an image. +pub fn site_like(url: &str) -> bool { + let h = host_of(url); + url.starts_with("https://") + && h.contains('.') + && !h.contains('@') + && !is_code_host(url) + && !is_console(url) + && !is_image(url) +} + +/// Every https address in a text with the words around it: a markdown link's +/// text, else the line it sits on. +pub fn urls_in(text: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + for line in text.lines() { + for (i, _) in line.match_indices("https://") { + let rest = &line[i..]; + let end = rest + .find(|c: char| { + c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>' | '<' | ']' | '`' | '|') + }) + .unwrap_or(rest.len()); + let url = rest[..end].trim_end_matches(['.', ',', ';', ':']); + // `[text](url)`: the text says what it is. + let label = line[..i] + .strip_suffix("](") + .and_then(|before| before.rfind('[').map(|j| before[j + 1..].to_string())) + .unwrap_or_else(|| line.to_string()); + if !url.is_empty() && !out.iter().any(|(u, _): &(String, String)| u == url) { + out.push((url.to_string(), label)); + } + } + } + out +} + +/// Words that say an address is the preview. +fn labelled_preview(label: &str, url: &str) -> bool { + let w = words(label); + let says = w.iter().any(|x| { + matches!( + x.as_str(), + "preview" | "previews" | "visit" | "open" | "deployment" | "deployed" | "live" | "url" + ) + }); + let h = host_of(url).to_ascii_lowercase(); + says || h.contains("preview") + || h.split(['.', '-']).any(|p| { + p.strip_prefix("pr") + .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())) + }) + || h.split('.').next().is_some_and(|l| l.contains("-pr-")) +} + +/// The preview address in a text. `named`: the text is a preview check's or +/// deploy status's own, so a site address counts even unlabelled; else it +/// must be labelled or shaped as a preview. +pub fn pick_url(text: &str, named: bool) -> Option { + let all: Vec<(String, String)> = urls_in(text) + .into_iter() + .filter(|(u, _)| site_like(u)) + .collect(); + all.iter() + .find(|(u, l)| labelled_preview(l, u)) + .or_else(|| if named { all.first() } else { None }) + .map(|(u, _)| u.clone()) +} + +// ── readers: each place a preview is published ───────────────────────────── + +fn s<'a>(v: &'a serde_json::Value, k: &str) -> &'a str { + v[k].as_str().unwrap_or("") +} + +fn same_sha(a: &str, head: &str) -> bool { + !a.is_empty() && !head.is_empty() && a.eq_ignore_ascii_case(head) +} + +/// The head's deployments, each with its statuses (as the deployments and +/// deployment statuses listings return them). A deployment to production +/// or to a shared environment is never a pull request's preview, unless it +/// says it is transient. +pub fn deployments( + list: &[(serde_json::Value, Vec)], + head: &str, +) -> Vec { + use crate::preview::{is_shared_env_label, role_of, Role}; + let mut out = Vec::new(); + for (d, statuses) in list { + if !same_sha(s(d, "sha"), head) { + continue; + } + let env = match s(d, "environment") { + "" => s(d, "original_environment"), + e => e, + }; + let transient = d["transient_environment"].as_bool().unwrap_or(false); + let shared = d["production_environment"].as_bool().unwrap_or(false) + || ((is_shared_env_label(env) + || matches!(role_of(env), Role::Production | Role::Staging)) + && !env.to_ascii_lowercase().contains("preview")); + if shared && !transient { + continue; + } + // The newest status says where it stands. + let mut sts: Vec<&serde_json::Value> = statuses.iter().collect(); + sts.sort_by(|a, b| { + s(b, "created_at") + .cmp(s(a, "created_at")) + .then(b["id"].as_u64().cmp(&a["id"].as_u64())) + }); + let newest = sts.first(); + let ready = match newest.map(|st| s(st, "state")) { + Some("success") => Ready::Up, + Some("failure" | "error") => Ready::Failed, + Some("inactive") => Ready::Gone, + // Created, queued, pending or in progress. + _ => Ready::Building, + }; + let url = newest + .map(|st| { + let env_url = s(st, "environment_url"); + let target = s(st, "target_url"); + let log = s(st, "log_url"); + if site_like(env_url) { + env_url.to_string() + } else if site_like(target) && target != log { + target.to_string() + } else { + String::new() + } + }) + .unwrap_or_default(); + out.push(Sighting { + source: Source::Deployment, + name: env.to_string(), + url, + ready, + tied: true, + }); + } + out +} + +/// The head's combined commit status: each context that reads as a deploy. +pub fn statuses(combined: &serde_json::Value, head: &str) -> Vec { + let sha = s(combined, "sha"); + if !sha.is_empty() && !same_sha(sha, head) { + return Vec::new(); + } + let mut out = Vec::new(); + for st in combined["statuses"].as_array().into_iter().flatten() { + let (ctx, desc) = (s(st, "context"), s(st, "description")); + if !reads_as_preview(ctx, desc) { + continue; + } + let ready = match s(st, "state") { + "success" => Ready::Up, + "failure" | "error" => Ready::Failed, + _ => Ready::Building, + }; + let target = s(st, "target_url"); + out.push(Sighting { + source: Source::CommitStatus, + name: ctx.to_string(), + url: if site_like(target) { + target.to_string() + } else { + String::new() + }, + ready, + tied: true, + }); + } + out +} + +/// The head's check runs (the check-runs listing): each that reads as a +/// preview deploy, its newest run per name. `covers` are the preview jobs +/// the repository's workflows run for the change (`preview::plan`). +pub fn check_runs( + runs: &serde_json::Value, + head: &str, + covers: &[crate::preview::Covering], +) -> Vec { + use crate::preview::{is_covering, role_of, Role}; + let mut newest: Vec<(&str, &serde_json::Value)> = Vec::new(); + for r in runs["check_runs"].as_array().into_iter().flatten() { + let sha = s(r, "head_sha"); + if !sha.is_empty() && !same_sha(sha, head) { + continue; + } + let name = s(r, "name"); + let out_text = format!( + "{} {}", + s(&r["output"], "title"), + s(&r["output"], "summary") + ); + let preview_job = covers + .iter() + .filter(|c| c.role == Some(Role::Preview)) + .any(|c| is_covering(std::slice::from_ref(c), name)); + if role_of(name) == Role::E2e || !(preview_job || reads_as_preview(name, &out_text)) { + continue; + } + if s(r, "conclusion") == "skipped" || s(r, "conclusion") == "neutral" { + continue; + } + match newest.iter_mut().find(|(n, _)| *n == name) { + Some(slot) if s(r, "started_at") > s(slot.1, "started_at") => slot.1 = r, + Some(_) => {} + None => newest.push((name, r)), + } + } + newest + .into_iter() + .map(|(name, r)| { + let ready = match (s(r, "status"), s(r, "conclusion")) { + ("completed", "success") => Ready::Up, + ("completed", _) => Ready::Failed, + _ => Ready::Building, + }; + let text = format!( + "{}\n{}\n{}", + s(&r["output"], "summary"), + s(&r["output"], "text"), + s(&r["output"], "title") + ); + let details = s(r, "details_url"); + let url = pick_url(&text, true) + .or_else(|| site_like(details).then(|| details.to_string())) + .unwrap_or_default(); + Sighting { + source: Source::CheckRun, + name: name.to_string(), + url, + ready, + tied: true, + } + }) + .collect() +} + +fn hexish(w: &str) -> bool { + // A commit's sha mixes digits and letters; a build number or a date + // is digits only. + (7..=40).contains(&w.len()) + && w.chars().all(|c| c.is_ascii_hexdigit()) + && w.chars().any(|c| c.is_ascii_digit()) + && w.chars().any(|c| c.is_ascii_alphabetic()) +} + +/// Whether a text names the head commit (its full sha or a prefix of seven +/// or more), names another commit, or names none. +fn names_commit(text: &str, head: &str) -> Option { + let head = head.to_ascii_lowercase(); + let mut other = false; + for w in text + .to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|w| hexish(w)) + { + if head.starts_with(w) { + return Some(true); + } + other = true; + } + other.then_some(false) +} + +/// The state a line or a comment says: failed, building, gone or up. +fn says(text: &str) -> Option { + let low = text.to_ascii_lowercase(); + let w = words(text); + let has = |xs: &[&str]| w.iter().any(|x| xs.contains(&x.as_str())); + if has(&[ + "failed", + "failure", + "error", + "errored", + "canceled", + "cancelled", + ]) || low.contains('❌') + { + return Some(Ready::Failed); + } + if has(&[ + "building", + "queued", + "pending", + "deploying", + "initializing", + "waiting", + ]) || low.contains("in progress") + || low.contains('⏳') + || low.contains('🔄') + { + return Some(Ready::Building); + } + if has(&["deleted", "removed", "expired", "inactive", "destroyed"]) || low.contains("torn down") + { + return Some(Ready::Gone); + } + if has(&[ + "ready", + "deployed", + "success", + "succeeded", + "live", + "available", + ]) || low.contains('✅') + { + return Some(Ready::Up); + } + None +} + +/// A table row's first cell, or "". +fn row_name(line: &str) -> String { + let t = line.trim(); + if !t.starts_with('|') { + return String::new(); + } + let cell = t.trim_matches('|').split('|').next().unwrap_or(""); + let clean: String = cell + .chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_' | '/' | '.')) + .collect(); + let clean = clean.trim(); + // A header row's or a label cell's words aren't an app. + if words(clean).iter().all(|w| { + matches!( + w.as_str(), + "name" + | "project" + | "app" + | "status" + | "preview" + | "deploy" + | "latest" + | "commit" + | "log" + | "updated" + | "url" + | "inspect" + | "visit" + ) + }) { + return String::new(); + } + clean.to_string() +} + +/// The bot comments on the pull request (the issue comments listing, oldest +/// first). A comment is tied to the head when it names the head commit, or +/// names none and was written or edited at or after `head_at` (the head +/// commit's time); one that names only another commit is an older deploy's. +/// Each line with a preview address is one sighting: a monorepo's table +/// gives one per app. +pub fn comments(list: &[serde_json::Value], head: &str, head_at: &str) -> Vec { + let mut bots: Vec<&serde_json::Value> = list + .iter() + .filter(|c| { + c["user"]["type"].as_str() == Some("Bot") + || c["user"]["login"] + .as_str() + .is_some_and(|l| l.ends_with("[bot]")) + }) + .collect(); + // The newest word first. + bots.sort_by(|a, b| { + let at = |c: &serde_json::Value| match s(c, "updated_at") { + "" => s(c, "created_at").to_string(), + u => u.to_string(), + }; + at(b).cmp(&at(a)) + }); + let mut out = Vec::new(); + for c in bots { + let body = s(c, "body"); + if !body.contains("https://") { + continue; + } + let updated = match s(c, "updated_at") { + "" => s(c, "created_at"), + u => u, + }; + let tied = match names_commit(body, head) { + Some(t) => t, + None => !head_at.is_empty() && updated >= head_at, + }; + let names_other = names_commit(body, head) == Some(false); + if names_other { + // An older commit's deploy: never this head's. + continue; + } + let whole = says(body); + for line in body.lines() { + let Some(url) = pick_url(line, false) else { + continue; + }; + out.push(Sighting { + source: Source::Comment, + name: row_name(line), + url, + ready: says(line).or(whole).unwrap_or(Ready::Up), + tied, + }); + } + } + out +} + +/// A preview link in the pull request's description: tied only when the +/// description names the head commit. +pub fn body(text: &str, head: &str) -> Vec { + let tied = names_commit(text, head) == Some(true); + text.lines() + .filter_map(|line| { + let url = pick_url(line, false)?; + Some(Sighting { + source: Source::Body, + name: row_name(line), + url, + ready: Ready::Up, + tied, + }) + }) + .collect() +} + +// ── the team's template ─────────────────────────────────────────────────── + +/// What an address template may name. +pub const PLACEHOLDERS: &[&str] = &[ + "{pr}", + "{branch}", + "{branch_slug}", + "{sha}", + "{short_sha}", + "{owner}", + "{repo}", +]; + +/// The pull request a template is filled in for. +#[derive(Debug, Clone, Copy, Default)] +pub struct Vars<'a> { + pub pr: u64, + pub branch: &'a str, + pub sha: &'a str, + pub owner: &'a str, + pub repo: &'a str, +} + +/// A branch name as hosts put it in an address: lowercase, every run of +/// other characters one `-`, no `-` at either end. +pub fn branch_slug(branch: &str) -> String { + let mut out = String::new(); + for c in branch.chars() { + if c.is_ascii_alphanumeric() { + out.push(c.to_ascii_lowercase()); + } else if !out.ends_with('-') { + out.push('-'); + } + } + out.trim_matches('-').to_string() +} + +fn braces(s: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut rest = s; + while let Some(i) = rest.find('{') { + match rest[i..].find('}') { + Some(j) => { + out.push(&rest[i..i + j + 1]); + rest = &rest[i + j + 1..]; + } + None => { + out.push(&rest[i..]); + break; + } + } + } + out +} + +/// Checks an address template as a team typed it; the error is one sentence +/// a person can act on. Empty is no template. +pub fn check_template(raw: &str) -> Result<(), String> { + let t = raw.trim(); + if t.is_empty() { + return Ok(()); + } + let rest = t + .strip_prefix("https://") + .ok_or("The preview address starts with https://.")?; + let host = rest.split(['/', '?', '#']).next().unwrap_or(""); + if host.is_empty() + || t.len() > 300 + || t.chars().any(|c| { + c.is_whitespace() || c.is_control() || matches!(c, '\'' | '"' | '`' | '\\' | '$' | ';') + }) + { + return Err( + "Enter the preview's address, like https://pr-{pr}.preview.your-domain.example.".into(), + ); + } + for b in braces(t) { + if !PLACEHOLDERS.contains(&b) { + return Err(format!( + "`{b}` isn't filled in; use {}.", + PLACEHOLDERS.join(", ") + )); + } + } + if !is_per_change(t) { + return Err( + "The address needs {pr}, {branch}, {branch_slug}, {sha} or {short_sha}, so each pull request gets its own preview." + .into(), + ); + } + Ok(()) +} + +/// Whether a template names something of the pull request, so it is that +/// pull request's own address (a fixed address is a shared environment). +pub fn is_per_change(t: &str) -> bool { + ["{pr}", "{branch}", "{branch_slug}", "{sha}", "{short_sha}"] + .iter() + .any(|p| t.contains(p)) +} + +/// A template filled in for a pull request. A host label longer than DNS +/// allows (63 characters) is cut to fit, as hosts cut a long branch's slug. +/// None when the template isn't valid or names a value the pull request +/// doesn't have. +pub fn expand(template: &str, v: Vars) -> Option { + let t = template.trim(); + check_template(t).ok()?; + if t.is_empty() { + return None; + } + let need = |p: &str, have: bool| !t.contains(p) || have; + if !(need("{pr}", v.pr > 0) + && need("{branch}", !v.branch.is_empty()) + && need("{branch_slug}", !v.branch.is_empty()) + && need("{sha}", !v.sha.is_empty()) + && need("{short_sha}", !v.sha.is_empty())) + { + return None; + } + let rest = &t["https://".len()..]; + let cut = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let (host_t, tail_t) = rest.split_at(cut); + let fill = |s: &str, host: bool| { + let branch = if host { + branch_slug(v.branch) + } else { + v.branch.to_string() + }; + s.replace("{pr}", &v.pr.to_string()) + .replace("{branch_slug}", &branch_slug(v.branch)) + .replace("{branch}", &branch) + .replace("{short_sha}", v.sha.get(..7).unwrap_or(v.sha)) + .replace("{sha}", v.sha) + .replace("{owner}", &branch_slug(v.owner)) + .replace("{repo}", &branch_slug(v.repo)) + }; + let host: Vec = fill(host_t, true) + .split('.') + .map(|l| { + if l.len() > 63 { + l[..63].trim_end_matches('-').to_string() + } else { + l.to_string() + } + }) + .collect(); + Some(format!("https://{}{}", host.join("."), fill(tail_t, false))) +} + +// ── which app, and the answer ───────────────────────────────────────────── + +/// Folders a monorepo keeps its apps under. +const APP_HOMES: &[&str] = &[ + "apps", + "packages", + "services", + "sites", + "projects", + "frontends", + "web", + "clients", +]; + +/// The app a changed path belongs to: the folder under a monorepo's apps +/// folder, else the path's first folder. +pub fn app_of(path: &str) -> Option { + let segs: Vec<&str> = path.split('/').collect(); + if segs.len() < 2 { + return None; + } + if APP_HOMES.contains(&segs[0]) && segs.len() >= 3 { + return Some(segs[1].to_string()); + } + Some(segs[0].to_string()) +} + +/// The apps a repository's tree has: each folder under a monorepo's apps +/// folder. +pub fn apps_of(tree: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for p in tree { + let segs: Vec<&str> = p.split('/').collect(); + if segs.len() >= 3 && APP_HOMES.contains(&segs[0]) { + let a = segs[1].to_string(); + if !out.contains(&a) { + out.push(a); + } + } + } + out +} + +fn names(name: &str, app: &str) -> bool { + let (n, a) = (norm(name), norm(app)); + a.len() >= 3 && n.contains(&a) +} + +/// How well a preview's name fits the change: it names a changed app (2), +/// names nothing known (0), names an app the change doesn't touch or reads +/// as a backend with no pages (-1). +pub fn app_score(name: &str, changed: &[String], apps: &[String]) -> i32 { + let changed_apps: Vec = changed.iter().filter_map(|p| app_of(p)).collect(); + if changed_apps.iter().any(|a| { + names(name, a) && (apps.is_empty() || apps.contains(a) || !APP_HOMES.contains(&a.as_str())) + }) { + return 2; + } + if apps + .iter() + .any(|a| names(name, a) && !changed_apps.contains(a)) + { + return -1; + } + let w = words(name); + if w.iter().any(|x| { + matches!( + x.as_str(), + "api" | "backend" | "server" | "graphql" | "worker" | "storybook" + ) + }) { + return -1; + } + 0 +} + +fn describe(s: &Sighting) -> String { + if s.name.is_empty() { + s.source.phrase().to_string() + } else { + format!("{} `{}`", s.source.phrase(), s.name) + } +} + +/// The one answer from every sighting: see the module's rules. +pub fn resolve(all: &[Sighting], changed: &[String], apps: &[String]) -> Answer { + fn pick<'a>( + group: Vec<&'a Sighting>, + changed: &[String], + apps: &[String], + ) -> Vec<&'a Sighting> { + let named: Vec = group + .iter() + .map(|s| { + if s.name.is_empty() { + 0 + } else { + app_score(&s.name, changed, apps) + } + }) + .collect(); + let best = named.iter().copied().max().unwrap_or(0); + group + .into_iter() + .zip(named) + .filter(|(_, sc)| *sc == best) + .map(|(s, _)| s) + .collect() + } + let up_with_url = |g: &[&Sighting]| -> Option { + g.iter() + .filter(|s| s.ready == Ready::Up && !s.url.is_empty()) + .min_by_key(|s| s.source) + .map(|s| Found { + url: s.url.clone(), + source: s.source, + name: s.name.clone(), + tied: s.tied, + }) + }; + let tied = pick(all.iter().filter(|s| s.tied).collect(), changed, apps); + if let Some(f) = up_with_url(&tied) { + return Answer::Up(f); + } + if let Some(b) = tied + .iter() + .filter(|s| s.ready == Ready::Building) + .min_by_key(|s| s.source) + { + return Answer::Building(describe(b)); + } + let up_without_url = tied.iter().any(|s| s.ready == Ready::Up); + if !up_without_url { + if let Some(f) = tied + .iter() + .filter(|s| matches!(s.ready, Ready::Failed | Ready::Gone)) + .min_by_key(|s| s.source) + { + let how = if f.ready == Ready::Failed { + "failed" + } else { + "was taken down" + }; + return Answer::Failed(format!("{} {how}", describe(f))); + } + } + let untied = pick(all.iter().filter(|s| !s.tied).collect(), changed, apps); + match up_with_url(&untied) { + Some(f) => Answer::Up(f), + None => Answer::Nothing, + } +} + +/// Minutes from `since` to `now` (RFC 3339), 0 when either can't be read. +pub fn minutes_between(since: &str, now: &str) -> i64 { + match ( + chrono::DateTime::parse_from_rfc3339(since), + chrono::DateTime::parse_from_rfc3339(now), + ) { + (Ok(a), Ok(b)) => (b - a).num_minutes().max(0), + _ => 0, + } +} + +/// Seconds from `since` to `now` (RFC 3339); a large number when `since` +/// can't be read, so a look is due. +pub fn seconds_between(since: &str, now: &str) -> i64 { + match ( + chrono::DateTime::parse_from_rfc3339(since), + chrono::DateTime::parse_from_rfc3339(now), + ) { + (Ok(a), Ok(b)) => (b - a).num_seconds(), + _ => i64::MAX, + } +} + +#[cfg(test)] +mod tests; diff --git a/services/common/src/preview_find/tests.rs b/services/common/src/preview_find/tests.rs new file mode 100644 index 000000000..cc7e4f966 --- /dev/null +++ b/services/common/src/preview_find/tests.rs @@ -0,0 +1,356 @@ +//! Replays of each route a preview's address is published on, with payloads +//! shaped like the code host's own listings and like real preview bots' +//! comments (names and hosts made up). + +use super::*; + +const HEAD: &str = "4f2c9e1ab7d3c5e8f0a1b2c3d4e5f60718293a4b"; +/// The head commit's time: a comment edited after it speaks of it. +const HEAD_AT: &str = "2026-11-17T10:00:00Z"; + +fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() +} + +fn fixture(text: &str) -> serde_json::Value { + serde_json::from_str(text).expect("fixture is JSON") +} + +fn deployment_list(text: &str) -> Vec<(serde_json::Value, Vec)> { + fixture(text) + .as_array() + .unwrap() + .iter() + .map(|d| { + ( + d["deployment"].clone(), + d["statuses"].as_array().cloned().unwrap_or_default(), + ) + }) + .collect() +} + +fn changed_web() -> Vec { + s(&["apps/web/src/app/signup/page.tsx"]) +} + +fn apps() -> Vec { + s(&["web", "admin"]) +} + +#[test] +fn a_hosts_deployments_give_the_changed_apps_preview_of_the_head() { + let d = deployment_list(include_str!("fixtures/deployments.json")); + let seen = deployments(&d, HEAD); + // The older commit's deploy and the production deploy are never this + // head's preview. + assert_eq!(seen.len(), 2, "{seen:?}"); + assert!(seen.iter().all(|x| x.tied && x.ready == Ready::Up)); + // The newest status says where it stands, and its environment address + // is the site (the target is a console page). + let web = seen.iter().find(|x| x.name.contains("web")).unwrap(); + assert_eq!( + web.url, + "https://web-git-feature-signup-form-team.host.example" + ); + // A monorepo: the app the change touches, never another app's. + assert_eq!( + resolve(&seen, &changed_web(), &apps()), + Answer::Up(Found { + url: "https://web-git-feature-signup-form-team.host.example".into(), + source: Source::Deployment, + name: "Preview – web".into(), + tied: true, + }) + ); + let admin_change = s(&["apps/admin/src/pages/users.tsx"]); + match resolve(&seen, &admin_change, &apps()) { + Answer::Up(f) => assert!(f.url.starts_with("https://admin-"), "{f:?}"), + a => panic!("{a:?}"), + } +} + +#[test] +fn a_workflow_jobs_environment_still_building_is_waited_on() { + let d = deployment_list(include_str!("fixtures/workflow_environment.json")); + let seen = deployments(&d, HEAD); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].ready, Ready::Building); + // Its log link is a run on the code host, never the preview. + assert_eq!(seen[0].url, ""); + assert!(matches!( + resolve(&seen, &changed_web(), &apps()), + Answer::Building(w) if w.contains("pr-12") + )); +} + +#[test] +fn a_deploy_that_failed_or_was_taken_down_is_said_never_waited_on() { + let mk = |state: &str| { + vec![( + serde_json::json!({"sha": HEAD, "environment": "preview/feature-x", "transient_environment": true}), + vec![ + serde_json::json!({"id": 1, "state": state, "created_at": "2026-11-17T10:01:00Z"}), + ], + )] + }; + for (state, word) in [ + ("failure", "failed"), + ("error", "failed"), + ("inactive", "taken down"), + ] { + let seen = deployments(&mk(state), HEAD); + match resolve(&seen, &changed_web(), &[]) { + Answer::Failed(w) => assert!(w.contains(word), "{w}"), + a => panic!("{state}: {a:?}"), + } + } +} + +#[test] +fn a_deploy_status_on_the_head_gives_the_preview_and_never_a_ci_log() { + let seen = statuses(&fixture(include_str!("fixtures/statuses.json")), HEAD); + // The CI build's status and the host's rule-check status don't read as a + // deploy of the preview. + assert_eq!(seen.len(), 1, "{seen:?}"); + assert_eq!( + seen[0].url, + "https://deploy-preview-12--acme-web.static-host.example" + ); + assert!(matches!( + resolve(&seen, &changed_web(), &[]), + Answer::Up(f) if f.source == Source::CommitStatus + )); + // Another commit's combined status says nothing of this head. + assert!(statuses( + &fixture(include_str!("fixtures/statuses.json")), + "0aa11bb22cc" + ) + .is_empty()); +} + +#[test] +fn a_preview_check_runs_output_carries_the_address() { + let seen = check_runs( + &fixture(include_str!("fixtures/check_runs.json")), + HEAD, + &[], + ); + // The end-to-end check and the unit tests aren't the deploy. + assert_eq!(seen.len(), 1, "{seen:?}"); + assert_eq!(seen[0].url, "https://8c1d2e3f.web.edge-host.example"); + assert_eq!(seen[0].ready, Ready::Up); +} + +#[test] +fn a_preview_job_named_by_the_workflows_counts_even_when_its_name_doesnt_say_preview() { + let runs = serde_json::json!({"check_runs": [ + {"name": "Ship web", "head_sha": HEAD, "status": "completed", "conclusion": "success", + "output": {"summary": "Live at https://web-12.review.your-domain.example", "text": null}} + ]}); + assert!(check_runs(&runs, HEAD, &[]).is_empty()); + let covers = vec![crate::preview::Covering { + check: "Ship web".into(), + role: Some(crate::preview::Role::Preview), + workflow: ".github/workflows/preview.yml".into(), + }]; + let seen = check_runs(&runs, HEAD, &covers); + assert_eq!(seen[0].url, "https://web-12.review.your-domain.example"); +} + +#[test] +fn a_bot_comment_edited_in_place_is_read_row_by_row_and_an_older_commits_is_not() { + let list = fixture(include_str!("fixtures/comments.json")); + let seen = comments(list.as_array().unwrap(), HEAD, HEAD_AT); + // A person's comment and the comment that names an older commit give + // nothing; the table gives one row per app, never its console links. + assert_eq!(seen.len(), 2, "{seen:?}"); + let web = seen.iter().find(|x| x.name == "web").unwrap(); + assert_eq!(web.ready, Ready::Building); + let admin = seen.iter().find(|x| x.name == "admin").unwrap(); + assert_eq!(admin.ready, Ready::Up); + assert!(seen.iter().all(|x| x.tied && !is_console(&x.url))); + // The change is in the web app, still building: wait for it, never take + // the admin app's preview instead. + assert!(matches!( + resolve(&seen, &changed_web(), &apps()), + Answer::Building(w) if w.contains("web") + )); + // Before the head's time, an unnamed comment speaks of an older push. + let early = comments(list.as_array().unwrap(), HEAD, "2026-11-17T11:00:00Z"); + assert!(early.iter().all(|x| !x.tied)); +} + +#[test] +fn a_comment_naming_the_head_commit_gives_its_preview() { + let list = fixture(include_str!("fixtures/comment_head.json")); + let seen = comments(list.as_array().unwrap(), HEAD, HEAD_AT); + assert!( + seen.iter().all(|x| x.tied && x.ready == Ready::Up), + "{seen:?}" + ); + let urls: Vec<&str> = seen.iter().map(|x| x.url.as_str()).collect(); + assert!(urls.contains(&"https://deploy-preview-12--acme-web.static-host.example")); + assert!(urls.contains(&"https://acme.pages.example/web/pr-preview/pr-12/")); + assert!(!urls.iter().any(|u| u.contains("/deploys/"))); +} + +#[test] +fn a_description_link_counts_only_when_nothing_on_the_head_has_an_address() { + let link = body( + "## Preview\nPreview: https://pr-12.preview.your-domain.example\nDocs: https://docs.example.org/guide", + HEAD, + ); + assert_eq!(link.len(), 1); + assert!(!link[0].tied); + // A check on the head says the deploy passed but prints no address: + // the link is used. + let mut all = link.clone(); + all.push(Sighting { + source: Source::CheckRun, + name: "Deploy preview".into(), + url: String::new(), + ready: Ready::Up, + tied: true, + }); + assert!(matches!( + resolve(&all, &[], &[]), + Answer::Up(f) if f.source == Source::Body && !f.tied + )); + // The head's deploy still building: wait, the link may serve an older + // build. + all.push(Sighting { + source: Source::Deployment, + name: "pr-12".into(), + url: String::new(), + ready: Ready::Building, + tied: true, + }); + assert!(matches!(resolve(&all, &[], &[]), Answer::Building(_))); +} + +#[test] +fn the_most_direct_source_wins_between_answers_on_the_head() { + let mut all = deployments( + &deployment_list(include_str!("fixtures/deployments.json")), + HEAD, + ); + all.extend(statuses( + &fixture(include_str!("fixtures/statuses.json")), + HEAD, + )); + all.extend(body( + "Preview: https://pr-12.preview.your-domain.example", + HEAD, + )); + assert!(matches!( + resolve(&all, &changed_web(), &apps()), + Answer::Up(f) if f.source == Source::Deployment + )); + assert_eq!(resolve(&[], &changed_web(), &apps()), Answer::Nothing); +} + +#[test] +fn templates_fill_in_the_pull_request_as_hosts_name_previews() { + assert_eq!(branch_slug("Feature/Signup_Form!!"), "feature-signup-form"); + assert_eq!(branch_slug("--a//b--"), "a-b"); + let v = Vars { + pr: 12, + branch: "feature/signup-form", + sha: HEAD, + owner: "acme", + repo: "web", + }; + assert_eq!( + expand("https://pr-{pr}.preview.your-domain.example", v).as_deref(), + Some("https://pr-12.preview.your-domain.example") + ); + assert_eq!( + expand("https://{repo}-git-{branch_slug}-team.host.example", v).as_deref(), + Some("https://web-git-feature-signup-form-team.host.example") + ); + // In a path the branch keeps its slashes; in a host it is a slug. + assert_eq!( + expand("https://previews.your-domain.example/{branch}/", v).as_deref(), + Some("https://previews.your-domain.example/feature/signup-form/") + ); + assert_eq!( + expand("https://{short_sha}.web.edge-host.example", v).as_deref(), + Some("https://4f2c9e1.web.edge-host.example") + ); + // A host label longer than DNS allows is cut to 63 characters. + let long = Vars { + branch: "feature/a-very-long-branch-name-that-keeps-going-and-going-past-the-limit", + ..v + }; + let u = expand("https://{branch_slug}--site.static-host.example", long).unwrap(); + let label = u["https://".len()..].split('.').next().unwrap(); + assert!(label.len() <= 63 && !label.ends_with('-'), "{label}"); + // Nothing to fill a placeholder with: no address. + assert_eq!( + expand("https://pr-{pr}.x.example", Vars { pr: 0, ..v }), + None + ); +} + +#[test] +fn a_template_is_checked_as_the_team_types_it() { + assert!(check_template("").is_ok()); + assert!(check_template("https://pr-{pr}.preview.your-domain.example").is_ok()); + assert!(check_template("http://pr-{pr}.x.example").is_err()); + assert!(check_template("https://pr-{number}.x.example").is_err()); + // A fixed address is a shared environment, not a pull request's own. + assert!(check_template("https://staging.your-domain.example").is_err()); + assert!(check_template("https://x.example/$(id)/{pr}").is_err()); +} + +#[test] +fn addresses_are_read_from_text_with_what_labels_them() { + assert_eq!( + pick_url( + "[Visit Preview](https://web-abc.host.example) and https://docs.example.org", + false + ) + .as_deref(), + Some("https://web-abc.host.example") + ); + assert_eq!(pick_url("see https://docs.example.org/guide", false), None); + assert_eq!( + pick_url("see https://docs.example.org/guide", true).as_deref(), + Some("https://docs.example.org/guide") + ); + assert!(is_console( + "https://app.static-host.example/sites/x/deploys/1" + )); + assert!(is_console("https://ci.example.org/gh/acme/web/4411")); + assert!(!is_console( + "https://deploy-preview-12--acme-web.static-host.example" + )); + assert!(is_code_host("https://github.com/acme/web/actions/runs/1")); + assert!(!site_like("https://img.shields.io/badge/x.svg")); +} + +#[test] +fn the_app_a_preview_is_named_after_is_matched_to_the_changed_paths() { + let tree = s(&[ + "apps/web/package.json", + "apps/admin/package.json", + "packages/ui/src/a.ts", + ]); + assert_eq!(apps_of(&tree), s(&["web", "admin", "ui"])); + let a = apps_of(&tree); + assert_eq!(app_score("Preview – web", &changed_web(), &a), 2); + assert_eq!(app_score("Preview – admin", &changed_web(), &a), -1); + assert_eq!(app_score("api-pr-12", &changed_web(), &a), -1); + assert_eq!(app_score("Preview", &changed_web(), &a), 0); +} + +#[test] +fn time_between_reads_rfc3339_and_a_missing_time_is_due() { + assert_eq!( + minutes_between("2026-11-17T10:00:00Z", "2026-11-17T10:45:30Z"), + 45 + ); + assert_eq!(minutes_between("", "2026-11-17T10:45:30Z"), 0); + assert_eq!(seconds_between("", "2026-11-17T10:45:30Z"), i64::MAX); +} diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 6ffc07112..fc27eeb40 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -461,6 +461,12 @@ fn build_app(state: Arc) -> Router { ) .route("/runs/close", post(routes::run_close::close_runs)) .route("/repos", get(routes::api::list_repos)) + .route( + "/repos/:owner/:name/preview-access", + get(routes::preview_access::get) + .put(routes::preview_access::put) + .delete(routes::preview_access::delete), + ) .route( "/repos/:owner/:name/staging-cms", get(routes::staging_cms::get) diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 653924dc4..81c890cc9 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -503,6 +503,10 @@ pub const CAPABILITIES: &[Capability] = &[ "graph::rebuild", "infrastructure::refresh_infrastructure", "infrastructure::refresh_repo_infrastructure", + // A repository's preview access (see routes::preview_access). + "preview_access::get", + "preview_access::put", + "preview_access::delete", // The staging-only CMS write connection (see routes::staging_cms). "staging_cms::get", "staging_cms::put", diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index c9dde8039..fd93e20fb 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -69,6 +69,7 @@ pub mod plan_chat_tools; pub mod plans; pub mod plugin_pkgs; pub mod plugins; +pub mod preview_access; pub mod repo_setup; pub mod review_lessons; pub mod reviewer; diff --git a/services/gateway/src/routes/preview_access.rs b/services/gateway/src/routes/preview_access.rs new file mode 100644 index 000000000..466da4a5f --- /dev/null +++ b/services/gateway/src/routes/preview_access.rs @@ -0,0 +1,251 @@ +//! A repository's preview access (Settings, Repositories, Preview access): +//! optional. The preview's address template, for a host that publishes it +//! nowhere CoderHelm reads, and how an automated browser gets through a +//! protected preview, with one secret the team stores. See +//! `common::preview_access` for the rules (the secret sealed, never +//! returned, sent only to the preview's own host). + +use std::sync::Arc; + +use aws_sdk_dynamodb::types::AttributeValue; +use axum::{ + extract::{Path, State}, + http::StatusCode, + Extension, Json, +}; +use common::preview_access::{self, Kind, PreviewAccess}; +use serde_json::{json, Value}; +use tracing::error; + +use crate::models::Claims; +use crate::AppState; + +type Reply = Result, (StatusCode, Json)>; + +fn fail(status: StatusCode, message: &str) -> (StatusCode, Json) { + ( + status, + Json(json!({ "error": message, "code": crate::openapi::default_code(status) })), + ) +} + +fn internal(context: &str, e: String) -> (StatusCode, Json) { + error!(error = %e, "{context}"); + fail( + StatusCode::INTERNAL_SERVER_ERROR, + "Something went wrong on our side. Try again.", + ) +} + +fn repo_of(owner: &str, name: &str) -> Result)> { + let repo = format!("{owner}/{name}"); + let ok = repo.len() <= 200 + && !repo.contains("..") + && repo + .chars() + .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/'); + if ok { + Ok(repo) + } else { + Err(fail( + StatusCode::BAD_REQUEST, + "That isn't a repository name.", + )) + } +} + +fn forbidden() -> (StatusCode, Json) { + fail( + StatusCode::FORBIDDEN, + "Only admins can change a repository's preview access.", + ) +} + +/// What the request asks to keep, checked: the access, and the secret to +/// seal ("" keeps the one saved). `prior`: the kind saved before and +/// whether a secret is saved. +pub fn read_body( + repo: &str, + body: &Value, + prior: Option<(Kind, bool)>, +) -> Result<(PreviewAccess, String), String> { + let s = |k: &str| body[k].as_str().unwrap_or("").trim().to_string(); + let kind = Kind::parse(&s("kind")).ok_or( + "Pick how the preview is protected: none, a header, a query parameter or a password.", + )?; + let a = PreviewAccess { + repo: repo.to_string(), + kind, + address: s("address"), + }; + a.validate()?; + let secret = body["secret"].as_str().unwrap_or("").trim().to_string(); + if kind == Kind::None { + return Ok((a, String::new())); + } + if secret.is_empty() { + // A saved secret is kept only for the same kind: another kind's + // secret has another shape. + return match prior { + Some((k, true)) if k == kind => Ok((a, String::new())), + _ => Err("Enter the secret the preview takes.".into()), + }; + } + preview_access::check_secret(kind, &secret)?; + Ok((a, secret)) +} + +async fn read_item( + state: &AppState, + team_id: &str, + repo: &str, +) -> Result>, (StatusCode, Json)> { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(preview_access::sk(repo))) + .send() + .await + .map(|r| r.item) + .map_err(|e| internal("Failed to read the preview access", e.to_string())) +} + +fn sealed_of(item: &std::collections::HashMap) -> Option { + item.get(preview_access::SECRET_ATTR) + .and_then(|v| v.as_s().ok().cloned()) + .filter(|s| !s.is_empty()) +} + +/// GET /api/repos/:owner/:name/preview-access +pub async fn get( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + let item = read_item(&state, &claims.team_id, &repo).await?; + Ok(Json( + match item.as_ref().and_then(PreviewAccess::from_item) { + Some(a) => a.view(item.as_ref().and_then(sealed_of).is_some()), + None => json!({ "configured": false, "repo": repo }), + }, + )) +} + +/// PUT /api/repos/:owner/:name/preview-access +/// Body: `{kind, address?, secret?}`. The secret is required the first +/// time for a protected kind and kept when left out later. +pub async fn put( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, + Json(body): Json, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + let prior = read_item(&state, &claims.team_id, &repo).await?; + let prior_sealed = prior.as_ref().and_then(sealed_of); + let prior_kind = prior + .as_ref() + .and_then(PreviewAccess::from_item) + .map(|a| (a.kind, prior_sealed.is_some())); + let (a, secret) = + read_body(&repo, &body, prior_kind).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + let sealed = if a.kind == Kind::None { + None + } else if secret.is_empty() { + prior_sealed + } else { + let cipher = super::alerts::cipher(&state); + Some( + preview_access::seal(&cipher, &claims.team_id, &repo, &secret) + .await + .map_err(|e| internal("Failed to seal the preview access secret", e))?, + ) + }; + let mut item = a.item(&claims.team_id); + let secret_set = sealed.is_some(); + if let Some(s) = sealed { + item.insert(preview_access::SECRET_ATTR.into(), AttributeValue::S(s)); + } + item.insert("updated_by".into(), AttributeValue::S(claims.email.clone())); + item.insert( + "updated_at".into(), + AttributeValue::S(chrono::Utc::now().to_rfc3339()), + ); + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .set_item(Some(item)) + .send() + .await + .map_err(|e| internal("Failed to save the preview access", e.to_string()))?; + Ok(Json(a.view(secret_set))) +} + +/// DELETE /api/repos/:owner/:name/preview-access +pub async fn delete( + State(state): State>, + Extension(claims): Extension, + Path((owner, name)): Path<(String, String)>, +) -> Reply { + claims.require_role(3).map_err(|_| forbidden())?; + let repo = repo_of(&owner, &name)?; + state + .dynamo + .delete_item() + .table_name(&state.config.settings_table_name) + .key("pk", AttributeValue::S(claims.team_id.clone())) + .key("sk", AttributeValue::S(preview_access::sk(&repo))) + .send() + .await + .map_err(|e| internal("Failed to remove the preview access", e.to_string()))?; + Ok(Json(json!({ "configured": false, "repo": repo }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_protected_kind_needs_its_secret_the_first_time_and_keeps_it_after() { + let body = json!({"kind": "header", "secret": "X-Bypass: abc123"}); + let (a, secret) = read_body("acme/web", &body, None).unwrap(); + assert_eq!(a.kind, Kind::Header); + assert_eq!(secret, "X-Bypass: abc123"); + let keep = json!({"kind": "header"}); + assert!(read_body("acme/web", &keep, None).is_err()); + assert_eq!( + read_body("acme/web", &keep, Some((Kind::Header, true))) + .unwrap() + .1, + "" + ); + // Another kind's secret has another shape: a new one is asked for. + let other = json!({"kind": "basic"}); + assert!(read_body("acme/web", &other, Some((Kind::Header, true))).is_err()); + } + + #[test] + fn the_address_alone_is_enough_and_is_checked() { + let ok = json!({"kind": "none", "address": "https://pr-{pr}.preview.example.com"}); + let (a, secret) = read_body("acme/web", &ok, None).unwrap(); + assert_eq!(a.address, "https://pr-{pr}.preview.example.com"); + assert!(secret.is_empty()); + let fixed = json!({"kind": "none", "address": "https://staging.example.com"}); + assert!(read_body("acme/web", &fixed, None).is_err()); + let bad = json!({"kind": "header", "secret": "nocolon"}); + assert!(read_body("acme/web", &bad, None).is_err()); + assert!(read_body("acme/web", &json!({"kind": "magic"}), None).is_err()); + } + + #[test] + fn repository_names_are_checked() { + assert_eq!(repo_of("acme", "web").unwrap(), "acme/web"); + assert!(repo_of("acme", "..").is_err()); + } +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 449ceca56..aea185278 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3237,47 +3237,61 @@ impl GitHubClient { .await } - /// The address each deployment of `sha` reports, as (environment, url): - /// the newest status of each deployment that has one. - pub async fn deployment_urls( + /// The deployments on commit `sha`, each with its newest statuses (the + /// deployments listing filtered by sha, then each one's statuses), for + /// `common::preview_find::deployments`. Empty when the installation + /// can't read deployments. + pub async fn deployments_with_statuses( &self, owner: &str, repo: &str, sha: &str, - ) -> Result, Box> { - let deps = self - .get(&format!( - "{API_BASE}/repos/{owner}/{repo}/deployments?sha={sha}&per_page=10" - )) - .await?; + ) -> Result< + Vec<(serde_json::Value, Vec)>, + Box, + > { + let Some(deps) = self + .get_granted( + "deployments", + &format!("/repos/{owner}/{repo}/deployments?sha={sha}&per_page=20"), + ) + .await? + else { + return Ok(Vec::new()); + }; let mut out = Vec::new(); - for d in deps.as_array().into_iter().flatten().take(10) { - let (Some(id), env) = (d["id"].as_u64(), d["environment"].as_str().unwrap_or("")) - else { + for d in deps.as_array().into_iter().flatten().take(20) { + let Some(id) = d["id"].as_u64() else { continue; }; let st = self - .get(&format!( - "{API_BASE}/repos/{owner}/{repo}/deployments/{id}/statuses?per_page=5" - )) - .await?; - if let Some(url) = st - .as_array() - .into_iter() - .flatten() - .filter_map(|s| { - s["environment_url"] - .as_str() - .or_else(|| s["target_url"].as_str()) - }) - .find(|u| u.starts_with("https://")) - { - out.push((env.to_string(), url.to_string())); - } + .get_granted( + "deployments", + &format!("/repos/{owner}/{repo}/deployments/{id}/statuses?per_page=10"), + ) + .await? + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default(); + out.push((d.clone(), st)); } Ok(out) } + /// When commit `sha` was made (its committer's time, RFC 3339). + pub async fn commit_time( + &self, + owner: &str, + repo: &str, + sha: &str, + ) -> Result> { + let c = self.git_commit(owner, repo, sha).await?; + Ok(c["committer"]["date"] + .as_str() + .or_else(|| c["author"]["date"].as_str()) + .unwrap_or("") + .to_string()) + } + /// Points a ref outside `refs/heads/` (no workflow starts on it) at /// `sha`, creating it when it doesn't exist. Only for CoderHelm's own /// refs, such as the one its pull request screenshots are kept on. diff --git a/services/worker/src/passes/ci_repro.rs b/services/worker/src/passes/ci_repro.rs index 549b40b1b..e09f0d74b 100644 --- a/services/worker/src/passes/ci_repro.rs +++ b/services/worker/src/passes/ci_repro.rs @@ -427,7 +427,7 @@ pub(crate) async fn two_way( } /// The team's test address for the repository (Tests settings), as set. -async fn test_address(state: &WorkerState, team_id: &str, repo: &str) -> Option { +pub(crate) async fn test_address(state: &WorkerState, team_id: &str, repo: &str) -> Option { let st = common::e2e::store::Store::new(&state.dynamo, &state.config.tests_table_name); if !st.enabled() { return None; diff --git a/services/worker/src/passes/pr_watch.rs b/services/worker/src/passes/pr_watch.rs index 1a7767d66..6d08b5578 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -308,8 +308,10 @@ pub fn decide_all(status: &str, seen: &Seen, marks: &Marks) -> Act { /// Whether the head's preview needs a look: the change's recorded state is /// of another head or not settled. A look that read nothing new (`fresh` -/// false) leaves a pending preview to the next change on the pull request. -pub fn preview_due(stored: &str, head: &str, fresh: bool) -> bool { +/// false) leaves a pending preview until `preview_find::POLL_SECS` after +/// its last look (`now`): a host's deploy finishing changes nothing else +/// on the pull request, and the wait is bounded (`preview::settle`). +pub fn preview_due(stored: &str, head: &str, fresh: bool, now: &str) -> bool { if head.is_empty() { return false; } @@ -319,7 +321,11 @@ pub fn preview_due(stored: &str, head: &str, fresh: bool) -> bool { Some(st) if super::preview::settled(&st, head) => false, // Ready: its pages are captured now, whatever else changed. Some(st) if st.stage == common::preview::Stage::Ready => true, - Some(_) => fresh, + Some(st) => { + fresh + || common::preview_find::seconds_between(&st.looked_at, now) + >= common::preview_find::POLL_SECS + } } } @@ -1005,10 +1011,14 @@ pub async fn look(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> }; let mut seen = seen; seen.preview_due = seen.open - && (preview_due(&c.preview, &seen.head, kept.is_none()) - || common::preview::State::from_json(&c.preview).is_some_and(|st| { - st.head == seen.head && super::preview::unread_failure(&st, &seen.failing) - })); + && (preview_due( + &c.preview, + &seen.head, + kept.is_none(), + &chrono::Utc::now().to_rfc3339(), + ) || common::preview::State::from_json(&c.preview).is_some_and(|st| { + st.head == seen.head && super::preview::unread_failure(&st, &seen.failing) + })); let mut act = resume_after_limit(&c.status, &seen, &c.marks, &c.limit_ended) .unwrap_or_else(|| decide_all(&c.status, &seen, &c.marks)); let mut performed = Performed::NotStarted; @@ -1398,7 +1408,8 @@ mod tests { #[test] fn an_unchecked_preview_is_picked_up_after_the_run_ended() { let mut seen = open(); - seen.preview_due = preview_due("", &seen.head, true); + let now = "2026-11-17T10:00:00Z"; + seen.preview_due = preview_due("", &seen.head, true, now); assert!(seen.preview_due); assert_eq!( decide_all("completed", &seen, &Marks::default()), @@ -1418,17 +1429,25 @@ mod tests { ..Default::default() } .to_json(); - assert!(!preview_due(&done, &seen.head, true)); - assert!(preview_due(&done, "another", false)); - // Pending and nothing new on the pull request: the next change. + assert!(!preview_due(&done, &seen.head, true, now)); + assert!(preview_due(&done, "another", false, now)); + // Pending and nothing new on the pull request: looked at again once + // a poll's time has passed since its last look. let pending = common::preview::State { head: seen.head.clone(), stage: common::preview::Stage::Deploying, + looked_at: "2026-11-17T09:59:30Z".into(), ..Default::default() } .to_json(); - assert!(!preview_due(&pending, &seen.head, false)); - assert!(preview_due(&pending, &seen.head, true)); + assert!(!preview_due(&pending, &seen.head, false, now)); + assert!(preview_due(&pending, &seen.head, true, now)); + assert!(preview_due( + &pending, + &seen.head, + false, + "2026-11-17T10:02:00Z" + )); // Never for a run still in flight. assert_eq!( decide_all("running", &seen, &Marks::default()), diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs index 3ee18abb0..8f8ee7721 100644 --- a/services/worker/src/passes/preview.rs +++ b/services/worker/src/passes/preview.rs @@ -15,14 +15,20 @@ //! the workflows need (only labels the team's settings allow, never a //! shared environment's), starts a workflow that counts labels only from //! a push with an empty commit on CoderHelm's own branch, and reads the -//! covering checks' results and the preview's address. +//! covering checks' results, and finds the head's preview wherever the +//! team's host or CI publishes it (`common::preview_find`: deployments, +//! deploy statuses, preview checks, bot comments, the description, the +//! team's address template), waiting a bounded time while it builds. //! - [`capture`] runs once the preview is up and its end-to-end checks //! passed, in a step of the watch: a failed capture says why in one line -//! and is never retried into a pass. +//! and is never retried into a pass. A protected preview is opened with +//! the access the team saved for the repository (`common::preview_access`). use aws_sdk_dynamodb::types::AttributeValue; use base64::Engine as _; use common::preview::{self as pv, CheckResult, Outcome, Shot, Stage, State}; +use common::preview_access::{self as pa, PreviewAccess}; +use common::preview_find::{self as pf, Answer}; use tracing::{info, warn}; use super::attr_s; @@ -113,12 +119,8 @@ fn outcome_of(run: &serde_json::Value) -> Outcome { } } -/// The covering checks' newest runs on the head, and the preview address -/// any of them printed. -fn covering_results( - runs: &serde_json::Value, - covers: &[pv::Covering], -) -> (Vec, Option) { +/// The covering checks' newest runs on the head. +fn covering_results(runs: &serde_json::Value, covers: &[pv::Covering]) -> Vec { // The newest run of each covering check that ran: a check skipped on // the draft and run once it was ready reads as run, and a later event // that skips it (another label added) doesn't undo a run. @@ -140,26 +142,193 @@ fn covering_results( None => newest.push((name, r)), } } - let mut out: Vec = Vec::new(); - let mut url = None; - for (name, r) in newest { - if url.is_none() { - url = [ - r["output"]["summary"].as_str(), - r["output"]["text"].as_str(), - r["details_url"].as_str(), - ] - .into_iter() - .flatten() - .find_map(pv::url_in); - } - out.push(CheckResult { + newest + .into_iter() + .map(|(name, r)| CheckResult { name: name.to_string(), outcome: outcome_of(r), url: r["html_url"].as_str().unwrap_or("").to_string(), + }) + .collect() +} + +/// The repository's preview access with its opened secret ("" when it has +/// none). None when the team saved none. +pub(crate) async fn load_access( + state: &WorkerState, + team_id: &str, + repo: &str, +) -> Option<(PreviewAccess, String)> { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&pa::sk(repo))) + .send() + .await + .ok()? + .item?; + let a = PreviewAccess::from_item(&item)?; + let sealed = item + .get(pa::SECRET_ATTR) + .and_then(|v| v.as_s().ok()) + .filter(|s| !s.is_empty()); + let secret = match sealed { + Some(sealed) if a.kind != pa::Kind::None => { + let kms = common::mcp_credentials::Kms { + client: &state.kms, + key_id: &state.config.secrets_key_id, + }; + match pa::open(&kms, team_id, repo, sealed).await { + Ok(t) => t, + Err(e) => { + warn!(repo, error = %e, "Could not open the preview access secret"); + String::new() + } + } + } + _ => String::new(), + }; + Some((a, secret)) +} + +/// The team's preview address template for the repository: its preview +/// access, else a Tests settings test address that names the pull request. +async fn template_of( + state: &WorkerState, + team_id: &str, + repo: &str, + access: Option<&PreviewAccess>, +) -> Option { + if let Some(a) = access.map(|a| a.address.trim()).filter(|a| !a.is_empty()) { + return Some(a.to_string()); + } + super::ci_repro::test_address(state, team_id, repo) + .await + .filter(|t| pf::is_per_change(t)) +} + +/// Everything on the pull request that says where the head's preview is. +#[allow(clippy::too_many_arguments)] +async fn sightings( + gh: &GitHubClient, + p: Pr<'_>, + pr: &serde_json::Value, + head: &str, + branch: &str, + runs: &serde_json::Value, + covers: &[pv::Covering], + template: Option<&str>, +) -> Vec { + let mut all = Vec::new(); + match gh.deployments_with_statuses(p.owner, p.repo, head).await { + Ok(d) => all.extend(pf::deployments(&d, head)), + Err(e) => warn!(pr = p.number, error = %e, "Could not read the head's deployments"), + } + match gh.commit_statuses(p.owner, p.repo, head).await { + Ok(Some(c)) => all.extend(pf::statuses(&c, head)), + Ok(None) => {} + Err(e) => warn!(pr = p.number, error = %e, "Could not read the head's statuses"), + } + all.extend(pf::check_runs(runs, head, covers)); + let head_at = gh + .commit_time(p.owner, p.repo, head) + .await + .unwrap_or_default(); + match gh.list_issue_comments(p.owner, p.repo, p.number).await { + Ok(c) => all.extend(pf::comments(&c, head, &head_at)), + Err(e) => warn!(pr = p.number, error = %e, "Could not read the pull request's comments"), + } + all.extend(pf::body(pr["body"].as_str().unwrap_or(""), head)); + if let Some(url) = template.and_then(|t| { + pf::expand( + t, + pf::Vars { + pr: p.number, + branch, + sha: head, + owner: p.owner, + repo: p.repo, + }, + ) + }) { + all.push(pf::Sighting { + source: pf::Source::Template, + name: String::new(), + url, + ready: pf::Ready::Up, + tied: false, }); } - (out, url) + all +} + +/// Where the preview stands once the repository's own preview checks +/// (`from_checks`, None when no workflow covers the change) and what the +/// pull request publishes about the head's preview are put together, with +/// the wait bounded. Pure: every case is tested. +pub fn settle(st: &mut State, from_checks: Option, answer: &Answer, now: &str) { + let waited = pf::minutes_between(&st.waiting_since, now); + let mut waiting_on = String::new(); + match from_checks { + Some(stage) => st.stage = stage, + None => st.stage = Stage::Triggered, + } + match answer { + Answer::Up(f) => { + st.url = f.url.clone(); + st.found = f.clone(); + match from_checks { + // No workflow of the repository's covers it: the host's own + // preview of the head is up. + None => st.stage = Stage::Ready, + // The workflows couldn't be started, but the head has a + // preview: it is checked on that. + Some(Stage::Blocked) => { + st.stage = Stage::Ready; + st.why.clear(); + } + Some(_) => {} + } + } + Answer::Building(what) => { + waiting_on = what.clone(); + if from_checks.is_none() || st.stage == Stage::Ready { + st.stage = Stage::Deploying; + } + } + Answer::Failed(what) => { + if from_checks.is_none() + || matches!(st.stage, Stage::Ready | Stage::Deploying | Stage::Triggered) + { + st.stage = Stage::Failed; + st.why = format!("{what} for this commit, so its pages couldn't be captured"); + } + } + Answer::Nothing if from_checks.is_none() => { + if waited >= pf::GRACE_MINS { + st.stage = Stage::Blocked; + st.why = format!( + "nothing on this commit publishes a preview (no deployment, deploy status, preview check, bot comment or description link) and the team set no preview address in {}, so no page could be captured", + pv::ACCESS_SETTING + ); + } + } + Answer::Nothing => {} + } + if matches!(st.stage, Stage::Triggered | Stage::Deploying) && waited >= pf::WAIT_BUDGET_MINS { + let what = if waiting_on.is_empty() { + "its checks hadn't finished".to_string() + } else { + format!("{waiting_on} was still building") + }; + st.stage = Stage::Blocked; + st.why = format!( + "the preview of this commit wasn't up within {} minutes ({what}), so its pages couldn't be captured; a new push starts the wait again", + pf::WAIT_BUDGET_MINS + ); + } } /// The workflow files at `git_ref`, with their text. @@ -437,85 +606,101 @@ pub async fn advance( }); st.covers = plan.covers.clone(); st.draft_gated = plan.draft_gated.clone(); - if !plan.has_path() { - st.stage = Stage::Blocked; - st.why = - "the repository has no preview deploy for this change, so no page could be captured" - .into(); - save(state, p, &st).await; - return Some(st); - } - // Start what the workflows need: once per label per head. - let mut add = Vec::new(); - for l in &plan.add { - if st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) { - continue; - } - if super::review_pr::may_add_label(state, p.team_id, p.owner, p.repo, l).await { - add.push(l.clone()); + let now = chrono::Utc::now().to_rfc3339(); + st.looked_at = now.clone(); + st.waiting_since = same_head + .map(|s| s.waiting_since.clone()) + .filter(|w| !w.is_empty()) + .unwrap_or_else(|| now.clone()); + let mut from_checks = None; + if plan.has_path() { + // Start what the workflows need: once per label per head. + let mut add = Vec::new(); + for l in &plan.add { + if st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) { + continue; + } + if super::review_pr::may_add_label(state, p.team_id, p.owner, p.repo, l).await { + add.push(l.clone()); + } } - } - let mut blocked = plan.blocked.clone(); - if !add.is_empty() { - match gh.add_labels(p.owner, p.repo, p.number, &add).await { - Ok(_) => { - info!(pr = p.number, labels = ?add, "Added the labels that start the preview and its end-to-end checks"); - st.labels_added.extend(add.iter().cloned()); - if plan.needs_push && !draft && !branch.is_empty() { - let pushed = nudge(gh, p.owner, p.repo, &branch, &head).await; - info!( - pr = p.number, - pushed, "Pushed an empty commit so the labels count" - ); + let mut blocked = plan.blocked.clone(); + if !add.is_empty() { + match gh.add_labels(p.owner, p.repo, p.number, &add).await { + Ok(_) => { + info!(pr = p.number, labels = ?add, "Added the labels that start the preview and its end-to-end checks"); + st.labels_added.extend(add.iter().cloned()); + if plan.needs_push && !draft && !branch.is_empty() { + let pushed = nudge(gh, p.owner, p.repo, &branch, &head).await; + info!( + pr = p.number, + pushed, "Pushed an empty commit so the labels count" + ); + } + } + Err(e) => { + warn!(pr = p.number, error = %e, "Could not add the preview labels"); + blocked.push(format!( + "CoderHelm couldn't add {} ({})", + add.join(", "), + common::truncate_str(&e.to_string(), 120) + )); } - } - Err(e) => { - warn!(pr = p.number, error = %e, "Could not add the preview labels"); - blocked.push(format!( - "CoderHelm couldn't add {} ({})", - add.join(", "), - common::truncate_str(&e.to_string(), 120) - )); } } + let not_allowed: Vec<&String> = plan + .add + .iter() + .filter(|l| { + !st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) + && !on_pr.iter().any(|o| o.eq_ignore_ascii_case(l)) + }) + .collect(); + if !not_allowed.is_empty() && add.is_empty() { + blocked.push(format!( + "the team's label settings don't let CoderHelm add {}", + not_allowed + .iter() + .map(|l| format!("`{l}`")) + .collect::>() + .join(", ") + )); + } + st.checks = covering_results(&runs, &plan.covers); + let triggered = !st.labels_added.is_empty() || draft; + let mut stage = pv::progress(&st.checks, triggered); + let none_ran = st.checks.iter().all(|c| c.outcome == Outcome::Skipped); + if none_ran && !blocked.is_empty() && st.labels_added.is_empty() && !draft { + stage = Stage::Blocked; + st.why = blocked.join("; "); + } + from_checks = Some(stage); } - let not_allowed: Vec<&String> = plan - .add - .iter() - .filter(|l| { - !st.labels_added.iter().any(|a| a.eq_ignore_ascii_case(l)) - && !on_pr.iter().any(|o| o.eq_ignore_ascii_case(l)) - }) - .collect(); - if !not_allowed.is_empty() && add.is_empty() { - blocked.push(format!( - "the team's label settings don't let CoderHelm add {}", - not_allowed - .iter() - .map(|l| format!("`{l}`")) - .collect::>() - .join(", ") - )); - } - let (results, url) = covering_results(&runs, &plan.covers); - st.checks = results; - let triggered = !st.labels_added.is_empty() || draft; - st.stage = pv::progress(&st.checks, triggered); - let none_ran = st.checks.iter().all(|c| c.outcome == Outcome::Skipped); - if none_ran && !blocked.is_empty() && st.labels_added.is_empty() && !draft { - st.stage = Stage::Blocked; - st.why = blocked.join("; "); - } - st.url = match url { - Some(u) => u, - None if matches!(st.stage, Stage::Ready | Stage::Deploying) => gh - .deployment_urls(p.owner, p.repo, &head) - .await - .ok() - .and_then(|d| pv::url_from_deployments(&d)) - .unwrap_or_default(), - None => String::new(), - }; + // Where the head's preview is, wherever the team's host or CI + // publishes it. + let repo_full = format!("{}/{}", p.owner, p.repo); + let access = load_access(state, p.team_id, &repo_full).await; + let template = template_of( + state, + p.team_id, + &repo_full, + access.as_ref().map(|(a, _)| a), + ) + .await; + let seen = sightings( + gh, + p, + pr, + &head, + &branch, + &runs, + &plan.covers, + template.as_deref(), + ) + .await; + let answer = pf::resolve(&seen, &changed, &pf::apps_of(&tree)); + info!(pr = p.number, sightings = seen.len(), answer = ?answer, "Read where the head's preview is"); + settle(&mut st, from_checks, &answer, &now); // Captured on this head already: it stays checked. if st.stage == Stage::Ready { if let Some(prev) = same_head.filter(|s| !s.shots.is_empty() || s.stage == Stage::Checked) { @@ -544,7 +729,10 @@ pub async fn capture( } st.stage = Stage::Checked; if st.url.is_empty() { - st.why = "the preview's address wasn't in its deploy's output or deployments, so its pages couldn't be captured".into(); + st.why = format!( + "the preview's checks passed but nothing on this commit published its address (no deployment, deploy status, preview check, bot comment or description link) and no preview address is set in {}, so its pages couldn't be captured", + pv::ACCESS_SETTING + ); save(state, p, st).await; return; } @@ -553,7 +741,19 @@ pub async fn capture( .next() .unwrap_or("") .to_string(); - let base = format!("https://{host}"); + let base = pv::capture_base(&st.url); + let repo_full = format!("{}/{}", p.owner, p.repo); + let (kind, secret) = match load_access(state, p.team_id, &repo_full).await { + Some((a, s)) if a.kind != pa::Kind::None && !s.is_empty() => (a.kind, s), + _ => (pa::Kind::None, String::new()), + }; + let hide = |t: &str| { + if secret.is_empty() { + t.to_string() + } else { + t.replace(secret.as_str(), "***") + } + }; let tree: Vec = gh .get_tree(p.owner, p.repo, &st.head) .await @@ -561,7 +761,7 @@ pub async fn capture( .unwrap_or_default(); let changed = changed_of(gh, p).await; let pages = pv::routes(&tree, &changed); - let script = pv::capture_script(&base, &pages); + let script = pv::capture_script(&base, &pages, kind); let source = match super::skill_run::pack(&[("capture.mjs".to_string(), script)]) { Ok(b) => b, Err(e) => { @@ -592,7 +792,7 @@ pub async fn capture( key: &key, source, cmd: &cmd, - secret: None, + secret: (!secret.is_empty()).then_some(secret.as_str()), hosts, }, deadline, @@ -603,13 +803,16 @@ pub async fn capture( Ok(o) => { st.why = format!( "the capture didn't run in the sandbox ({})", - common::truncate_str(o.output.lines().next().unwrap_or(""), 120) + common::truncate_str(&hide(o.output.lines().next().unwrap_or("")), 120) ); save(state, p, st).await; return; } Err(e) => { - st.why = format!("the sandbox couldn't run the capture ({e})"); + st.why = format!( + "the sandbox couldn't run the capture ({})", + hide(&e.to_string()) + ); save(state, p, st).await; return; } @@ -620,7 +823,7 @@ pub async fn capture( .find(|(n, _)| n.ends_with("shots.json")) .and_then(|(_, b)| serde_json::from_str(b).ok()) .unwrap_or_default(); - if let Some(why) = pv::why_no_shot(&report) { + if let Some(why) = pv::why_no_shot(&report, kind != pa::Kind::None) { st.why = why; save(state, p, st).await; return; @@ -671,7 +874,7 @@ async fn keep_images( let short = head.get(..12).unwrap_or(head); let mut entries: Vec<(String, Option)> = Vec::new(); let mut shots: Vec<(Shot, String)> = Vec::new(); - for c in report.iter().filter(|c| (1..400).contains(&c.status)) { + for c in report.iter().filter(|c| c.shot()) { let Some((_, b64)) = files .iter() .find(|(n, _)| n.ends_with(&format!("{}.png.b64", c.name))) @@ -735,7 +938,7 @@ mod tests { use super::*; #[test] - fn covering_runs_are_read_with_the_preview_address_they_print() { + fn covering_runs_are_read_newest_first() { let runs = serde_json::json!({"check_runs": [ {"name": "Deploy Preview Web App", "status": "completed", "conclusion": "success", "html_url": "https://github.com/o/r/runs/1", @@ -754,11 +957,10 @@ mod tests { ..Default::default() }, ]; - let (r, url) = covering_results(&runs, &covers); + let r = covering_results(&runs, &covers); assert_eq!(r.len(), 2); assert_eq!(r[0].outcome, Outcome::Passed); assert_eq!(r[1].outcome, Outcome::Running); - assert_eq!(url.as_deref(), Some("https://pr-9.preview-web.example.com")); assert_eq!(pv::progress(&r, true), Stage::Deploying); } @@ -776,7 +978,7 @@ mod tests { check: "E2E on preview".into(), ..Default::default() }]; - let (r, _) = covering_results(&runs, &covers); + let r = covering_results(&runs, &covers); assert_eq!(r.len(), 1); assert_eq!(r[0].outcome, Outcome::Passed); } @@ -797,4 +999,117 @@ mod tests { }; assert!(!settled(&pending, "abc")); } + + const T0: &str = "2026-11-17T10:00:00Z"; + + fn waiting() -> State { + State { + head: "abc".into(), + waiting_since: T0.into(), + ..Default::default() + } + } + + fn up(source: pf::Source) -> Answer { + Answer::Up(pf::Found { + url: "https://pr-12.preview.example.com".into(), + source, + name: String::new(), + tied: true, + }) + } + + #[test] + fn a_hosts_own_preview_counts_when_no_workflow_covers_the_change() { + let mut st = waiting(); + settle( + &mut st, + None, + &up(pf::Source::Deployment), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Ready); + assert_eq!(st.url, "https://pr-12.preview.example.com"); + assert_eq!(st.found.source, pf::Source::Deployment); + let mut st = waiting(); + settle( + &mut st, + None, + &Answer::Building("the deployment".into()), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Deploying); + assert!(st.pending()); + } + + #[test] + fn a_preview_still_building_after_its_checks_passed_is_waited_on() { + let mut st = waiting(); + settle( + &mut st, + Some(Stage::Ready), + &Answer::Building("the deployment `pr-12`".into()), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Deploying); + // The workflows couldn't start, but the head has its preview. + let mut st = waiting(); + st.why = "the label isn't allowed".into(); + settle( + &mut st, + Some(Stage::Blocked), + &up(pf::Source::Comment), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Ready); + assert!(st.why.is_empty()); + } + + #[test] + fn a_failed_head_deploy_is_said_with_where_it_was_read() { + let mut st = waiting(); + settle( + &mut st, + None, + &Answer::Failed("the head commit's deployment `Preview` failed".into()), + "2026-11-17T10:03:00Z", + ); + assert_eq!(st.stage, Stage::Failed); + assert!(st.why.contains("deployment `Preview` failed"), "{}", st.why); + } + + #[test] + fn the_wait_is_bounded() { + // Nothing at all on the head: a short grace, then no preview. + let mut st = waiting(); + settle(&mut st, None, &Answer::Nothing, "2026-11-17T10:02:00Z"); + assert_eq!(st.stage, Stage::Triggered); + let mut st = waiting(); + settle(&mut st, None, &Answer::Nothing, "2026-11-17T10:07:00Z"); + assert_eq!(st.stage, Stage::Blocked); + assert!(st.why.contains(pv::ACCESS_SETTING), "{}", st.why); + // Building for longer than the budget: said, never waited on for ever. + let mut st = waiting(); + settle( + &mut st, + None, + &Answer::Building("the deploy status `site/deploy-preview`".into()), + "2026-11-17T11:00:00Z", + ); + assert_eq!(st.stage, Stage::Blocked); + assert!( + st.why.contains("60 minutes") && st.why.contains("still building"), + "{}", + st.why + ); + let mut st = waiting(); + settle( + &mut st, + Some(Stage::Deploying), + &Answer::Nothing, + "2026-11-17T11:05:00Z", + ); + assert_eq!(st.stage, Stage::Blocked); + assert!(st.why.contains("checks hadn't finished")); + } } From ac98bdb31564ae346f842aa65f68c043143d654a Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 00:02:05 -0500 Subject: [PATCH 24/32] Fill the Before and After table from the end-to-end run's screenshots CoderHelm's own pull request now shows the screenshots its end-to-end run already took, instead of "No screenshot". - common::e2e::shots reads the images Cucumber JSON embeds, Playwright JSON attaches and Playwright's HTML report keeps under data/, keyed by the test's id, and picks the test that shows the change: one the change edits, one the test map ties to the changed files, or one whose name shares a word with a changed UI file. - e2e_screens keeps that test's screenshot on the head and on the default branch's newest passing run in the install's own bucket, records it for the head and rebuilds the description. - The table links each image through the API with a signed link that works for a year (GET /webhooks/ci/tests/screenshot); the bucket keeps the images 395 days. --- infra/lib/storage-stack.ts | 7 + services/common/src/e2e/mod.rs | 4 + services/common/src/e2e/shots.rs | 867 ++++++++++++++++++ services/common/src/pr_body.rs | 18 +- services/gateway/src/main.rs | 3 + services/gateway/src/routes/tests.rs | 60 ++ services/worker/src/passes/description.rs | 31 + .../worker/src/passes/description_eval.rs | 1 + services/worker/src/passes/e2e.rs | 22 +- services/worker/src/passes/e2e_screens.rs | 426 +++++++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/test_fix.rs | 24 + 12 files changed, 1461 insertions(+), 3 deletions(-) create mode 100644 services/common/src/e2e/shots.rs create mode 100644 services/worker/src/passes/e2e_screens.rs diff --git a/infra/lib/storage-stack.ts b/infra/lib/storage-stack.ts index e15166b02..b467b1b2c 100644 --- a/infra/lib/storage-stack.ts +++ b/infra/lib/storage-stack.ts @@ -133,6 +133,13 @@ export class StorageStack extends cdk.Stack { expiration: cdk.Duration.days(2), noncurrentVersionExpiration: cdk.Duration.days(1), }, + { + // End-to-end screenshots in pull request descriptions: their links + // work for a year (common::e2e::shots), the images a month longer. + prefix: "e2e-shots/", + expiration: cdk.Duration.days(395), + noncurrentVersionExpiration: cdk.Duration.days(1), + }, { // Move old run artifacts to Infrequent Access after 90 days transitions: [ diff --git a/services/common/src/e2e/mod.rs b/services/common/src/e2e/mod.rs index 76a699773..d093148c5 100644 --- a/services/common/src/e2e/mod.rs +++ b/services/common/src/e2e/mod.rs @@ -33,6 +33,9 @@ //! holds end-to-end selectors to it. //! - [`branches`] finds test branches on a page's state and which of them a //! recorded run, or the page as it is now, would run. +//! - [`shots`] finds the screenshots a report carries for the tests that +//! show a change, for the Before and After table of CoderHelm's own pull +//! request. pub mod attribution; pub mod branches; @@ -54,6 +57,7 @@ pub mod parse; pub mod probe; pub mod quarantine; pub mod report_source; +pub mod shots; pub mod signature; pub mod stats; pub mod store; diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs new file mode 100644 index 000000000..1d323f61b --- /dev/null +++ b/services/common/src/e2e/shots.rs @@ -0,0 +1,867 @@ +//! Screenshots the end-to-end reports already carry, for the Before and +//! After table of CoderHelm's own pull request. +//! +//! A pull request whose whole change was visual showed no screenshot, while +//! the team's end-to-end run on it had taken some. The reports CoderHelm +//! reads (`parse`, `attribution`) keep them: +//! +//! - Cucumber JSON (WebdriverIO, Appium): images embedded in a scenario's +//! steps and hooks, base64 in the report itself; +//! - Playwright JSON: image attachments of a test's result, a file in the +//! run's artifacts (`path`) or the image itself (`body`); +//! - Playwright's HTML report: image attachments under its `data/` folder. +//! +//! [`shots_in`] reads them per test, keyed by the test's id +//! ([`ParsedTest::id`]), and [`pick`] chooses the tests that show the change: +//! a test the change edits, a test the repository's test map ties to the +//! changed files, or a test whose name shares a word with a changed UI file. +//! The worker keeps the images in the install's own bucket +//! ([`object_key`]); the description links them with a signed link +//! ([`sign`]) that the API serves at [`LINK_PATH`] until it expires. + +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::Engine; +use hmac::{Hmac, Mac}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::Sha256; + +use super::coverage::TestMap; +use super::model::{test_id, Framework, Outcome, ParsedTest}; + +/// Largest image kept. +pub const MAX_IMAGE: usize = 5 * 1024 * 1024; +/// Where the images are kept in the install's bucket. +pub const KEY_PREFIX: &str = "e2e-shots"; +/// How long an image link works (the bucket keeps the images a little +/// longer, see `infra/lib/storage-stack.ts`). +pub const LINK_VALID_SECS: i64 = 365 * 86_400; +/// The path the API serves an image at. +pub const LINK_PATH: &str = "/webhooks/ci/tests/screenshot"; +const MAX_TOKEN_LEN: usize = 2048; + +/// One test's screenshot in one report. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Shot { + /// The test's id ([`ParsedTest::id`]). + pub test_id: String, + pub image: Image, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Image { + /// The image itself (a Cucumber embedding, a Playwright `body`). + Inline(Vec), + /// A file of the run, as the report wrote its path. + File(String), +} + +/// The image's type, from its first bytes. Only PNG, JPEG and WebP are +/// kept. +pub fn image_type(bytes: &[u8]) -> Option<&'static str> { + if bytes.starts_with(&[0x89, b'P', b'N', b'G']) { + Some("image/png") + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + Some("image/jpeg") + } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + Some("image/webp") + } else { + None + } +} + +/// The file extension for an image type. +pub fn extension(content_type: &str) -> &'static str { + match content_type { + "image/jpeg" => "jpg", + "image/webp" => "webp", + _ => "png", + } +} + +fn is_image(content_type: &str) -> bool { + matches!( + content_type.trim().to_ascii_lowercase().as_str(), + "image/png" | "image/jpeg" | "image/jpg" | "image/webp" + ) +} + +fn decoded(data: &str) -> Option> { + let clean: String = data.chars().filter(|c| !c.is_whitespace()).collect(); + let bytes = STANDARD.decode(clean).ok()?; + (bytes.len() <= MAX_IMAGE && image_type(&bytes).is_some()).then_some(bytes) +} + +/// The screenshots in one report file, the last one of each test (its last +/// attempt, its final state). Empty when the file is not a report this +/// reads or carries no image. +pub fn shots_in(name: &str, bytes: &[u8]) -> Vec { + if bytes.len() > super::parse::MAX_REPORT_BYTES { + return Vec::new(); + } + let lower = name.to_lowercase(); + let found = if lower.ends_with(".html") { + playwright_html(bytes) + } else if lower.ends_with(".json") { + match serde_json::from_slice::(bytes) { + Ok(v) if v.get("suites").is_some() && v.get("config").is_some() => playwright(&v), + Ok(v) if v + .as_array() + .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => + { + cucumber(&v) + } + _ => Vec::new(), + } + } else { + Vec::new() + }; + last_per_test(found) +} + +fn last_per_test(found: Vec) -> Vec { + let mut out: Vec = Vec::new(); + for s in found { + match out.iter_mut().find(|x| x.test_id == s.test_id) { + Some(x) => *x = s, + None => out.push(s), + } + } + out +} + +// ── Cucumber JSON ───────────────────────────────────────────────────────── + +fn cucumber(report: &Value) -> Vec { + let mut out = Vec::new(); + for feature in report.as_array().into_iter().flatten() { + let file = feature["uri"].as_str().unwrap_or(""); + let feature_name = feature["name"].as_str().unwrap_or(""); + let suite: Vec = if feature_name.is_empty() { + vec![] + } else { + vec![feature_name.to_string()] + }; + for el in feature["elements"].as_array().into_iter().flatten() { + if el["type"].as_str() == Some("background") { + continue; + } + let last = ["before", "steps", "after"] + .iter() + .flat_map(|k| el[*k].as_array().into_iter().flatten()) + .flat_map(|s| s["embeddings"].as_array().into_iter().flatten()) + .filter(|e| { + is_image( + e["mime_type"] + .as_str() + .or_else(|| e["media"]["type"].as_str()) + .unwrap_or(""), + ) + }) + .filter_map(|e| e["data"].as_str().and_then(decoded)) + .last(); + if let Some(bytes) = last { + out.push(Shot { + test_id: test_id( + Framework::Cucumber, + file, + &suite, + el["name"].as_str().unwrap_or(""), + None, + ), + image: Image::Inline(bytes), + }); + } + } + } + out +} + +// ── Playwright ──────────────────────────────────────────────────────────── + +/// The last image attachment of a test's last result. +fn pw_image(results: &Value) -> Option { + let last = results.as_array()?.last()?; + last["attachments"] + .as_array()? + .iter() + .filter(|a| is_image(a["contentType"].as_str().unwrap_or(""))) + .filter_map(|a| match (a["body"].as_str(), a["path"].as_str()) { + (Some(b), _) if !b.is_empty() => decoded(b).map(Image::Inline), + (_, Some(p)) if !p.is_empty() && !p.contains("..") => Some(Image::File(p.to_string())), + _ => None, + }) + .last() +} + +fn project_of(test: &Value) -> Option<&str> { + test["projectName"].as_str().filter(|p| !p.is_empty()) +} + +/// The same walk as `parse::parse_playwright`, so ids match. +fn pw_walk(suite: &Value, path: &mut Vec, out: &mut Vec) { + let title = suite["title"].as_str().unwrap_or(""); + let file = suite["file"].as_str().unwrap_or(""); + let pushed = !title.is_empty() && title != file; + if pushed { + path.push(title.to_string()); + } + for spec in suite["specs"].as_array().into_iter().flatten() { + let spec_file = spec["file"].as_str().unwrap_or(file); + for test in spec["tests"].as_array().into_iter().flatten() { + if let Some(image) = pw_image(&test["results"]) { + out.push(Shot { + test_id: test_id( + Framework::Playwright, + spec_file, + path, + spec["title"].as_str().unwrap_or(""), + project_of(test), + ), + image, + }); + } + } + } + for child in suite["suites"].as_array().into_iter().flatten() { + pw_walk(child, path, out); + } + if pushed { + path.pop(); + } +} + +fn playwright(report: &Value) -> Vec { + let mut out = Vec::new(); + for suite in report["suites"].as_array().into_iter().flatten() { + pw_walk(suite, &mut Vec::new(), &mut out); + } + out +} + +/// The same reading as `parse::parse_playwright_html`, so ids match. The +/// attachments' paths are relative to the report (`data/.png`). +fn playwright_html(bytes: &[u8]) -> Vec { + use std::io::Read; + let Some(zip_bytes) = super::parse::html_report_zip(bytes) else { + return Vec::new(); + }; + let Ok(mut zip) = zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)) else { + return Vec::new(); + }; + let limit = super::parse::MAX_REPORT_BYTES as u64; + let mut read = |name: &str| -> Option { + let f = zip.by_name(name).ok()?; + if f.size() > limit { + return None; + } + let mut buf = Vec::new(); + f.take(limit).read_to_end(&mut buf).ok()?; + serde_json::from_slice(&buf).ok() + }; + let Some(report) = read("report.json") else { + return Vec::new(); + }; + let mut out = Vec::new(); + for summary in report["files"].as_array().into_iter().flatten() { + let Some(file) = summary["fileId"] + .as_str() + .and_then(|id| read(&format!("{id}.json"))) + else { + continue; + }; + let file_name = file["fileName"].as_str().unwrap_or(""); + for t in file["tests"].as_array().into_iter().flatten() { + let Some(image) = pw_image(&t["results"]) else { + continue; + }; + let suite: Vec = t["path"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p.as_str().map(str::to_string)) + .collect(); + out.push(Shot { + test_id: test_id( + Framework::Playwright, + t["location"]["file"].as_str().unwrap_or(file_name), + &suite, + t["title"].as_str().unwrap_or(""), + project_of(t), + ), + image, + }); + } + } + out +} + +/// The run's file an image attachment names. `report` is the report's own +/// name in the run's folder, `names` every file there. A relative path is +/// read next to the report; an absolute one (the runner's disk) is the file +/// whose name ends with the most of its trailing folders, at least the +/// image's own folder: every Playwright test writes `test-finished-1.png`, +/// in a folder of its own. +pub fn resolve(report: &str, path: &str, names: &[String]) -> Option { + let p = path.replace('\\', "/"); + if p.split('/').any(|s| s == "..") { + return None; + } + let absolute = p.starts_with('/') || p.get(1..2) == Some(":"); + if !absolute { + let dir = report + .rsplit_once('/') + .map(|(d, _)| format!("{d}/")) + .unwrap_or_default(); + let near = format!("{dir}{}", p.trim_start_matches("./")); + if names.contains(&near) { + return Some(near); + } + } + let segs: Vec<&str> = p.split('/').filter(|s| !s.is_empty()).collect(); + for k in (2..=segs.len()).rev() { + let tail = segs[segs.len() - k..].join("/"); + if let Some(n) = names + .iter() + .find(|n| **n == tail || n.ends_with(&format!("/{tail}"))) + { + return Some(n.clone()); + } + } + None +} + +// ── Which tests show the change ─────────────────────────────────────────── + +/// Why a test's screenshot is shown for a change. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Why { + /// The change edits the test itself. + TestChanged, + /// The repository's test map ties the test's area to a changed file. + Mapped, + /// The test's name shares this word with a changed UI file. + Named(String), +} + +impl Why { + /// Stronger evidence first. + fn rank(&self) -> u8 { + match self { + Why::TestChanged => 0, + Why::Mapped => 1, + Why::Named(_) => 2, + } + } + + pub fn words(&self) -> String { + match self { + Why::TestChanged => "this change edits the test".into(), + Why::Mapped => "the repository's test map ties it to the changed files".into(), + Why::Named(w) => format!("its name and a changed UI file share the word \"{w}\""), + } + } +} + +/// Folder and file names that say nothing about what a file shows. +const GENERIC: &[&str] = &[ + "src", "app", "apps", "lib", "libs", "packages", "package", "components", "component", + "screens", "screen", "pages", "page", "views", "view", "styles", "style", "index", "main", + "common", "shared", "utils", "util", "hooks", "assets", "features", "feature", "layout", + "layouts", "containers", "container", "modules", "module", "default", "mobile", "native", + "client", "public", "test", "tests", "spec", "specs", "e2e", "ui", "tsx", "jsx", "scss", + "css", "vue", "svelte", "html", "styled", "theme", "types", "button", "text", "item", + "list", "card", "modal", +]; + +/// The words of a path or title: split on anything but letters and digits +/// and at camelCase humps, lowercased, at least four letters, none of +/// [`GENERIC`]. +fn words(s: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut cur = String::new(); + let mut prev_lower = false; + let mut push = |w: &mut String| { + let l = w.to_ascii_lowercase(); + if l.len() >= 4 && !GENERIC.contains(&l.as_str()) && !out.contains(&l) { + out.push(l); + } + w.clear(); + }; + for c in s.chars() { + if !c.is_ascii_alphanumeric() { + push(&mut cur); + prev_lower = false; + continue; + } + if c.is_ascii_uppercase() && prev_lower { + push(&mut cur); + } + prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit(); + cur.push(c); + } + push(&mut cur); + out +} + +fn same_file(a: &str, b: &str) -> bool { + let (a, b) = (a.trim_start_matches("./"), b.trim_start_matches("./")); + !a.is_empty() + && !b.is_empty() + && (a == b || a.ends_with(&format!("/{b}")) || b.ends_with(&format!("/{a}"))) +} + +/// Why `t`'s screenshot shows the change to `changed`, if it does. +pub fn why_shown(t: &ParsedTest, changed: &[String], map: Option<&TestMap>) -> Option { + if changed.iter().any(|f| same_file(f, &t.file)) { + return Some(Why::TestChanged); + } + if map.is_some() && !super::triage::related_changes(t, changed, map).is_empty() { + return Some(Why::Mapped); + } + let named = words(&format!("{} {}", t.full_title(), t.file)); + changed + .iter() + .filter(|f| crate::pr_facts::is_ui(f)) + .flat_map(|f| words(f)) + .find(|w| named.contains(w)) + .map(Why::Named) +} + +/// The tests whose screenshots show the change, best first: the tests that +/// passed in the end, a test the change edits before one the test map +/// names, before one that only shares a word. +pub fn pick<'a>( + tests: &'a [ParsedTest], + changed: &[String], + map: Option<&TestMap>, +) -> Vec<(&'a ParsedTest, Why)> { + let mut out: Vec<(&ParsedTest, Why)> = tests + .iter() + .filter(|t| matches!(Outcome::of(&t.attempts), Outcome::Passed | Outcome::Flaky)) + .filter_map(|t| why_shown(t, changed, map).map(|w| (t, w))) + .collect(); + out.sort_by_key(|(_, w)| w.rank()); + out +} + +// ── What the description shows ──────────────────────────────────────────── + +/// One side of the table: the kept image and the run it came from. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Side { + /// The image's key in the install's bucket. + pub key: String, + /// The run's page; empty for an upload with no run page. + #[serde(default)] + pub run_url: String, +} + +/// The screenshots kept for one head of a pull request. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Kept { + pub pr: u64, + /// The test's full title. + pub test: String, + /// Why this test shows the change ([`Why::words`]). + pub why: String, + /// The branch the Before side was taken on. + pub base: String, + /// The test on the base branch, when a run there kept one. + #[serde(default)] + pub before: Option, + /// The test on the head. + pub after: Side, + /// When the links stop working (unix seconds); fixed when kept, so the + /// description is the same text on every rebuild. + pub expires_at: i64, +} + +fn md_link(text: &str, url: &str) -> String { + if url.starts_with("https://") { + format!("[{text}]({url})") + } else { + text.to_string() + } +} + +/// The table for `k`; `link` gives an image's link from its key. +pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Screens { + let test = k.test.replace('`', "'"); + let base: &str = if k.base.is_empty() { + "the base branch" + } else { + &k.base + }; + let (before, before_alt) = match &k.before { + Some(s) => (link(&s.key), format!("{test} on {base}, before this change")), + None => ( + String::new(), + format!("No screenshot of this test on {base} yet"), + ), + }; + let runs = [ + k.before + .as_ref() + .map(|s| md_link(&format!("{base}'s run"), &s.run_url)), + Some(md_link("this head's run", &k.after.run_url)), + ] + .into_iter() + .flatten() + .collect::>() + .join(", "); + crate::pr_body::Screens::Images { + before, + before_alt, + after: link(&k.after.key), + after_alt: format!("{test} on this head"), + caption: format!( + "From the end-to-end test `{test}` ({runs}), shown because {}.", + k.why.trim_end_matches('.') + ), + } +} + +/// The key an image is kept under in the install's bucket. +pub fn object_key(team: &str, repo: &str, pr: u64, sha: &str, side: &str, ext: &str) -> String { + format!( + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{side}.{ext}", + team_folder(team), + sha.get(..12).unwrap_or(sha) + ) +} + +fn team_folder(team: &str) -> String { + team.replace(['#', '/'], "_") +} + +// ── Signed links ────────────────────────────────────────────────────────── + +type HmacSha256 = Hmac; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TokenError { + Malformed, + BadSignature, + Expired, +} + +fn mac(secret: &str, payload: &str) -> HmacSha256 { + // A key for screenshot links only, so a link never stands in for a + // session or for any other signed link. + let mut kdf = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC takes any key"); + kdf.update(b"coderhelm/e2e-screenshot/v1"); + let key = kdf.finalize().into_bytes(); + let mut m = HmacSha256::new_from_slice(&key).expect("HMAC takes any key"); + m.update(payload.as_bytes()); + m +} + +/// A token that reads one kept image of one team until `expires_at`. The +/// token is `base64url(team \n key \n expiry) . base64url(HMAC-SHA256)`. +pub fn sign(secret: &str, team: &str, key: &str, expires_at: i64) -> String { + let payload = format!("{team}\n{key}\n{expires_at}"); + let sig = mac(secret, &payload).finalize().into_bytes(); + format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(payload.as_bytes()), + URL_SAFE_NO_PAD.encode(sig) + ) +} + +/// The image key a token reads, if it is genuine, current, and names one of +/// its own team's kept images. +pub fn verify(secret: &str, token: &str, now: i64) -> Result { + if token.is_empty() || token.len() > MAX_TOKEN_LEN { + return Err(TokenError::Malformed); + } + let (body, sig) = token.split_once('.').ok_or(TokenError::Malformed)?; + let payload = URL_SAFE_NO_PAD + .decode(body) + .ok() + .and_then(|b| String::from_utf8(b).ok()) + .ok_or(TokenError::Malformed)?; + let sig = URL_SAFE_NO_PAD + .decode(sig) + .map_err(|_| TokenError::Malformed)?; + mac(secret, &payload) + .verify_slice(&sig) + .map_err(|_| TokenError::BadSignature)?; + let p: Vec<&str> = payload.split('\n').collect(); + let [team, key, exp] = p.as_slice() else { + return Err(TokenError::Malformed); + }; + let exp: i64 = exp.parse().map_err(|_| TokenError::Malformed)?; + let own = format!("{KEY_PREFIX}/{}/", team_folder(team)); + if team.is_empty() || !key.starts_with(&own) || key.split('/').any(|s| s == "..") { + return Err(TokenError::Malformed); + } + if now >= exp { + return Err(TokenError::Expired); + } + Ok(key.to_string()) +} + +/// The link for a token on this deployment's API. +pub fn url(api: &str, token: &str) -> String { + format!("{}{LINK_PATH}?t={token}", api.trim_end_matches('/')) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::e2e::model::{Attempt, AttemptStatus}; + use serde_json::json; + + const PNG: &[u8] = &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3]; + + fn b64(b: &[u8]) -> String { + STANDARD.encode(b) + } + + fn ids(report: &str, bytes: &[u8]) -> Vec { + let tests = super::super::parse::parse_any(report, bytes, &Default::default()).unwrap(); + tests.iter().map(ParsedTest::id).collect() + } + + #[test] + fn cucumber_embeddings_give_each_scenario_its_last_image_under_the_test_id() { + let report = json!([{ + "uri": "features/checkout.feature", + "name": "Checkout", + "elements": [ + {"type": "background", "name": "", "steps": [ + {"keyword": "Given ", "name": "signed in", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "image/png", "data": b64(PNG)}]} + ]}, + {"type": "scenario", "name": "Pays by card", "steps": [ + {"keyword": "When ", "name": "pay", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "image/png", "data": b64(b"\x89PNG first")}]}, + {"keyword": "Then ", "name": "paid", "result": {"status": "passed"}, + "embeddings": [{"mime_type": "text/plain", "data": b64(b"log")}]} + ], "after": [ + {"keyword": "After", "result": {"status": "passed"}, + "embeddings": [{"media": {"type": "image/png"}, "data": b64(PNG)}]} + ]}, + {"type": "scenario", "name": "No image", "steps": [ + {"keyword": "When ", "name": "x", "result": {"status": "passed"}} + ]} + ] + }]); + let bytes = serde_json::to_vec(&report).unwrap(); + let shots = shots_in("wdio/cucumber.json", &bytes); + assert_eq!(shots.len(), 1); + assert_eq!(shots[0].image, Image::Inline(PNG.to_vec())); + // The id is the one the parser gives the scenario. + assert!(ids("wdio/cucumber.json", &bytes).contains(&shots[0].test_id)); + } + + #[test] + fn playwright_attachments_are_a_body_or_a_file_of_the_last_attempt() { + let report = json!({ + "config": {}, + "suites": [{"title": "home.spec.ts", "file": "home.spec.ts", "specs": [], "suites": [{ + "title": "Home", "file": "home.spec.ts", + "specs": [ + {"title": "shows the hero", "file": "home.spec.ts", "tests": [{ + "projectName": "chromium", + "results": [ + {"retry": 0, "status": "failed", "attachments": [ + {"name": "screenshot", "contentType": "image/png", "path": "/runner/test-results/home-hero/test-failed-1.png"}]}, + {"retry": 1, "status": "passed", "attachments": [ + {"name": "trace", "contentType": "application/zip", "path": "/runner/test-results/home-hero/trace.zip"}, + {"name": "screenshot", "contentType": "image/png", "path": "/runner/test-results/home-hero/test-finished-1.png"}]} + ]}]}, + {"title": "inline", "file": "home.spec.ts", "tests": [{ + "projectName": "chromium", + "results": [{"retry": 0, "status": "passed", "attachments": [ + {"name": "after", "contentType": "image/png", "body": b64(PNG)}]}]}]} + ] + }]}] + }); + let bytes = serde_json::to_vec(&report).unwrap(); + let shots = shots_in("results.json", &bytes); + assert_eq!(shots.len(), 2); + assert_eq!( + shots[0].image, + Image::File("/runner/test-results/home-hero/test-finished-1.png".into()) + ); + assert_eq!(shots[1].image, Image::Inline(PNG.to_vec())); + let parsed = ids("results.json", &bytes); + assert!(shots.iter().all(|s| parsed.contains(&s.test_id))); + } + + #[test] + fn an_attachment_is_found_next_to_its_report_or_by_its_own_folder() { + let names: Vec = [ + "report/index.html", + "report/data/abc.png", + "results/home-hero/test-finished-1.png", + "results/cart-total/test-finished-1.png", + ] + .map(String::from) + .to_vec(); + assert_eq!( + resolve("report/index.html", "data/abc.png", &names).as_deref(), + Some("report/data/abc.png") + ); + assert_eq!( + resolve( + "results/results.json", + "/home/runner/work/app/test-results/cart-total/test-finished-1.png", + &names + ) + .as_deref(), + Some("results/cart-total/test-finished-1.png") + ); + // The file name alone is every test's; it never decides. + assert_eq!( + resolve("r.json", "/elsewhere/test-finished-1.png", &names), + None + ); + assert_eq!(resolve("r.json", "../secret/a.png", &names), None); + } + + fn passed(file: &str, suite: &[&str], title: &str) -> ParsedTest { + ParsedTest { + framework: Framework::Playwright, + file: file.into(), + suite: suite.iter().map(|s| s.to_string()).collect(), + title: title.into(), + project: None, + tags: vec![], + attempts: vec![Attempt { + retry: 0, + status: AttemptStatus::Passed, + duration_ms: 1, + error: None, + trace_url: None, + video_url: None, + screenshot_url: None, + }], + } + } + + #[test] + fn the_test_the_change_edits_comes_before_one_that_shares_a_word() { + let mut failed = passed("e2e/checkout.spec.ts", &["Checkout"], "fails"); + failed.attempts[0].status = AttemptStatus::Failed; + let tests = vec![ + passed("e2e/home.spec.ts", &["Home"], "shows the hero"), + passed("e2e/checkout.spec.ts", &["Checkout"], "pays by card"), + failed, + passed("e2e/profile.spec.ts", &["Profile"], "edits the name"), + ]; + let changed: Vec = [ + "src/screens/Checkout/PayButton.tsx", + "e2e/profile.spec.ts", + "README.md", + ] + .map(String::from) + .to_vec(); + let picked = pick(&tests, &changed, None); + let titles: Vec<&str> = picked.iter().map(|(t, _)| t.title.as_str()).collect(); + assert_eq!(titles, vec!["edits the name", "pays by card"]); + assert_eq!(picked[0].1, Why::TestChanged); + assert_eq!(picked[1].1, Why::Named("checkout".into())); + } + + #[test] + fn generic_folders_and_non_ui_files_never_match() { + let tests = vec![passed("e2e/screens.spec.ts", &["Components"], "index page")]; + let changed: Vec = ["src/components/index.tsx", "src/api/screens.ts"] + .map(String::from) + .to_vec(); + assert!(pick(&tests, &changed, None).is_empty()); + } + + #[test] + fn words_split_camel_case_and_drop_short_and_generic_ones() { + assert_eq!( + words("src/screens/CheckoutSummary/PayButton.tsx"), + vec!["checkout", "summary"] + ); + } + + #[test] + fn the_table_names_the_test_its_runs_and_why() { + let k = Kept { + pr: 7, + test: "Checkout › pays by `card`".into(), + why: Why::Named("checkout".into()).words(), + base: "main".into(), + before: Some(Side { + key: "e2e-shots/T/o/r/7/abc/before.png".into(), + run_url: "https://github.com/o/r/actions/runs/1".into(), + }), + after: Side { + key: "e2e-shots/T/o/r/7/abc/after.png".into(), + run_url: "https://github.com/o/r/actions/runs/2".into(), + }, + expires_at: 10, + }; + let s = screens(&k, |key| format!("https://api.example.com/x?k={key}")); + let crate::pr_body::Screens::Images { + before, + after, + caption, + after_alt, + .. + } = s + else { + panic!("images"); + }; + assert!(before.ends_with("before.png")); + assert!(after.ends_with("after.png")); + assert_eq!(after_alt, "Checkout › pays by 'card' on this head"); + assert_eq!( + caption, + "From the end-to-end test `Checkout › pays by 'card'` ([main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)), shown because its name and a changed UI file share the word \"checkout\"." + ); + let none = screens( + &Kept { + before: None, + ..k.clone() + }, + |key| key.to_string(), + ); + let crate::pr_body::Screens::Images { + before, before_alt, .. + } = none + else { + panic!("images"); + }; + assert!(before.is_empty()); + assert_eq!(before_alt, "No screenshot of this test on main yet"); + } + + #[test] + fn a_link_reads_one_image_of_its_own_team_until_it_expires() { + let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "after", "png"); + assert_eq!(key, "e2e-shots/TEAM_a/o/r/7/0123456789ab/after.png"); + let t = sign("s", "TEAM#a", &key, 100); + assert_eq!(verify("s", &t, 99), Ok(key.clone())); + assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); + assert_eq!(verify("other", &t, 99), Err(TokenError::BadSignature)); + // Signed, but for another team's image or anything else in the bucket. + let theirs = sign("s", "TEAM#a", "e2e-shots/TEAM_b/o/r/1/x/after.png", 100); + assert_eq!(verify("s", &theirs, 99), Err(TokenError::Malformed)); + let raw = sign("s", "TEAM#a", "e2e/TEAM_a/o/r/raw/1-1/report.json", 100); + assert_eq!(verify("s", &raw, 99), Err(TokenError::Malformed)); + let up = sign("s", "TEAM#a", "e2e-shots/TEAM_a/../../secret", 100); + assert_eq!(verify("s", &up, 99), Err(TokenError::Malformed)); + // An unsubscribe token never reads an image. + let u = crate::unsubscribe::sign("s", "TEAM#a", "USER#1", "weekly_summary", 100); + assert!(verify("s", &u, 99).is_err()); + assert!(url("https://api.example.com/", &t) + .starts_with("https://api.example.com/webhooks/ci/tests/screenshot?t=")); + } + + #[test] + fn only_real_images_are_kept() { + assert_eq!(image_type(PNG), Some("image/png")); + assert_eq!(image_type(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg")); + assert_eq!(image_type(b""), None); + assert_eq!(decoded(&b64(b"")), None); + } +} diff --git a/services/common/src/pr_body.rs b/services/common/src/pr_body.rs index bdb6c3037..7435e4c37 100644 --- a/services/common/src/pr_body.rs +++ b/services/common/src/pr_body.rs @@ -228,11 +228,16 @@ impl Row { /// The screenshots of a UI change, or why there are none. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum Screens { + /// One Before and After pair. An empty `before` is a side with no + /// image: its cell says `before_alt` instead. Images { before: String, before_alt: String, after: String, after_alt: String, + /// One line under the table: where the images came from. + #[serde(default)] + caption: String, }, /// One line: why there is no screenshot. Missing(String), @@ -798,19 +803,28 @@ fn screens_markdown(s: &Screens) -> String { before_alt, after, after_alt, + caption, } => { let img = |src: &str, alt: &str| { + if src.trim().is_empty() { + return cell(&one_line(alt)); + } format!( "\"{}\"", src.replace('"', "%22"), one_line(alt).replace('"', "'") ) }; - format!( + let mut s = format!( "| Before | After |\n|---|---|\n| {} | {} |", img(before, before_alt), img(after, after_alt) - ) + ); + let caption = one_line(caption); + if !caption.is_empty() { + s.push_str(&format!("\n\n{caption}")); + } + s } Screens::Missing(why) => format!("No screenshot: {}.", part(why)), Screens::Pages(pages) => { diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index fc27eeb40..c9242f981 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1620,6 +1620,9 @@ fn build_app(state: Arc) -> Router { // CI calls signed with a GitHub Actions OIDC token .route("/ci/tests/results", post(routes::tests::ci_upload)) .route("/ci/tests/quarantine", get(routes::tests::ci_quarantine)) + // A screenshot in the Before and After table of CoderHelm's own pull + // request; the signed link is the credential (routes::tests). + .route("/ci/tests/screenshot", get(routes::tests::ci_screenshot)) // Events CoderHelm's relay forwards to a hybrid install, and its // ownership proof (routes::hybrid_install). .route("/relay", post(routes::hybrid_install::intake)) diff --git a/services/gateway/src/routes/tests.rs b/services/gateway/src/routes/tests.rs index 44bdbb1a9..4fec457c2 100644 --- a/services/gateway/src/routes/tests.rs +++ b/services/gateway/src/routes/tests.rs @@ -1382,6 +1382,66 @@ pub async fn ci_quarantine( })) } +#[derive(Deserialize)] +pub struct ShotQuery { + #[serde(default)] + t: String, +} + +/// GET /webhooks/ci/tests/screenshot?t= — one end-to-end screenshot kept for +/// the Before and After table of CoderHelm's own pull request +/// (`common::e2e::shots`). Public, because GitHub fetches the image for the +/// pull request's readers: the signed token is the credential, and it names +/// one image of one team until it expires. Anything else is a 404 that says +/// nothing. +pub async fn ci_screenshot( + State(state): State>, + Query(q): Query, +) -> axum::response::Response { + use axum::http::header; + use axum::response::IntoResponse; + use common::e2e::shots; + let not_found = || (StatusCode::NOT_FOUND, "Not found").into_response(); + let secret = state.secrets.jwt_secret.as_str(); + if secret.is_empty() { + return not_found(); + } + let key = match shots::verify(secret, q.t.trim(), chrono::Utc::now().timestamp()) { + Ok(k) => k, + Err(e) => { + info!(reason = ?e, "Screenshot link refused"); + return not_found(); + } + }; + let Ok(obj) = state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(&key) + .send() + .await + else { + return not_found(); + }; + let Ok(body) = obj.body.collect().await else { + return not_found(); + }; + let bytes = body.into_bytes(); + let Some(content_type) = shots::image_type(&bytes) else { + return not_found(); + }; + ( + StatusCode::OK, + [ + (header::CONTENT_TYPE, content_type), + (header::CACHE_CONTROL, "public, max-age=86400"), + (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), + ], + bytes, + ) + .into_response() +} + #[cfg(test)] mod unit { use super::*; diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index ec53e3ebd..03ac81ee4 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -550,6 +550,25 @@ pub async fn rebuild( .await } +/// [`rebuild`] for a pull request, its ticket read from the run that opened +/// it: something its description shows arrived on the same head (the +/// screenshots of the end-to-end run, `e2e_screens`). +pub async fn rebuild_pr( + state: &WorkerState, + github: &GitHubClient, + team_id: &str, + owner: &str, + repo: &str, + number: u64, +) -> Reconciled { + let ticket = match super::review_pr::lookup_run_by_pr(state, team_id, owner, repo, number).await + { + Some(run_id) => run_ticket(state, team_id, &run_id).await, + None => String::new(), + }; + rebuild(state, github, team_id, owner, repo, number, &ticket).await +} + /// What was read about a pull request for one build. struct Gathered { pr: serde_json::Value, @@ -558,6 +577,9 @@ struct Gathered { checks: Option>, run: RunBits, run_url: String, + /// The Before and After table the end-to-end run on the head filled + /// (`e2e_screens`). + screens: Option, } /// What the run behind a pull request holds for its description. @@ -645,6 +667,9 @@ impl Gathered { super::description_facts::with_two_way(&mut f, &self.run.two_way); super::description_facts::with_scope(&mut f, self.run.scope.as_ref(), &self.files); f.waiting = self.run.waiting.clone(); + if self.screens.is_some() { + f.screens = self.screens.clone(); + } f } } @@ -781,6 +806,11 @@ async fn gather( } else { format!("{app}/runs/detail?id={run_id}") }; + let screens = if head.is_empty() { + None + } else { + super::e2e_screens::screens_for(state, team_id, &format!("{owner}/{repo}"), &head).await + }; Ok(Gathered { pr, files, @@ -788,6 +818,7 @@ async fn gather( checks, run, run_url, + screens, }) } diff --git a/services/worker/src/passes/description_eval.rs b/services/worker/src/passes/description_eval.rs index ee9372991..4a314aa34 100644 --- a/services/worker/src/passes/description_eval.rs +++ b/services/worker/src/passes/description_eval.rs @@ -682,6 +682,7 @@ pub fn ui_facts() -> Facts { before_alt: "Sub Title field with a 190-character subtitle and no warning".into(), after: "https://github.com/user-attachments/assets/after-example".into(), after_alt: "Same field showing the warning 'Over 160 characters (190)'".into(), + caption: String::new(), }), run_url: "https://app.example.com/runs/detail?id=run-4812".into(), repo_url: "https://github.com/acme/site".into(), diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index b3d55beb8..ca7a1e5a9 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -622,10 +622,30 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { if run.rescued { note_rescued(&st, &gh, &msg, &run, pr).await; } + let own = is_own_pr(&gh, &msg, pr).await; // A run that failed only on quarantined tests needs no fix or re-run. - if failed > 0 && !run.rescued && is_own_pr(&gh, &msg, pr).await { + if failed > 0 && !run.rescued && own { own_pr_failures(state, &gh, &msg, &run, pr, &lines, &tests).await; } + // CoderHelm's own pull request shows the screenshots this run took + // of the tests its change touches. + if own { + super::e2e_screens::keep( + state, + &gh, + &st, + super::e2e_screens::Head { + msg: &msg, + pr, + tests: &tests, + reports: &reports, + changed: &changed, + map: map.as_ref(), + }, + |t| scoped_id(&repo, t), + ) + .await; + } recommend_from_pr(state, &gh, &msg, pr, &changed, map.as_ref()).await; follow_generated(state, &gh, &msg, &run, &tests).await; } diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs new file mode 100644 index 000000000..4bc649b14 --- /dev/null +++ b/services/worker/src/passes/e2e_screens.rs @@ -0,0 +1,426 @@ +//! The Before and After table of CoderHelm's own pull request, filled from +//! the screenshots its end-to-end run took (the rules are +//! `common::e2e::shots`). +//! +//! When a run on the pull request's head is read (`e2e::ingest`), the +//! tests that show the change are chosen ([`shots::pick`]), and the first +//! one with a screenshot on the head is kept with its screenshot from the +//! newest passing run on the default branch, when one is kept there too. +//! The images go to the install's own bucket, the record to the settings +//! table for the head, and the description is rebuilt: its table links each +//! image through the API with a signed link that expires +//! ([`screens_for`]). A head keeps the first pair found; a later run on the +//! same head changes nothing. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::e2e::coverage::TestMap; +use common::e2e::messages::TestIngest; +use common::e2e::model::{Outcome, ParsedTest}; +use common::e2e::report_source::Location; +use common::e2e::shots::{self, Image, Kept, Side}; +use common::e2e::store::Store; +use tracing::{info, warn}; + +use super::test_fix::{CiReports, KeptRun, Reports, S3Reports}; +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// Tests tried for a screenshot on the head. +const MAX_TRIED: usize = 3; +/// How long the record of a head is kept. +const RECORD_DAYS: i64 = 90; + +fn record_sk(repo: &str, sha: &str) -> String { + format!("E2E_SHOTS#{repo}#{sha}") +} + +pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> Option { + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&record_sk(repo, sha))) + .send() + .await + .ok()? + .item?; + serde_json::from_str(item.get("data")?.as_s().ok()?).ok() +} + +async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) { + let ttl = (chrono::Utc::now() + chrono::Duration::days(RECORD_DAYS)).timestamp(); + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", super::attr_s(team_id)) + .item("sk", super::attr_s(&record_sk(repo, sha))) + .item( + "data", + super::attr_s(&serde_json::to_string(k).unwrap_or_default()), + ) + .item("ttl", AttributeValue::N(ttl.to_string())) + .send() + .await + { + warn!(error = %e, "Could not save the end-to-end screenshots of a head"); + } +} + +/// The Before and After table for a pull request's head, when a run on it +/// kept screenshots. `None` without a signing secret or a public API +/// address: GitHub fetches the images from the API, so a link must reach +/// it. +pub async fn screens_for( + state: &WorkerState, + team_id: &str, + repo: &str, + sha: &str, +) -> Option { + let secret = state.secrets.jwt_secret.as_str(); + let api = common::public_urls::api_url(&state.config.stage); + if secret.is_empty() || !api.starts_with("https://") { + return None; + } + let k = load(state, team_id, repo, sha).await?; + Some(shots::screens(&k, |key| { + shots::url(api, &shots::sign(secret, team_id, key, k.expires_at)) + })) +} + +/// Report files held in memory: an uploaded report, or the raw reports kept +/// in the install's bucket for an upload. +struct Held(Vec<(String, Vec)>); + +#[async_trait::async_trait] +impl Reports for Held { + fn label(&self, _run_id: u64, _attempt: u32) -> String { + "the uploaded report".into() + } + + async fn runs(&self) -> Vec { + Vec::new() + } + + async fn reports(&self, _run_id: u64, _attempt: u32) -> Result)>, String> { + Ok(self.0.clone()) + } + + async fn file(&self, _run_id: u64, _attempt: u32, path: &str) -> Option> { + self.0 + .iter() + .find(|(n, _)| n == path) + .map(|(_, b)| b.clone()) + } + + async fn names(&self, _run_id: u64, _attempt: u32) -> Vec { + self.0.iter().map(|(n, _)| n.clone()).collect() + } +} + +/// Where one run's reports are read. +enum Source<'a> { + Held(Held), + S3(Box), + Ci(CiReports<'a>), +} + +impl Source<'_> { + fn reports(&self) -> &dyn Reports { + match self { + Source::Held(r) => r, + Source::S3(r) => r.as_ref(), + Source::Ci(r) => r, + } + } +} + +/// The raw reports kept in the install's bucket for an uploaded run +/// (`e2e::ingest` keeps them within a budget). +async fn kept_raw(state: &WorkerState, team_id: &str, repo: &str, run_key: &str) -> Held { + let marker = common::e2e::store::raw_report_key(team_id, repo, run_key, "x"); + let prefix = marker.trim_end_matches('x').to_string(); + let mut out = Vec::new(); + let Ok(listed) = state + .s3 + .list_objects_v2() + .bucket(&state.config.bucket_name) + .prefix(&prefix) + .max_keys(20) + .send() + .await + else { + return Held(out); + }; + for o in listed.contents() { + let (Some(key), size) = (o.key(), o.size().unwrap_or(0)) else { + continue; + }; + if size < 0 || size as usize > common::e2e::parse::MAX_REPORT_BYTES { + continue; + } + let Ok(obj) = state + .s3 + .get_object() + .bucket(&state.config.bucket_name) + .key(key) + .send() + .await + else { + continue; + }; + if let Ok(body) = obj.body.collect().await { + let name = key.strip_prefix(&prefix).unwrap_or(key).to_string(); + out.push((name, body.into_bytes().to_vec())); + } + } + Held(out) +} + +/// `{run_id}-{attempt}`, the key of a run read from GitHub. +fn run_of(run_key: &str) -> Option<(u64, u32)> { + let (run, attempt) = run_key.split_once('-')?; + Some((run.parse().ok()?, attempt.parse().ok()?)) +} + +/// The screenshots of `wanted` (test ids) in one run, by test id. +async fn images( + r: &dyn Reports, + run_id: u64, + attempt: u32, + wanted: &[String], +) -> HashMap> { + let mut out = HashMap::new(); + let Ok(files) = r.reports(run_id, attempt).await else { + return out; + }; + let mut names: Option> = None; + for (name, bytes) in &files { + for s in shots::shots_in(name, bytes) { + if !wanted.contains(&s.test_id) { + continue; + } + let image = match s.image { + Image::Inline(b) => Some(b), + Image::File(p) => { + if names.is_none() { + names = Some(r.names(run_id, attempt).await); + } + match shots::resolve(name, &p, names.as_deref().unwrap_or_default()) { + Some(n) => r.file(run_id, attempt, &n).await, + None => None, + } + } + }; + if let Some(b) = + image.filter(|b| b.len() <= shots::MAX_IMAGE && shots::image_type(b).is_some()) + { + out.insert(s.test_id, b); + } + } + } + out +} + +/// Keeps one image in the install's bucket; its key. +async fn put(state: &WorkerState, key_of: impl Fn(&str) -> String, bytes: Vec) -> Option { + let content_type = shots::image_type(&bytes)?; + let key = key_of(shots::extension(content_type)); + match state + .s3 + .put_object() + .bucket(&state.config.bucket_name) + .key(&key) + .content_type(content_type) + .body(bytes.into()) + .send() + .await + { + Ok(_) => Some(key), + Err(e) => { + warn!(error = %e, "Could not keep an end-to-end screenshot"); + None + } + } +} + +/// Everything a run on a pull request's head brings for its table. +pub struct Head<'a> { + pub msg: &'a TestIngest, + pub pr: u64, + pub tests: &'a [ParsedTest], + /// The reports this run was read from (an upload's report). + pub reports: &'a [(String, Vec)], + /// The files the pull request changes. + pub changed: &'a [String], + pub map: Option<&'a TestMap>, +} + +/// Keeps the screenshots that show the change of CoderHelm's own pull +/// request from one run on its head, and rebuilds its description with +/// them. `scoped` is a test's id in the store. +pub async fn keep( + state: &WorkerState, + gh: &GitHubClient, + st: &Store<'_>, + h: Head<'_>, + scoped: impl Fn(&ParsedTest) -> String, +) { + let msg = h.msg; + let (owner, name) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); + let repo = format!("{owner}/{name}"); + if state.secrets.jwt_secret.is_empty() || msg.head_sha.is_empty() { + return; + } + let picked = shots::pick(h.tests, h.changed, h.map); + if picked.is_empty() || load(state, &msg.team_id, &repo, &msg.head_sha).await.is_some() { + return; + } + let location = st + .settings(&msg.team_id) + .await + .ok() + .and_then(|s| s.report_source(&repo).and_then(|r| r.location().ok())); + let location = location.as_ref(); + // Where the team keeps the repository's reports, else the run's + // artifacts: the same places the failure attribution reads. + let open = |run_id: u64| async move { + if let Some(l @ Location::S3 { .. }) = location { + let mut tried = Vec::new(); + if let Some(r) = super::test_fix::open_s3(state, &msg.team_id, l, &mut tried).await { + return Source::S3(Box::new(r)); + } + } + Source::Ci(CiReports::new(gh, owner, name, vec![(run_id, 1)])) + }; + // The head's run. + let head = if msg.upload_key.is_some() { + Source::Held(Held(h.reports.to_vec())) + } else { + open(msg.run_id).await + }; + let tried: Vec<&(&ParsedTest, shots::Why)> = picked.iter().take(MAX_TRIED).collect(); + let ids: Vec = tried.iter().map(|(t, _)| t.id()).collect(); + let mut after = images(head.reports(), msg.run_id, msg.run_attempt, &ids).await; + let Some((t, why, after_bytes)) = tried + .into_iter() + .find_map(|(t, w)| after.remove(&t.id()).map(|b| (*t, w, b))) + else { + info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); + return; + }; + // The same test on the default branch: its newest passing run there. + let newest = st + .record(&msg.team_id, &scoped(t)) + .await + .ok() + .flatten() + .and_then(|r| { + r.history.into_iter().rev().find(|e| { + e.branch == msg.default_branch + && !e.bad_run + && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) + }) + }); + let mut before: Option<(Vec, String)> = None; + if let Some(e) = newest { + let (src, run_id, attempt, run_url) = if e.run_key.starts_with("up-") { + ( + Source::Held(kept_raw(state, &msg.team_id, &repo, &e.run_key).await), + 0, + 1, + String::new(), + ) + } else if let Some((run_id, attempt)) = run_of(&e.run_key) { + ( + open(run_id).await, + run_id, + attempt, + format!("https://github.com/{repo}/actions/runs/{run_id}"), + ) + } else { + (Source::Held(Held(Vec::new())), 0, 1, String::new()) + }; + before = images(src.reports(), run_id, attempt, &[t.id()]) + .await + .remove(&t.id()) + .map(|b| (b, run_url)); + } + let key_of = |side: &'static str| { + let (team, pr, sha) = (msg.team_id.clone(), h.pr, msg.head_sha.clone()); + let repo = repo.clone(); + move |ext: &str| shots::object_key(&team, &repo, pr, &sha, side, ext) + }; + let Some(after_key) = put(state, key_of("after"), after_bytes).await else { + return; + }; + let before = match before { + Some((b, run_url)) => put(state, key_of("before"), b) + .await + .map(|key| Side { key, run_url }), + None => None, + }; + let kept = Kept { + pr: h.pr, + test: t.full_title(), + why: why.words(), + base: msg.default_branch.clone(), + before, + after: Side { + key: after_key, + run_url: msg.html_url.clone(), + }, + expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, + }; + save(state, &msg.team_id, &repo, &msg.head_sha, &kept).await; + info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); + if let super::description::Reconciled::Failed(why) = + super::description::rebuild_pr(state, gh, &msg.team_id, owner, name, h.pr).await + { + warn!(repo = %repo, pr = h.pr, why, "The description was not rebuilt with the screenshots; the next rebuild shows them"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_github_run_key_names_its_run_and_attempt() { + assert_eq!(run_of("123-2"), Some((123, 2))); + assert_eq!(run_of("up-1-1-abcdef"), None); + assert_eq!(run_of("nope"), None); + } + + #[tokio::test] + async fn an_attachment_is_read_from_the_file_its_report_names() { + let png = vec![0x89, b'P', b'N', b'G', 0, 1]; + let report = serde_json::json!({ + "config": {}, + "suites": [{"title": "a.spec.ts", "file": "a.spec.ts", "specs": [ + {"title": "shows it", "file": "a.spec.ts", "tests": [{"results": [ + {"status": "passed", "attachments": [ + {"name": "screenshot", "contentType": "image/png", + "path": "/runner/work/test-results/a-shows-it/test-finished-1.png"}]}]}]} + ]}] + }); + let held = Held(vec![ + ("pw/results.json".into(), serde_json::to_vec(&report).unwrap()), + ("pw/test-results/a-shows-it/test-finished-1.png".into(), png.clone()), + ]); + let tests = common::e2e::parse::parse_any( + "results.json", + &serde_json::to_vec(&report).unwrap(), + &Default::default(), + ) + .unwrap(); + let id = tests[0].id(); + let got = images(&held, 1, 1, &[id.clone()]).await; + assert_eq!(got.get(&id), Some(&png)); + // A test nobody asked for is not read. + assert!(images(&held, 1, 1, &["other".into()]).await.is_empty()); + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index d09b4c4c7..d593c7c34 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1279,6 +1279,7 @@ pub mod e2e_attribution; /// preview before the pull request is called done. pub(crate) mod e2e_proof; pub mod e2e_reads; +pub mod e2e_screens; pub mod e2e_setup; pub mod email_events; mod explore_guard; diff --git a/services/worker/src/passes/test_fix.rs b/services/worker/src/passes/test_fix.rs index bdc15a028..9e17506d7 100644 --- a/services/worker/src/passes/test_fix.rs +++ b/services/worker/src/passes/test_fix.rs @@ -367,6 +367,12 @@ pub trait Reports: Send + Sync { async fn reports(&self, run_id: u64, attempt: u32) -> Result)>, String>; /// One file of the run's folder (an attachment of an HTML report). async fn file(&self, run_id: u64, attempt: u32, path: &str) -> Option>; + /// Every file of the run's folder, by the path [`Reports::file`] + /// reads: where a report's attachment is found when the report wrote + /// the runner's own path (`e2e_screens`). + async fn names(&self, _run_id: u64, _attempt: u32) -> Vec { + Vec::new() + } } /// What one run's reports say. @@ -694,6 +700,17 @@ impl Reports for S3Reports { .map(|(_, s, _)| *s)?; self.get(&key, size).await } + + async fn names(&self, run_id: u64, attempt: u32) -> Vec { + let attempt = self.attempt_for(run_id, attempt); + let prefix = self.run_prefix(run_id, attempt); + self.index + .get(&(run_id, attempt)) + .into_iter() + .flatten() + .map(|(k, _, _)| k.strip_prefix(&prefix).unwrap_or(k).to_string()) + .collect() + } } /// Reports in a run's GitHub Actions artifacts. @@ -837,6 +854,13 @@ impl Reports for CiReports<'_> { .find(|(n, _)| n == path) .map(|(_, b)| b) } + + async fn names(&self, run_id: u64, _attempt: u32) -> Vec { + self.files(run_id) + .await + .map(|f| f.into_iter().map(|(n, _)| n).collect()) + .unwrap_or_default() + } } /// The team's AWS session that can read `location`: the first connected From db43e67bf370de45696e94af9c10cc0112dce7db Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:50:44 -0500 Subject: [PATCH 25/32] Say why a screenshot's test was picked, and pass clippy The reason names the test, not only its name (the match reads its title and file); an empty Before cell says no passing run on the base kept one rather than "yet"; the caption gives the reason before the run links. Formatted, and two iterator and one slice lint fixed. --- services/common/src/e2e/shots.rs | 95 ++++++++++++++++++----- services/worker/src/passes/e2e_screens.rs | 24 ++++-- 2 files changed, 96 insertions(+), 23 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 1d323f61b..0068f2a6f 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -105,9 +105,9 @@ pub fn shots_in(name: &str, bytes: &[u8]) -> Vec { } else if lower.ends_with(".json") { match serde_json::from_slice::(bytes) { Ok(v) if v.get("suites").is_some() && v.get("config").is_some() => playwright(&v), - Ok(v) if v - .as_array() - .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => + Ok(v) + if v.as_array() + .is_some_and(|a| a.iter().any(|f| f.get("elements").is_some())) => { cucumber(&v) } @@ -159,7 +159,7 @@ fn cucumber(report: &Value) -> Vec { ) }) .filter_map(|e| e["data"].as_str().and_then(decoded)) - .last(); + .next_back(); if let Some(bytes) = last { out.push(Shot { test_id: test_id( @@ -191,7 +191,7 @@ fn pw_image(results: &Value) -> Option { (_, Some(p)) if !p.is_empty() && !p.contains("..") => Some(Image::File(p.to_string())), _ => None, }) - .last() + .next_back() } fn project_of(test: &Value) -> Option<&str> { @@ -358,20 +358,73 @@ impl Why { match self { Why::TestChanged => "this change edits the test".into(), Why::Mapped => "the repository's test map ties it to the changed files".into(), - Why::Named(w) => format!("its name and a changed UI file share the word \"{w}\""), + Why::Named(w) => format!("the test and a changed UI file share the word \"{w}\""), } } } /// Folder and file names that say nothing about what a file shows. const GENERIC: &[&str] = &[ - "src", "app", "apps", "lib", "libs", "packages", "package", "components", "component", - "screens", "screen", "pages", "page", "views", "view", "styles", "style", "index", "main", - "common", "shared", "utils", "util", "hooks", "assets", "features", "feature", "layout", - "layouts", "containers", "container", "modules", "module", "default", "mobile", "native", - "client", "public", "test", "tests", "spec", "specs", "e2e", "ui", "tsx", "jsx", "scss", - "css", "vue", "svelte", "html", "styled", "theme", "types", "button", "text", "item", - "list", "card", "modal", + "src", + "app", + "apps", + "lib", + "libs", + "packages", + "package", + "components", + "component", + "screens", + "screen", + "pages", + "page", + "views", + "view", + "styles", + "style", + "index", + "main", + "common", + "shared", + "utils", + "util", + "hooks", + "assets", + "features", + "feature", + "layout", + "layouts", + "containers", + "container", + "modules", + "module", + "default", + "mobile", + "native", + "client", + "public", + "test", + "tests", + "spec", + "specs", + "e2e", + "ui", + "tsx", + "jsx", + "scss", + "css", + "vue", + "svelte", + "html", + "styled", + "theme", + "types", + "button", + "text", + "item", + "list", + "card", + "modal", ]; /// The words of a path or title: split on anything but letters and digits @@ -494,10 +547,13 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree &k.base }; let (before, before_alt) = match &k.before { - Some(s) => (link(&s.key), format!("{test} on {base}, before this change")), + Some(s) => ( + link(&s.key), + format!("{test} on {base}, before this change"), + ), None => ( String::new(), - format!("No screenshot of this test on {base} yet"), + format!("No screenshot of this test from a passing run on {base}"), ), }; let runs = [ @@ -516,7 +572,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree after: link(&k.after.key), after_alt: format!("{test} on this head"), caption: format!( - "From the end-to-end test `{test}` ({runs}), shown because {}.", + "Screenshots of the end-to-end test `{test}`, chosen because {}: {runs}.", k.why.trim_end_matches('.') ), } @@ -816,7 +872,7 @@ mod tests { assert_eq!(after_alt, "Checkout › pays by 'card' on this head"); assert_eq!( caption, - "From the end-to-end test `Checkout › pays by 'card'` ([main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)), shown because its name and a changed UI file share the word \"checkout\"." + "Screenshots of the end-to-end test `Checkout › pays by 'card'`, chosen because the test and a changed UI file share the word \"checkout\": [main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)." ); let none = screens( &Kept { @@ -832,7 +888,10 @@ mod tests { panic!("images"); }; assert!(before.is_empty()); - assert_eq!(before_alt, "No screenshot of this test on main yet"); + assert_eq!( + before_alt, + "No screenshot of this test from a passing run on main" + ); } #[test] diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 4bc649b14..5c339c2d3 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -226,7 +226,11 @@ async fn images( } /// Keeps one image in the install's bucket; its key. -async fn put(state: &WorkerState, key_of: impl Fn(&str) -> String, bytes: Vec) -> Option { +async fn put( + state: &WorkerState, + key_of: impl Fn(&str) -> String, + bytes: Vec, +) -> Option { let content_type = shots::image_type(&bytes)?; let key = key_of(shots::extension(content_type)); match state @@ -276,7 +280,11 @@ pub async fn keep( return; } let picked = shots::pick(h.tests, h.changed, h.map); - if picked.is_empty() || load(state, &msg.team_id, &repo, &msg.head_sha).await.is_some() { + if picked.is_empty() + || load(state, &msg.team_id, &repo, &msg.head_sha) + .await + .is_some() + { return; } let location = st @@ -408,8 +416,14 @@ mod tests { ]}] }); let held = Held(vec![ - ("pw/results.json".into(), serde_json::to_vec(&report).unwrap()), - ("pw/test-results/a-shows-it/test-finished-1.png".into(), png.clone()), + ( + "pw/results.json".into(), + serde_json::to_vec(&report).unwrap(), + ), + ( + "pw/test-results/a-shows-it/test-finished-1.png".into(), + png.clone(), + ), ]); let tests = common::e2e::parse::parse_any( "results.json", @@ -418,7 +432,7 @@ mod tests { ) .unwrap(); let id = tests[0].id(); - let got = images(&held, 1, 1, &[id.clone()]).await; + let got = images(&held, 1, 1, std::slice::from_ref(&id)).await; assert_eq!(got.get(&id), Some(&png)); // A test nobody asked for is not read. assert!(images(&held, 1, 1, &["other".into()]).await.is_empty()); From f3c39c04e58fb4bf3dec05797efe0043f0738d3e Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:57:40 -0500 Subject: [PATCH 26/32] no-mistakes(review): Claim head record, use PR base, align record TTL --- services/common/src/e2e/shots.rs | 89 ++++++++++++++-- services/worker/src/passes/e2e_screens.rs | 124 ++++++++++++++-------- 2 files changed, 159 insertions(+), 54 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 0068f2a6f..d05e6cb43 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -24,10 +24,10 @@ use base64::Engine; use hmac::{Hmac, Mac}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use sha2::Sha256; +use sha2::{Digest, Sha256}; use super::coverage::TestMap; -use super::model::{test_id, Framework, Outcome, ParsedTest}; +use super::model::{test_id, Framework, HistoryEntry, Outcome, ParsedTest}; /// Largest image kept. pub const MAX_IMAGE: usize = 5 * 1024 * 1024; @@ -553,7 +553,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree ), None => ( String::new(), - format!("No screenshot of this test from a passing run on {base}"), + format!("No passing run on {base} with a screenshot of this test yet"), ), }; let runs = [ @@ -578,12 +578,31 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree } } -/// The key an image is kept under in the install's bucket. -pub fn object_key(team: &str, repo: &str, pr: u64, sha: &str, side: &str, ext: &str) -> String { +/// The newest run of a test on `branch` that passed: where its Before +/// screenshot is read. +pub fn newest_passing<'a>(history: &'a [HistoryEntry], branch: &str) -> Option<&'a HistoryEntry> { + history.iter().rev().find(|e| { + e.branch == branch && !e.bad_run && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) + }) +} + +/// The key an image of test `test` is kept under in the install's bucket; +/// two tests never share one. +pub fn object_key( + team: &str, + repo: &str, + pr: u64, + sha: &str, + test: &str, + side: &str, + ext: &str, +) -> String { + let test = hex::encode(Sha256::digest(test.as_bytes())); format!( - "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{side}.{ext}", + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{}/{side}.{ext}", team_folder(team), - sha.get(..12).unwrap_or(sha) + sha.get(..12).unwrap_or(sha), + &test[..16] ) } @@ -890,14 +909,22 @@ mod tests { assert!(before.is_empty()); assert_eq!( before_alt, - "No screenshot of this test from a passing run on main" + "No passing run on main with a screenshot of this test yet" ); } #[test] fn a_link_reads_one_image_of_its_own_team_until_it_expires() { - let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "after", "png"); - assert_eq!(key, "e2e-shots/TEAM_a/o/r/7/0123456789ab/after.png"); + let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "t", "after", "png"); + // sha256("t") = e3b98a4da31a127d... + assert_eq!( + key, + "e2e-shots/TEAM_a/o/r/7/0123456789ab/e3b98a4da31a127d/after.png" + ); + assert_ne!( + key, + object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "u", "after", "png") + ); let t = sign("s", "TEAM#a", &key, 100); assert_eq!(verify("s", &t, 99), Ok(key.clone())); assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); @@ -916,6 +943,48 @@ mod tests { .starts_with("https://api.example.com/webhooks/ci/tests/screenshot?t=")); } + #[test] + fn before_comes_from_the_newest_passing_run_on_the_pull_requests_base() { + let e = |run: &str, branch: &str, outcome, bad_run| HistoryEntry { + run_key: run.into(), + sha: "s".into(), + branch: branch.into(), + pr: None, + at: "t".into(), + outcome, + bad_run, + attempts: vec![], + }; + let history = vec![ + e("1-1", "develop", Outcome::Passed, false), + e("2-1", "develop", Outcome::Failed, false), + e("3-1", "develop", Outcome::Passed, true), + e("4-1", "main", Outcome::Passed, false), + ]; + // A pull request into develop never shows main's newer run. + assert_eq!( + newest_passing(&history, "develop").map(|e| e.run_key.as_str()), + Some("1-1") + ); + assert_eq!( + newest_passing(&history, "main").map(|e| e.run_key.as_str()), + Some("4-1") + ); + assert_eq!(newest_passing(&history, "release"), None); + let k = Kept { + base: "develop".into(), + ..Default::default() + }; + let crate::pr_body::Screens::Images { before_alt, .. } = screens(&k, |key| key.into()) + else { + panic!("images"); + }; + assert_eq!( + before_alt, + "No passing run on develop with a screenshot of this test yet" + ); + } + #[test] fn only_real_images_are_kept() { assert_eq!(image_type(PNG), Some("image/png")); diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 5c339c2d3..833d9ebbc 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -5,11 +5,13 @@ //! When a run on the pull request's head is read (`e2e::ingest`), the //! tests that show the change are chosen ([`shots::pick`]), and the first //! one with a screenshot on the head is kept with its screenshot from the -//! newest passing run on the default branch, when one is kept there too. +//! newest passing run on the pull request's base branch, when one is kept +//! there too. //! The images go to the install's own bucket, the record to the settings //! table for the head, and the description is rebuilt: its table links each //! image through the API with a signed link that expires -//! ([`screens_for`]). A head keeps the first pair found; a later run on the +//! ([`screens_for`]). A head keeps the first pair found: its record is +//! claimed before any image is kept, so a later or concurrent run on the //! same head changes nothing. use std::collections::HashMap; @@ -17,7 +19,7 @@ use std::collections::HashMap; use aws_sdk_dynamodb::types::AttributeValue; use common::e2e::coverage::TestMap; use common::e2e::messages::TestIngest; -use common::e2e::model::{Outcome, ParsedTest}; +use common::e2e::model::ParsedTest; use common::e2e::report_source::Location; use common::e2e::shots::{self, Image, Kept, Side}; use common::e2e::store::Store; @@ -29,8 +31,6 @@ use crate::WorkerState; /// Tests tried for a screenshot on the head. const MAX_TRIED: usize = 3; -/// How long the record of a head is kept. -const RECORD_DAYS: i64 = 90; fn record_sk(repo: &str, sha: &str) -> String { format!("E2E_SHOTS#{repo}#{sha}") @@ -50,9 +50,10 @@ pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> serde_json::from_str(item.get("data")?.as_s().ok()?).ok() } -async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) { - let ttl = (chrono::Utc::now() + chrono::Duration::days(RECORD_DAYS)).timestamp(); - if let Err(e) = state +/// Saves the record of a head unless one is there; whether this one is. +/// The record lives as long as its links work. +async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) -> bool { + state .dynamo .put_item() .table_name(&state.config.settings_table_name) @@ -62,11 +63,26 @@ async fn save(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kep "data", super::attr_s(&serde_json::to_string(k).unwrap_or_default()), ) - .item("ttl", AttributeValue::N(ttl.to_string())) + .item("ttl", AttributeValue::N(k.expires_at.to_string())) + .condition_expression("attribute_not_exists(sk)") + .send() + .await + .is_ok() +} + +/// Drops a claimed record whose images could not be kept, so a later run +/// on the head can keep its own. +async fn release(state: &WorkerState, team_id: &str, repo: &str, sha: &str) { + if let Err(e) = state + .dynamo + .delete_item() + .table_name(&state.config.settings_table_name) + .key("pk", super::attr_s(team_id)) + .key("sk", super::attr_s(&record_sk(repo, sha))) .send() .await { - warn!(error = %e, "Could not save the end-to-end screenshots of a head"); + warn!(error = %e, "Could not drop the record of a head whose screenshots were not kept"); } } @@ -225,28 +241,25 @@ async fn images( out } -/// Keeps one image in the install's bucket; its key. -async fn put( - state: &WorkerState, - key_of: impl Fn(&str) -> String, - bytes: Vec, -) -> Option { - let content_type = shots::image_type(&bytes)?; - let key = key_of(shots::extension(content_type)); +/// Keeps one image in the install's bucket under `key`; whether it was. +async fn put(state: &WorkerState, key: &str, bytes: Vec) -> bool { + let Some(content_type) = shots::image_type(&bytes) else { + return false; + }; match state .s3 .put_object() .bucket(&state.config.bucket_name) - .key(&key) + .key(key) .content_type(content_type) .body(bytes.into()) .send() .await { - Ok(_) => Some(key), + Ok(_) => true, Err(e) => { warn!(error = %e, "Could not keep an end-to-end screenshot"); - None + false } } } @@ -320,19 +333,24 @@ pub async fn keep( info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); return; }; - // The same test on the default branch: its newest passing run there. + // The same test on the branch the pull request goes into: its newest + // passing run there. + let Some(base) = gh + .get_pull_request(owner, name, h.pr) + .await + .ok() + .and_then(|p| p["base"]["ref"].as_str().map(str::to_string)) + .filter(|b| !b.is_empty()) + else { + warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); + return; + }; let newest = st .record(&msg.team_id, &scoped(t)) .await .ok() .flatten() - .and_then(|r| { - r.history.into_iter().rev().find(|e| { - e.branch == msg.default_branch - && !e.bad_run - && matches!(e.outcome, Outcome::Passed | Outcome::Flaky) - }) - }); + .and_then(|r| shots::newest_passing(&r.history, &base).cloned()); let mut before: Option<(Vec, String)> = None; if let Some(e) = newest { let (src, run_id, attempt, run_url) = if e.run_key.starts_with("up-") { @@ -357,33 +375,51 @@ pub async fn keep( .remove(&t.id()) .map(|b| (b, run_url)); } - let key_of = |side: &'static str| { - let (team, pr, sha) = (msg.team_id.clone(), h.pr, msg.head_sha.clone()); - let repo = repo.clone(); - move |ext: &str| shots::object_key(&team, &repo, pr, &sha, side, ext) + let key_of = |side: &str, bytes: &[u8]| { + shots::image_type(bytes).map(|ct| { + shots::object_key( + &msg.team_id, + &repo, + h.pr, + &msg.head_sha, + &t.id(), + side, + shots::extension(ct), + ) + }) }; - let Some(after_key) = put(state, key_of("after"), after_bytes).await else { + let Some(after_key) = key_of("after", &after_bytes) else { return; }; - let before = match before { - Some((b, run_url)) => put(state, key_of("before"), b) - .await - .map(|key| Side { key, run_url }), - None => None, - }; + let before = + before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); let kept = Kept { pr: h.pr, test: t.full_title(), why: why.words(), - base: msg.default_branch.clone(), - before, + base, + before: before.as_ref().map(|(_, key, run_url)| Side { + key: key.clone(), + run_url: run_url.clone(), + }), after: Side { - key: after_key, + key: after_key.clone(), run_url: msg.html_url.clone(), }, expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, }; - save(state, &msg.team_id, &repo, &msg.head_sha, &kept).await; + if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { + info!(repo = %repo, pr = h.pr, "Another run on this head kept its screenshots first"); + return; + } + let mut kept_all = put(state, &after_key, after_bytes).await; + if let Some((b, key, _)) = before { + kept_all = kept_all && put(state, &key, b).await; + } + if !kept_all { + release(state, &msg.team_id, &repo, &msg.head_sha).await; + return; + } info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); if let super::description::Reconciled::Failed(why) = super::description::rebuild_pr(state, gh, &msg.team_id, owner, name, h.pr).await From 5656f6cf5164407a60e1ad8270b9251a632d5593 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 01:59:27 -0500 Subject: [PATCH 27/32] no-mistakes(review): Upload screenshots before claiming the head record --- services/common/src/e2e/shots.rs | 30 ++++++++++----- services/worker/src/passes/e2e.rs | 1 + services/worker/src/passes/e2e_screens.rs | 46 +++++++++++------------ 3 files changed, 43 insertions(+), 34 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index d05e6cb43..1c697b2ca 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -586,20 +586,22 @@ pub fn newest_passing<'a>(history: &'a [HistoryEntry], branch: &str) -> Option<& }) } -/// The key an image of test `test` is kept under in the install's bucket; -/// two tests never share one. +/// The key an image of test `test` from run `run` is kept under in the +/// install's bucket; two tests or two runs never share one. +#[allow(clippy::too_many_arguments)] pub fn object_key( team: &str, repo: &str, pr: u64, sha: &str, + run: &str, test: &str, side: &str, ext: &str, ) -> String { let test = hex::encode(Sha256::digest(test.as_bytes())); format!( - "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{}/{side}.{ext}", + "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{run}/{}/{side}.{ext}", team_folder(team), sha.get(..12).unwrap_or(sha), &test[..16] @@ -915,16 +917,26 @@ mod tests { #[test] fn a_link_reads_one_image_of_its_own_team_until_it_expires() { - let key = object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "t", "after", "png"); + let key = object_key( + "TEAM#a", + "o/r", + 7, + "0123456789abcdef", + "12-1", + "t", + "after", + "png", + ); // sha256("t") = e3b98a4da31a127d... assert_eq!( key, - "e2e-shots/TEAM_a/o/r/7/0123456789ab/e3b98a4da31a127d/after.png" - ); - assert_ne!( - key, - object_key("TEAM#a", "o/r", 7, "0123456789abcdef", "u", "after", "png") + "e2e-shots/TEAM_a/o/r/7/0123456789ab/12-1/e3b98a4da31a127d/after.png" ); + let other = |run: &str, test: &str| { + object_key("TEAM#a", "o/r", 7, "0123456789abcdef", run, test, "after", "png") + }; + assert_ne!(key, other("12-1", "u")); + assert_ne!(key, other("13-1", "t")); let t = sign("s", "TEAM#a", &key, 100); assert_eq!(verify("s", &t, 99), Ok(key.clone())); assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index ca7a1e5a9..c40b46dd4 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -636,6 +636,7 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { &st, super::e2e_screens::Head { msg: &msg, + run_key: &run_key, pr, tests: &tests, reports: &reports, diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 833d9ebbc..643ef469a 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -10,9 +10,9 @@ //! The images go to the install's own bucket, the record to the settings //! table for the head, and the description is rebuilt: its table links each //! image through the API with a signed link that expires -//! ([`screens_for`]). A head keeps the first pair found: its record is -//! claimed before any image is kept, so a later or concurrent run on the -//! same head changes nothing. +//! ([`screens_for`]). A head keeps the first pair found: each run keeps its +//! images under its own keys, then saves the head's record only when none +//! is there, so a later or concurrent run on the same head changes nothing. use std::collections::HashMap; @@ -53,7 +53,7 @@ pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> /// Saves the record of a head unless one is there; whether this one is. /// The record lives as long as its links work. async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) -> bool { - state + match state .dynamo .put_item() .table_name(&state.config.settings_table_name) @@ -67,22 +67,16 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke .condition_expression("attribute_not_exists(sk)") .send() .await - .is_ok() -} - -/// Drops a claimed record whose images could not be kept, so a later run -/// on the head can keep its own. -async fn release(state: &WorkerState, team_id: &str, repo: &str, sha: &str) { - if let Err(e) = state - .dynamo - .delete_item() - .table_name(&state.config.settings_table_name) - .key("pk", super::attr_s(team_id)) - .key("sk", super::attr_s(&record_sk(repo, sha))) - .send() - .await { - warn!(error = %e, "Could not drop the record of a head whose screenshots were not kept"); + Ok(_) => true, + Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => { + info!(repo, "Another run on this head kept its screenshots first"); + false + } + Err(e) => { + warn!(error = %e, repo, "Could not save the end-to-end screenshots of a head"); + false + } } } @@ -267,6 +261,8 @@ async fn put(state: &WorkerState, key: &str, bytes: Vec) -> bool { /// Everything a run on a pull request's head brings for its table. pub struct Head<'a> { pub msg: &'a TestIngest, + /// This run's key in the store. + pub run_key: &'a str, pub pr: u64, pub tests: &'a [ParsedTest], /// The reports this run was read from (an upload's report). @@ -382,6 +378,7 @@ pub async fn keep( &repo, h.pr, &msg.head_sha, + h.run_key, &t.id(), side, shots::extension(ct), @@ -408,16 +405,15 @@ pub async fn keep( }, expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, }; - if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { - info!(repo = %repo, pr = h.pr, "Another run on this head kept its screenshots first"); + if !put(state, &after_key, after_bytes).await { return; } - let mut kept_all = put(state, &after_key, after_bytes).await; if let Some((b, key, _)) = before { - kept_all = kept_all && put(state, &key, b).await; + if !put(state, &key, b).await { + return; + } } - if !kept_all { - release(state, &msg.team_id, &repo, &msg.head_sha).await; + if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { return; } info!(repo = %repo, pr = h.pr, test = %kept.test, before = kept.before.is_some(), "End-to-end screenshots kept for the Before and After table"); From 47cd548edd914d4d470d1935ce832c0239c7e5e6 Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 02:01:02 -0500 Subject: [PATCH 28/32] no-mistakes(review): Detect lost claim race with the typed DynamoDB error --- services/worker/src/passes/e2e_screens.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 643ef469a..a0d786bfa 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -69,7 +69,10 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke .await { Ok(_) => true, - Err(e) if format!("{e:?}").contains("ConditionalCheckFailed") => { + Err(e) + if e.as_service_error() + .is_some_and(|s| s.is_conditional_check_failed_exception()) => + { info!(repo, "Another run on this head kept its screenshots first"); false } From fde62c155b4586e5fa15afdba9ae305786fccb5a Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:12:40 -0500 Subject: [PATCH 29/32] Format the screenshot fixes with cargo fmt --- services/common/src/e2e/shots.rs | 11 ++++++++++- services/worker/src/passes/e2e_screens.rs | 3 +-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 1c697b2ca..1380f3949 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -933,7 +933,16 @@ mod tests { "e2e-shots/TEAM_a/o/r/7/0123456789ab/12-1/e3b98a4da31a127d/after.png" ); let other = |run: &str, test: &str| { - object_key("TEAM#a", "o/r", 7, "0123456789abcdef", run, test, "after", "png") + object_key( + "TEAM#a", + "o/r", + 7, + "0123456789abcdef", + run, + test, + "after", + "png", + ) }; assert_ne!(key, other("12-1", "u")); assert_ne!(key, other("13-1", "t")); diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index a0d786bfa..af447b5e1 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -391,8 +391,7 @@ pub async fn keep( let Some(after_key) = key_of("after", &after_bytes) else { return; }; - let before = - before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); + let before = before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); let kept = Kept { pr: h.pr, test: t.full_title(), From 2d1b941303c4da477ec8e39f15e0d62c06cb30be Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:16:47 -0500 Subject: [PATCH 30/32] no-mistakes(review): Pick screenshot test against PR base, fetch PR once --- services/worker/src/passes/e2e.rs | 20 +++++----- services/worker/src/passes/e2e_screens.rs | 47 ++++++++++++++--------- 2 files changed, 38 insertions(+), 29 deletions(-) diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index c40b46dd4..e27e13f46 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -622,7 +622,11 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { if run.rescued { note_rescued(&st, &gh, &msg, &run, pr).await; } - let own = is_own_pr(&gh, &msg, pr).await; + let pull = gh + .get_pull_request(&msg.repo_owner, &msg.repo_name, pr) + .await + .ok(); + let own = is_own_pr(&msg, pull.as_ref()); // A run that failed only on quarantined tests needs no fix or re-run. if failed > 0 && !run.rescued && own { own_pr_failures(state, &gh, &msg, &run, pr, &lines, &tests).await; @@ -640,6 +644,7 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { pr, tests: &tests, reports: &reports, + pull: pull.as_ref(), changed: &changed, map: map.as_ref(), }, @@ -2382,16 +2387,9 @@ async fn recommend(st: &Store<'_>, team: &str, rec: Recommendation) { /// Whether the PR is one CoderHelm opened: a branch in the default shape, or /// a PR whose author is CoderHelm's app (a team's own branch pattern). -async fn is_own_pr(gh: &GitHubClient, msg: &TestIngest, pr: u64) -> bool { - if msg - .head_branch - .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) - { - return true; - } - gh.get_pull_request(&msg.repo_owner, &msg.repo_name, pr) - .await - .is_ok_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) +fn is_own_pr(msg: &TestIngest, pull: Option<&serde_json::Value>) -> bool { + msg.head_branch.starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) + || pull.is_some_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) } async fn recommend_from_pr( diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index af447b5e1..08561b3a5 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -270,7 +270,9 @@ pub struct Head<'a> { pub tests: &'a [ParsedTest], /// The reports this run was read from (an upload's report). pub reports: &'a [(String, Vec)], - /// The files the pull request changes. + /// The pull request, as GitHub returns it. + pub pull: Option<&'a serde_json::Value>, + /// The files the head changes against the default branch. pub changed: &'a [String], pub map: Option<&'a TestMap>, } @@ -291,14 +293,34 @@ pub async fn keep( if state.secrets.jwt_secret.is_empty() || msg.head_sha.is_empty() { return; } - let picked = shots::pick(h.tests, h.changed, h.map); - if picked.is_empty() - || load(state, &msg.team_id, &repo, &msg.head_sha) - .await - .is_some() + if load(state, &msg.team_id, &repo, &msg.head_sha) + .await + .is_some() { return; } + // The branch the pull request goes into: the tests its change touches + // are read against it, and the Before image comes from it. + let Some(base) = h + .pull + .and_then(|p| p["base"]["ref"].as_str()) + .filter(|b| !b.is_empty()) + .map(str::to_string) + else { + warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); + return; + }; + let changed = if base == msg.default_branch { + h.changed.to_vec() + } else { + gh.compare_changed_files(owner, name, &base, &msg.head_sha) + .await + .unwrap_or_default() + }; + let picked = shots::pick(h.tests, &changed, h.map); + if picked.is_empty() { + return; + } let location = st .settings(&msg.team_id) .await @@ -332,18 +354,7 @@ pub async fn keep( info!(repo = %repo, pr = h.pr, tests = ids.len(), "No screenshot on the head for the tests that show the change"); return; }; - // The same test on the branch the pull request goes into: its newest - // passing run there. - let Some(base) = gh - .get_pull_request(owner, name, h.pr) - .await - .ok() - .and_then(|p| p["base"]["ref"].as_str().map(str::to_string)) - .filter(|b| !b.is_empty()) - else { - warn!(repo = %repo, pr = h.pr, "Could not read the pull request's base branch; no screenshots kept"); - return; - }; + // The same test on the base branch: its newest passing run there. let newest = st .record(&msg.team_id, &scoped(t)) .await From 5a808baabe2b87e31614bd8ae950adce320ae15d Mon Sep 17 00:00:00 2001 From: Shoyu Date: Sun, 15 Nov 2026 06:51:57 -0500 Subject: [PATCH 31/32] no-mistakes(document): Format is_own_pr with cargo fmt --- services/worker/src/passes/e2e.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index e27e13f46..c55b83c51 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -2388,7 +2388,8 @@ async fn recommend(st: &Store<'_>, team: &str, rec: Recommendation) { /// Whether the PR is one CoderHelm opened: a branch in the default shape, or /// a PR whose author is CoderHelm's app (a team's own branch pattern). fn is_own_pr(msg: &TestIngest, pull: Option<&serde_json::Value>) -> bool { - msg.head_branch.starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) + msg.head_branch + .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) || pull.is_some_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) } From a30427a0d6324c2511fce82c1bdc72c0be45d88d Mon Sep 17 00:00:00 2001 From: Shoyu Date: Tue, 17 Nov 2026 16:41:17 -0500 Subject: [PATCH 32/32] Keep end-to-end screenshots on the screenshots ref, under the preview's pages Review asked for one hosting model and for the pair not to hide the preview's page captures. - The Before and After images are committed to refs/coderhelm/screenshots beside the preview's captures and linked by commit, so only people who can read the repository see them. The public screenshot route, its signed links, the bucket copies and their lifecycle rule are gone. - preview::keep_on_ref is the one way both write that ref: blobs, a commit on top of the ref, and a move without force (advance_own_ref), tried again on top when another writer moved it, so no writer's commit is dropped and no image link breaks. - The pair is its own fact (e2e_screens), rendered as a table under the preview's pages and never instead of them; it takes the place of a "No screenshot" line. The preview's pages now win over a set screens table. - An ingest reads the pull request only when it needs it: a failure on a branch that is not CoderHelm's shape, or a report that carries screenshots. CiReports gets the run's real attempt. --- infra/lib/storage-stack.ts | 7 - services/common/src/e2e/shots.rs | 225 ++++++---------------- services/common/src/pr_body.rs | 60 +++++- services/common/src/pr_facts.rs | 44 ++++- services/gateway/src/main.rs | 3 - services/gateway/src/routes/tests.rs | 60 ------ services/worker/src/clients/github.rs | 44 +++-- services/worker/src/passes/description.rs | 4 +- services/worker/src/passes/e2e.rs | 34 +++- services/worker/src/passes/e2e_screens.rs | 119 +++++------- services/worker/src/passes/preview.rs | 105 +++++++--- 11 files changed, 331 insertions(+), 374 deletions(-) diff --git a/infra/lib/storage-stack.ts b/infra/lib/storage-stack.ts index b467b1b2c..e15166b02 100644 --- a/infra/lib/storage-stack.ts +++ b/infra/lib/storage-stack.ts @@ -133,13 +133,6 @@ export class StorageStack extends cdk.Stack { expiration: cdk.Duration.days(2), noncurrentVersionExpiration: cdk.Duration.days(1), }, - { - // End-to-end screenshots in pull request descriptions: their links - // work for a year (common::e2e::shots), the images a month longer. - prefix: "e2e-shots/", - expiration: cdk.Duration.days(395), - noncurrentVersionExpiration: cdk.Duration.days(1), - }, { // Move old run artifacts to Infrequent Access after 90 days transitions: [ diff --git a/services/common/src/e2e/shots.rs b/services/common/src/e2e/shots.rs index 1380f3949..8ed5ac2dd 100644 --- a/services/common/src/e2e/shots.rs +++ b/services/common/src/e2e/shots.rs @@ -15,13 +15,13 @@ //! ([`ParsedTest::id`]), and [`pick`] chooses the tests that show the change: //! a test the change edits, a test the repository's test map ties to the //! changed files, or a test whose name shares a word with a changed UI file. -//! The worker keeps the images in the install's own bucket -//! ([`object_key`]); the description links them with a signed link -//! ([`sign`]) that the API serves at [`LINK_PATH`] until it expires. +//! The worker commits the images to the ref CoderHelm keeps its pull +//! request screenshots on in the repository itself (`refs/coderhelm/screenshots`, +//! next to the preview's page captures, at [`ref_path`]) and links them by +//! commit, so only people who can read the repository see them. -use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::engine::general_purpose::STANDARD; use base64::Engine; -use hmac::{Hmac, Mac}; use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest, Sha256}; @@ -31,14 +31,6 @@ use super::model::{test_id, Framework, HistoryEntry, Outcome, ParsedTest}; /// Largest image kept. pub const MAX_IMAGE: usize = 5 * 1024 * 1024; -/// Where the images are kept in the install's bucket. -pub const KEY_PREFIX: &str = "e2e-shots"; -/// How long an image link works (the bucket keeps the images a little -/// longer, see `infra/lib/storage-stack.ts`). -pub const LINK_VALID_SECS: i64 = 365 * 86_400; -/// The path the API serves an image at. -pub const LINK_PATH: &str = "/webhooks/ci/tests/screenshot"; -const MAX_TOKEN_LEN: usize = 2048; /// One test's screenshot in one report. #[derive(Debug, Clone, PartialEq, Eq)] @@ -503,8 +495,9 @@ pub fn pick<'a>( /// One side of the table: the kept image and the run it came from. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Side { - /// The image's key in the install's bucket. - pub key: String, + /// The image's address on the screenshots ref, at the commit that + /// added it. + pub src: String, /// The run's page; empty for an upload with no run page. #[serde(default)] pub run_url: String, @@ -525,9 +518,6 @@ pub struct Kept { pub before: Option, /// The test on the head. pub after: Side, - /// When the links stop working (unix seconds); fixed when kept, so the - /// description is the same text on every rebuild. - pub expires_at: i64, } fn md_link(text: &str, url: &str) -> String { @@ -538,8 +528,8 @@ fn md_link(text: &str, url: &str) -> String { } } -/// The table for `k`; `link` gives an image's link from its key. -pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Screens { +/// The Before and After table for `k`. +pub fn screens(k: &Kept) -> crate::pr_body::Screens { let test = k.test.replace('`', "'"); let base: &str = if k.base.is_empty() { "the base branch" @@ -548,7 +538,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree }; let (before, before_alt) = match &k.before { Some(s) => ( - link(&s.key), + s.src.clone(), format!("{test} on {base}, before this change"), ), None => ( @@ -569,7 +559,7 @@ pub fn screens(k: &Kept, link: impl Fn(&str) -> String) -> crate::pr_body::Scree crate::pr_body::Screens::Images { before, before_alt, - after: link(&k.after.key), + after: k.after.src.clone(), after_alt: format!("{test} on this head"), caption: format!( "Screenshots of the end-to-end test `{test}`, chosen because {}: {runs}.", @@ -586,104 +576,28 @@ pub fn newest_passing<'a>(history: &'a [HistoryEntry], branch: &str) -> Option<& }) } -/// The key an image of test `test` from run `run` is kept under in the -/// install's bucket; two tests or two runs never share one. -#[allow(clippy::too_many_arguments)] -pub fn object_key( - team: &str, - repo: &str, - pr: u64, - sha: &str, - run: &str, - test: &str, - side: &str, - ext: &str, -) -> String { +/// Where an image of test `test` from run `run` is kept on the screenshots +/// ref, beside the preview's captures of the same head (`pr-//`); +/// two tests or two runs never share a path. +pub fn ref_path(pr: u64, sha: &str, run: &str, test: &str, side: &str, ext: &str) -> String { let test = hex::encode(Sha256::digest(test.as_bytes())); + let run: String = run + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect(); format!( - "{KEY_PREFIX}/{}/{repo}/{pr}/{}/{run}/{}/{side}.{ext}", - team_folder(team), + "pr-{pr}/{}/e2e-{}-{run}-{side}.{ext}", sha.get(..12).unwrap_or(sha), &test[..16] ) } -fn team_folder(team: &str) -> String { - team.replace(['#', '/'], "_") -} - -// ── Signed links ────────────────────────────────────────────────────────── - -type HmacSha256 = Hmac; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TokenError { - Malformed, - BadSignature, - Expired, -} - -fn mac(secret: &str, payload: &str) -> HmacSha256 { - // A key for screenshot links only, so a link never stands in for a - // session or for any other signed link. - let mut kdf = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC takes any key"); - kdf.update(b"coderhelm/e2e-screenshot/v1"); - let key = kdf.finalize().into_bytes(); - let mut m = HmacSha256::new_from_slice(&key).expect("HMAC takes any key"); - m.update(payload.as_bytes()); - m -} - -/// A token that reads one kept image of one team until `expires_at`. The -/// token is `base64url(team \n key \n expiry) . base64url(HMAC-SHA256)`. -pub fn sign(secret: &str, team: &str, key: &str, expires_at: i64) -> String { - let payload = format!("{team}\n{key}\n{expires_at}"); - let sig = mac(secret, &payload).finalize().into_bytes(); - format!( - "{}.{}", - URL_SAFE_NO_PAD.encode(payload.as_bytes()), - URL_SAFE_NO_PAD.encode(sig) - ) -} - -/// The image key a token reads, if it is genuine, current, and names one of -/// its own team's kept images. -pub fn verify(secret: &str, token: &str, now: i64) -> Result { - if token.is_empty() || token.len() > MAX_TOKEN_LEN { - return Err(TokenError::Malformed); - } - let (body, sig) = token.split_once('.').ok_or(TokenError::Malformed)?; - let payload = URL_SAFE_NO_PAD - .decode(body) - .ok() - .and_then(|b| String::from_utf8(b).ok()) - .ok_or(TokenError::Malformed)?; - let sig = URL_SAFE_NO_PAD - .decode(sig) - .map_err(|_| TokenError::Malformed)?; - mac(secret, &payload) - .verify_slice(&sig) - .map_err(|_| TokenError::BadSignature)?; - let p: Vec<&str> = payload.split('\n').collect(); - let [team, key, exp] = p.as_slice() else { - return Err(TokenError::Malformed); - }; - let exp: i64 = exp.parse().map_err(|_| TokenError::Malformed)?; - let own = format!("{KEY_PREFIX}/{}/", team_folder(team)); - if team.is_empty() || !key.starts_with(&own) || key.split('/').any(|s| s == "..") { - return Err(TokenError::Malformed); - } - if now >= exp { - return Err(TokenError::Expired); - } - Ok(key.to_string()) -} - -/// The link for a token on this deployment's API. -pub fn url(api: &str, token: &str) -> String { - format!("{}{LINK_PATH}?t={token}", api.trim_end_matches('/')) -} - #[cfg(test)] mod tests { use super::*; @@ -868,16 +782,15 @@ mod tests { why: Why::Named("checkout".into()).words(), base: "main".into(), before: Some(Side { - key: "e2e-shots/T/o/r/7/abc/before.png".into(), + src: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-x-1-1-before.png?raw=true".into(), run_url: "https://github.com/o/r/actions/runs/1".into(), }), after: Side { - key: "e2e-shots/T/o/r/7/abc/after.png".into(), + src: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-x-2-1-after.png?raw=true".into(), run_url: "https://github.com/o/r/actions/runs/2".into(), }, - expires_at: 10, }; - let s = screens(&k, |key| format!("https://api.example.com/x?k={key}")); + let s = screens(&k); let crate::pr_body::Screens::Images { before, after, @@ -888,20 +801,17 @@ mod tests { else { panic!("images"); }; - assert!(before.ends_with("before.png")); - assert!(after.ends_with("after.png")); + assert!(before.ends_with("before.png?raw=true")); + assert!(after.ends_with("after.png?raw=true")); assert_eq!(after_alt, "Checkout › pays by 'card' on this head"); assert_eq!( caption, "Screenshots of the end-to-end test `Checkout › pays by 'card'`, chosen because the test and a changed UI file share the word \"checkout\": [main's run](https://github.com/o/r/actions/runs/1), [this head's run](https://github.com/o/r/actions/runs/2)." ); - let none = screens( - &Kept { - before: None, - ..k.clone() - }, - |key| key.to_string(), - ); + let none = screens(&Kept { + before: None, + ..k.clone() + }); let crate::pr_body::Screens::Images { before, before_alt, .. } = none @@ -916,52 +826,26 @@ mod tests { } #[test] - fn a_link_reads_one_image_of_its_own_team_until_it_expires() { - let key = object_key( - "TEAM#a", - "o/r", - 7, - "0123456789abcdef", - "12-1", - "t", - "after", - "png", - ); + fn each_test_and_run_has_its_own_path_beside_the_preview_captures() { + let path = ref_path(7, "0123456789abcdef", "12-1", "t", "after", "png"); // sha256("t") = e3b98a4da31a127d... assert_eq!( - key, - "e2e-shots/TEAM_a/o/r/7/0123456789ab/12-1/e3b98a4da31a127d/after.png" + path, + "pr-7/0123456789ab/e2e-e3b98a4da31a127d-12-1-after.png" + ); + assert_ne!( + path, + ref_path(7, "0123456789abcdef", "12-1", "u", "after", "png") + ); + assert_ne!( + path, + ref_path(7, "0123456789abcdef", "13-1", "t", "after", "png") + ); + // An upload's run key is kept to letters, digits and dashes. + assert_eq!( + ref_path(7, "0123456789abcdef", "up-9/../x", "t", "before", "jpg"), + "pr-7/0123456789ab/e2e-e3b98a4da31a127d-up-9____x-before.jpg" ); - let other = |run: &str, test: &str| { - object_key( - "TEAM#a", - "o/r", - 7, - "0123456789abcdef", - run, - test, - "after", - "png", - ) - }; - assert_ne!(key, other("12-1", "u")); - assert_ne!(key, other("13-1", "t")); - let t = sign("s", "TEAM#a", &key, 100); - assert_eq!(verify("s", &t, 99), Ok(key.clone())); - assert_eq!(verify("s", &t, 100), Err(TokenError::Expired)); - assert_eq!(verify("other", &t, 99), Err(TokenError::BadSignature)); - // Signed, but for another team's image or anything else in the bucket. - let theirs = sign("s", "TEAM#a", "e2e-shots/TEAM_b/o/r/1/x/after.png", 100); - assert_eq!(verify("s", &theirs, 99), Err(TokenError::Malformed)); - let raw = sign("s", "TEAM#a", "e2e/TEAM_a/o/r/raw/1-1/report.json", 100); - assert_eq!(verify("s", &raw, 99), Err(TokenError::Malformed)); - let up = sign("s", "TEAM#a", "e2e-shots/TEAM_a/../../secret", 100); - assert_eq!(verify("s", &up, 99), Err(TokenError::Malformed)); - // An unsubscribe token never reads an image. - let u = crate::unsubscribe::sign("s", "TEAM#a", "USER#1", "weekly_summary", 100); - assert!(verify("s", &u, 99).is_err()); - assert!(url("https://api.example.com/", &t) - .starts_with("https://api.example.com/webhooks/ci/tests/screenshot?t=")); } #[test] @@ -996,8 +880,7 @@ mod tests { base: "develop".into(), ..Default::default() }; - let crate::pr_body::Screens::Images { before_alt, .. } = screens(&k, |key| key.into()) - else { + let crate::pr_body::Screens::Images { before_alt, .. } = screens(&k) else { panic!("images"); }; assert_eq!( diff --git a/services/common/src/pr_body.rs b/services/common/src/pr_body.rs index 7435e4c37..653bc4d07 100644 --- a/services/common/src/pr_body.rs +++ b/services/common/src/pr_body.rs @@ -301,6 +301,9 @@ pub struct Body { pub rows: Vec, /// `Some` for a UI change. pub screens: Option, + /// A Before and After pair from the end-to-end run on the head, shown + /// under [`Body::screens`] (never instead of the preview's pages). + pub e2e_screens: Option, /// The first fold's name ([`NOTES`] when empty). pub notes_label: String, /// Generated text at the top of the first fold. @@ -1067,8 +1070,14 @@ fn blocks(b: &Body) -> Blocks { if !how.is_empty() { verification.push_str(&format!("\n\nHow to check: {how}.")); } - if let Some(s) = &b.screens { - out.screens = screens_markdown(s); + // The preview's pages first, then the end-to-end pair under them; a + // "No screenshot" line goes when the pair is there. + let parts: Vec = match (&b.screens, &b.e2e_screens) { + (Some(Screens::Missing(_)), Some(e)) | (None, Some(e)) => vec![screens_markdown(e)], + (s, e) => s.iter().chain(e).map(screens_markdown).collect(), + }; + if !parts.is_empty() { + out.screens = parts.join("\n\n"); verification.push_str(&format!("\n\n{}", out.screens)); } out.verification = verification; @@ -1887,6 +1896,53 @@ mod tests { assert_eq!(defects(&body, "d78bb24"), Vec::::new(), "{body}"); } + /// The end-to-end pair is an addition: under the preview's pages, never + /// instead of them; it takes the place of a "No screenshot" line. + #[test] + fn the_end_to_end_pair_goes_under_the_preview_pages() { + let pair = Screens::Images { + before: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-1-before.png?raw=true".into(), + before_alt: "Checkout on main, before this change".into(), + after: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-1-after.png?raw=true".into(), + after_alt: "Checkout on this head".into(), + caption: "Screenshots of the end-to-end test `Checkout`, chosen because this change edits the test: this head's run.".into(), + }; + let body = |screens: Option| Body { + head: "d78bb24".into(), + summary: "Shows the total on the checkout page.".into(), + level: Level::Low, + risk: "one page's layout only".into(), + rollback: "revert this PR".into(), + rows: vec![Row { + check: "Unit tests (CI)".into(), + outcome: Outcome::Passed, + detail: String::new(), + }], + screens, + e2e_screens: Some(pair.clone()), + ..Default::default() + }; + let r = render(&body(Some(Screens::Pages(vec![( + "/checkout".into(), + "https://img.example.com/d.png".into(), + "https://img.example.com/p.png".into(), + )])))); + let pages = r.visible.clone(); + let at = |v: &str, h: &str| v.find(h).unwrap_or_else(|| panic!("{h}: {v}")); + assert!(at(&pages, "| Page | Desktop | Phone |") < at(&pages, "| Before | After |")); + assert!(pages.contains("Screenshots of the end-to-end test `Checkout`")); + let whole = format!("{pages}\n\n{}", r.footer); + assert_eq!(defects(&whole, "d78bb24"), Vec::::new(), "{whole}"); + let missing = render(&body(Some(Screens::Missing( + "CoderHelm had no runnable preview to capture for this run".into(), + )))) + .visible; + assert!(!missing.contains("No screenshot"), "{missing}"); + assert!(missing.contains("| Before | After |"), "{missing}"); + let alone = render(&body(None)).visible; + assert!(alone.contains("| Before | After |"), "{alone}"); + } + /// The layout: Problem, Changes, (Needed from you), Risk, Verification, /// two or three lines each; the preview's link, its screenshots, what /// the pull request waits on and how to check are in Verification. diff --git a/services/common/src/pr_facts.rs b/services/common/src/pr_facts.rs index 612bc53df..597c9855f 100644 --- a/services/common/src/pr_facts.rs +++ b/services/common/src/pr_facts.rs @@ -373,6 +373,10 @@ pub struct Facts { /// A UI change's screenshots, or why there are none. #[serde(default)] pub screens: Option, + /// A Before and After pair from the end-to-end run on the head + /// (`e2e::shots`): shown under the preview's pages, never instead. + #[serde(default)] + pub e2e_screens: Option, /// What the pull request waits on, one line (`crate::waiting_line`). #[serde(default)] pub waiting: String, @@ -1480,8 +1484,8 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { .iter() .any(|x| crate::preview::is_user_visible(&x.path)); let screens = match (&f.screens, &f.preview) { - (Some(s), _) => Some(s.clone()), - (None, Some(p)) => screens_of(p, visible), + (s, Some(p)) => screens_of(p, visible).or_else(|| s.clone()), + (Some(s), None) => Some(s.clone()), (None, None) if f.files.iter().any(|x| is_ui(&x.path)) => Some(Screens::Missing( "CoderHelm had no runnable preview to capture for this run".into(), )), @@ -1597,6 +1601,7 @@ pub fn body_of(f: &Facts, ticked: &[String]) -> crate::pr_body::Body { rollback, rows: rows(f), screens, + e2e_screens: f.e2e_screens.clone(), notes_label, notes_top, evidence: evidence.join("\n\n"), @@ -1642,6 +1647,41 @@ mod tests { } } + /// The preview's captured pages are never hidden by another table: the + /// end-to-end pair travels on its own and is shown under them. + #[test] + fn the_preview_pages_win_and_the_end_to_end_pair_is_kept_beside_them() { + use crate::pr_body::Screens; + let pair = Screens::Images { + before: String::new(), + before_alt: "No passing run on main with a screenshot of this test yet".into(), + after: "https://github.com/o/r/blob/c1/pr-7/abc/e2e-1-after.png?raw=true".into(), + after_alt: "Checkout on this head".into(), + caption: String::new(), + }; + let mut f = ticket_facts(); + f.screens = Some(pair.clone()); + f.e2e_screens = Some(pair.clone()); + f.preview = Some(crate::preview::State { + shots: vec![crate::preview::Shot { + page: "/checkout".into(), + width: "desktop".into(), + src: "https://img.example.com/d.png".into(), + }], + ..Default::default() + }); + let b = body_of(&f, &[]); + assert!( + matches!(b.screens, Some(Screens::Pages(_))), + "{:?}", + b.screens + ); + assert_eq!(b.e2e_screens, Some(pair.clone())); + // Without a preview, a table someone set still shows. + f.preview = None; + assert_eq!(body_of(&f, &[]).screens, Some(pair)); + } + fn ticket_facts() -> Facts { Facts { head: "abc1234def".into(), diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index c9242f981..fc27eeb40 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -1620,9 +1620,6 @@ fn build_app(state: Arc) -> Router { // CI calls signed with a GitHub Actions OIDC token .route("/ci/tests/results", post(routes::tests::ci_upload)) .route("/ci/tests/quarantine", get(routes::tests::ci_quarantine)) - // A screenshot in the Before and After table of CoderHelm's own pull - // request; the signed link is the credential (routes::tests). - .route("/ci/tests/screenshot", get(routes::tests::ci_screenshot)) // Events CoderHelm's relay forwards to a hybrid install, and its // ownership proof (routes::hybrid_install). .route("/relay", post(routes::hybrid_install::intake)) diff --git a/services/gateway/src/routes/tests.rs b/services/gateway/src/routes/tests.rs index 4fec457c2..44bdbb1a9 100644 --- a/services/gateway/src/routes/tests.rs +++ b/services/gateway/src/routes/tests.rs @@ -1382,66 +1382,6 @@ pub async fn ci_quarantine( })) } -#[derive(Deserialize)] -pub struct ShotQuery { - #[serde(default)] - t: String, -} - -/// GET /webhooks/ci/tests/screenshot?t= — one end-to-end screenshot kept for -/// the Before and After table of CoderHelm's own pull request -/// (`common::e2e::shots`). Public, because GitHub fetches the image for the -/// pull request's readers: the signed token is the credential, and it names -/// one image of one team until it expires. Anything else is a 404 that says -/// nothing. -pub async fn ci_screenshot( - State(state): State>, - Query(q): Query, -) -> axum::response::Response { - use axum::http::header; - use axum::response::IntoResponse; - use common::e2e::shots; - let not_found = || (StatusCode::NOT_FOUND, "Not found").into_response(); - let secret = state.secrets.jwt_secret.as_str(); - if secret.is_empty() { - return not_found(); - } - let key = match shots::verify(secret, q.t.trim(), chrono::Utc::now().timestamp()) { - Ok(k) => k, - Err(e) => { - info!(reason = ?e, "Screenshot link refused"); - return not_found(); - } - }; - let Ok(obj) = state - .s3 - .get_object() - .bucket(&state.config.bucket_name) - .key(&key) - .send() - .await - else { - return not_found(); - }; - let Ok(body) = obj.body.collect().await else { - return not_found(); - }; - let bytes = body.into_bytes(); - let Some(content_type) = shots::image_type(&bytes) else { - return not_found(); - }; - ( - StatusCode::OK, - [ - (header::CONTENT_TYPE, content_type), - (header::CACHE_CONTROL, "public, max-age=86400"), - (header::X_CONTENT_TYPE_OPTIONS, "nosniff"), - ], - bytes, - ) - .into_response() -} - #[cfg(test)] mod unit { use super::*; diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index aea185278..d476cf6d3 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3292,15 +3292,20 @@ impl GitHubClient { .to_string()) } - /// Points a ref outside `refs/heads/` (no workflow starts on it) at - /// `sha`, creating it when it doesn't exist. Only for CoderHelm's own - /// refs, such as the one its pull request screenshots are kept on. - pub async fn set_own_ref( + /// Moves a ref outside `refs/heads/` (no workflow starts on it; only for + /// CoderHelm's own refs, such as the one its pull request screenshots + /// are kept on) from `from` to `to` without force: GitHub refuses the + /// move when the ref no longer points at an ancestor of `to`, so a + /// commit another writer put on it in the meantime is never dropped. + /// With `from` `None` the ref is created, and creating one that exists + /// is refused the same way. + pub async fn advance_own_ref( &self, owner: &str, repo: &str, name: &str, - sha: &str, + from: Option<&str>, + to: &str, ) -> Result<(), Box> { let name = name.trim_start_matches("refs/"); if name.starts_with("heads/") || name.starts_with("tags/") || !name.contains('/') { @@ -3308,21 +3313,22 @@ impl GitHubClient { format!("`refs/{name}` is not a ref CoderHelm keeps its own files on").into(), ); } - let patched = self - .patch( - &format!("{API_BASE}/repos/{owner}/{repo}/git/refs/{name}"), - &serde_json::json!({"sha": sha, "force": true}), - ) - .await; - if patched.is_ok() { - return Ok(()); + match from { + Some(_) => self + .patch( + &format!("{API_BASE}/repos/{owner}/{repo}/git/refs/{name}"), + &serde_json::json!({"sha": to, "force": false}), + ) + .await + .map(|_| ()), + None => self + .post( + &format!("{API_BASE}/repos/{owner}/{repo}/git/refs"), + &serde_json::json!({"ref": format!("refs/{name}"), "sha": to}), + ) + .await + .map(|_| ()), } - self.post( - &format!("{API_BASE}/repos/{owner}/{repo}/git/refs"), - &serde_json::json!({"ref": format!("refs/{name}"), "sha": sha}), - ) - .await - .map(|_| ()) } /// The commit a ref outside `refs/heads/` points at, if it exists. diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index 03ac81ee4..c97e08234 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -667,9 +667,7 @@ impl Gathered { super::description_facts::with_two_way(&mut f, &self.run.two_way); super::description_facts::with_scope(&mut f, self.run.scope.as_ref(), &self.files); f.waiting = self.run.waiting.clone(); - if self.screens.is_some() { - f.screens = self.screens.clone(); - } + f.e2e_screens = self.screens.clone(); f } } diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index c55b83c51..138eaf569 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -622,18 +622,28 @@ pub async fn ingest(state: &WorkerState, msg: TestIngest) -> Result<(), Err> { if run.rescued { note_rescued(&st, &gh, &msg, &run, pr).await; } - let pull = gh - .get_pull_request(&msg.repo_owner, &msg.repo_name, pr) - .await - .ok(); - let own = is_own_pr(&msg, pull.as_ref()); // A run that failed only on quarantined tests needs no fix or re-run. - if failed > 0 && !run.rescued && own { + let fix = failed > 0 && !run.rescued; + // Screenshots in this run's reports, for the description's table. + let shots = reports + .iter() + .any(|(n, b)| !common::e2e::shots::shots_in(n, b).is_empty()); + // The pull request is read only when one of them needs it: whose it + // is (unless the branch says), and its base for the screenshots. + let pull = if (fix && !own_branch(&msg)) || shots { + gh.get_pull_request(&msg.repo_owner, &msg.repo_name, pr) + .await + .ok() + } else { + None + }; + let own = is_own_pr(&msg, pull.as_ref()); + if fix && own { own_pr_failures(state, &gh, &msg, &run, pr, &lines, &tests).await; } // CoderHelm's own pull request shows the screenshots this run took // of the tests its change touches. - if own { + if shots && own { super::e2e_screens::keep( state, &gh, @@ -2385,11 +2395,17 @@ async fn recommend(st: &Store<'_>, team: &str, rec: Recommendation) { } } +/// Whether the run's branch is in CoderHelm's default shape: its pull +/// request is CoderHelm's without reading it. +fn own_branch(msg: &TestIngest) -> bool { + msg.head_branch + .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) +} + /// Whether the PR is one CoderHelm opened: a branch in the default shape, or /// a PR whose author is CoderHelm's app (a team's own branch pattern). fn is_own_pr(msg: &TestIngest, pull: Option<&serde_json::Value>) -> bool { - msg.head_branch - .starts_with(common::git_conventions::DEFAULT_BRANCH_PREFIX) + own_branch(msg) || pull.is_some_and(|p| super::is_own_login(p["user"]["login"].as_str().unwrap_or(""))) } diff --git a/services/worker/src/passes/e2e_screens.rs b/services/worker/src/passes/e2e_screens.rs index 08561b3a5..a1da040f2 100644 --- a/services/worker/src/passes/e2e_screens.rs +++ b/services/worker/src/passes/e2e_screens.rs @@ -7,12 +7,14 @@ //! one with a screenshot on the head is kept with its screenshot from the //! newest passing run on the pull request's base branch, when one is kept //! there too. -//! The images go to the install's own bucket, the record to the settings -//! table for the head, and the description is rebuilt: its table links each -//! image through the API with a signed link that expires -//! ([`screens_for`]). A head keeps the first pair found: each run keeps its -//! images under its own keys, then saves the head's record only when none -//! is there, so a later or concurrent run on the same head changes nothing. +//! The images are committed to the screenshots ref in the repository +//! (`preview::SHOTS_REF`, next to the preview's page captures) and linked +//! by commit, so only people who can read the repository see them; the +//! record goes to the settings table for the head and the description is +//! rebuilt, the pair under the preview's pages ([`screens_for`]). A head +//! keeps the first pair found: each run commits its images under its own +//! paths, then saves the head's record only when none is there, so a later +//! or concurrent run on the same head changes nothing. use std::collections::HashMap; @@ -31,6 +33,9 @@ use crate::WorkerState; /// Tests tried for a screenshot on the head. const MAX_TRIED: usize = 3; +/// How long the record of a head is kept: the description of an open pull +/// request is rebuilt from it. +const RECORD_DAYS: i64 = 365; fn record_sk(repo: &str, sha: &str) -> String { format!("E2E_SHOTS#{repo}#{sha}") @@ -51,8 +56,8 @@ pub async fn load(state: &WorkerState, team_id: &str, repo: &str, sha: &str) -> } /// Saves the record of a head unless one is there; whether this one is. -/// The record lives as long as its links work. async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Kept) -> bool { + let ttl = (chrono::Utc::now() + chrono::Duration::days(RECORD_DAYS)).timestamp(); match state .dynamo .put_item() @@ -63,7 +68,7 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke "data", super::attr_s(&serde_json::to_string(k).unwrap_or_default()), ) - .item("ttl", AttributeValue::N(k.expires_at.to_string())) + .item("ttl", AttributeValue::N(ttl.to_string())) .condition_expression("attribute_not_exists(sk)") .send() .await @@ -84,24 +89,16 @@ async fn claim(state: &WorkerState, team_id: &str, repo: &str, sha: &str, k: &Ke } /// The Before and After table for a pull request's head, when a run on it -/// kept screenshots. `None` without a signing secret or a public API -/// address: GitHub fetches the images from the API, so a link must reach -/// it. +/// kept screenshots. pub async fn screens_for( state: &WorkerState, team_id: &str, repo: &str, sha: &str, ) -> Option { - let secret = state.secrets.jwt_secret.as_str(); - let api = common::public_urls::api_url(&state.config.stage); - if secret.is_empty() || !api.starts_with("https://") { - return None; - } - let k = load(state, team_id, repo, sha).await?; - Some(shots::screens(&k, |key| { - shots::url(api, &shots::sign(secret, team_id, key, k.expires_at)) - })) + load(state, team_id, repo, sha) + .await + .map(|k| shots::screens(&k)) } /// Report files held in memory: an uploaded report, or the raw reports kept @@ -238,29 +235,6 @@ async fn images( out } -/// Keeps one image in the install's bucket under `key`; whether it was. -async fn put(state: &WorkerState, key: &str, bytes: Vec) -> bool { - let Some(content_type) = shots::image_type(&bytes) else { - return false; - }; - match state - .s3 - .put_object() - .bucket(&state.config.bucket_name) - .key(key) - .content_type(content_type) - .body(bytes.into()) - .send() - .await - { - Ok(_) => true, - Err(e) => { - warn!(error = %e, "Could not keep an end-to-end screenshot"); - false - } - } -} - /// Everything a run on a pull request's head brings for its table. pub struct Head<'a> { pub msg: &'a TestIngest, @@ -290,7 +264,7 @@ pub async fn keep( let msg = h.msg; let (owner, name) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); let repo = format!("{owner}/{name}"); - if state.secrets.jwt_secret.is_empty() || msg.head_sha.is_empty() { + if msg.head_sha.is_empty() { return; } if load(state, &msg.team_id, &repo, &msg.head_sha) @@ -329,20 +303,20 @@ pub async fn keep( let location = location.as_ref(); // Where the team keeps the repository's reports, else the run's // artifacts: the same places the failure attribution reads. - let open = |run_id: u64| async move { + let open = |run_id: u64, attempt: u32| async move { if let Some(l @ Location::S3 { .. }) = location { let mut tried = Vec::new(); if let Some(r) = super::test_fix::open_s3(state, &msg.team_id, l, &mut tried).await { return Source::S3(Box::new(r)); } } - Source::Ci(CiReports::new(gh, owner, name, vec![(run_id, 1)])) + Source::Ci(CiReports::new(gh, owner, name, vec![(run_id, attempt)])) }; // The head's run. let head = if msg.upload_key.is_some() { Source::Held(Held(h.reports.to_vec())) } else { - open(msg.run_id).await + open(msg.run_id, msg.run_attempt).await }; let tried: Vec<&(&ParsedTest, shots::Why)> = picked.iter().take(MAX_TRIED).collect(); let ids: Vec = tried.iter().map(|(t, _)| t.id()).collect(); @@ -372,7 +346,7 @@ pub async fn keep( ) } else if let Some((run_id, attempt)) = run_of(&e.run_key) { ( - open(run_id).await, + open(run_id, attempt).await, run_id, attempt, format!("https://github.com/{repo}/actions/runs/{run_id}"), @@ -385,11 +359,11 @@ pub async fn keep( .remove(&t.id()) .map(|b| (b, run_url)); } - let key_of = |side: &str, bytes: &[u8]| { + // Both images in one commit on the screenshots ref, each at a path of + // its own test and run. + let path_of = |side: &str, bytes: &[u8]| { shots::image_type(bytes).map(|ct| { - shots::object_key( - &msg.team_id, - &repo, + shots::ref_path( h.pr, &msg.head_sha, h.run_key, @@ -399,33 +373,44 @@ pub async fn keep( ) }) }; - let Some(after_key) = key_of("after", &after_bytes) else { + let Some(after_path) = path_of("after", &after_bytes) else { return; }; - let before = before.and_then(|(b, run_url)| key_of("before", &b).map(|key| (b, key, run_url))); + let before = before.and_then(|(b, run_url)| path_of("before", &b).map(|p| (b, p, run_url))); + let mut files = vec![(after_path.clone(), after_bytes)]; + if let Some((b, p, _)) = &before { + files.push((p.clone(), b.clone())); + } + let short = msg.head_sha.get(..12).unwrap_or(&msg.head_sha); + let commit = match super::preview::keep_on_ref( + gh, + owner, + name, + &format!("End-to-end screenshots of #{} at {short}", h.pr), + &files, + ) + .await + { + Ok(c) => c, + Err(e) => { + warn!(error = %e, repo = %repo, pr = h.pr, "Could not keep the end-to-end screenshots on the screenshots ref"); + return; + } + }; let kept = Kept { pr: h.pr, test: t.full_title(), why: why.words(), base, - before: before.as_ref().map(|(_, key, run_url)| Side { - key: key.clone(), - run_url: run_url.clone(), + before: before.map(|(_, path, run_url)| Side { + src: super::preview::image_url(owner, name, &commit, &path), + run_url, }), after: Side { - key: after_key.clone(), + src: super::preview::image_url(owner, name, &commit, &after_path), run_url: msg.html_url.clone(), }, - expires_at: chrono::Utc::now().timestamp() + shots::LINK_VALID_SECS, }; - if !put(state, &after_key, after_bytes).await { - return; - } - if let Some((b, key, _)) = before { - if !put(state, &key, b).await { - return; - } - } if !claim(state, &msg.team_id, &repo, &msg.head_sha, &kept).await { return; } diff --git a/services/worker/src/passes/preview.rs b/services/worker/src/passes/preview.rs index 8f8ee7721..3106a1e74 100644 --- a/services/worker/src/passes/preview.rs +++ b/services/worker/src/passes/preview.rs @@ -872,7 +872,7 @@ async fn keep_images( files: &[(String, String)], ) -> Result, Box> { let short = head.get(..12).unwrap_or(head); - let mut entries: Vec<(String, Option)> = Vec::new(); + let mut images: Vec<(String, Vec)> = Vec::new(); let mut shots: Vec<(Shot, String)> = Vec::new(); for c in report.iter().filter(|c| c.shot()) { let Some((_, b64)) = files @@ -884,15 +884,7 @@ async fn keep_images( let clean: String = b64.chars().filter(|c| !c.is_whitespace()).collect(); let bytes = base64::engine::general_purpose::STANDARD.decode(clean)?; let path = format!("pr-{}/{short}/{}.png", p.number, c.name); - let sha = gh.put_blob(p.owner, p.repo, &bytes).await?; - entries.push(( - path.clone(), - Some(GitEntry { - mode: "100644".into(), - kind: "blob".into(), - sha, - }), - )); + images.push((path.clone(), bytes)); shots.push(( Shot { page: c.page.clone(), @@ -902,37 +894,88 @@ async fn keep_images( path, )); } - if entries.is_empty() { + if images.is_empty() { return Ok(Vec::new()); } - let parent = gh.own_ref(p.owner, p.repo, SHOTS_REF).await; - let base_tree = match &parent { - Some(c) => gh.commit_tree_parents(p.owner, p.repo, c).await?.0, - None => String::new(), - }; - let tree = gh.put_tree(p.owner, p.repo, &base_tree, &entries).await?; - let commit = gh - .put_commit( - p.owner, - p.repo, - &format!("Screenshots of #{} at {short}", p.number), - &tree, - &parent.into_iter().collect::>(), - ) - .await?; - gh.set_own_ref(p.owner, p.repo, SHOTS_REF, &commit).await?; + let commit = keep_on_ref( + gh, + p.owner, + p.repo, + &format!("Screenshots of #{} at {short}", p.number), + &images, + ) + .await?; Ok(shots .into_iter() .map(|(mut s, path)| { - s.src = format!( - "https://github.com/{}/{}/blob/{commit}/{path}?raw=true", - p.owner, p.repo - ); + s.src = image_url(p.owner, p.repo, &commit, &path); s }) .collect()) } +/// Times a write to [`SHOTS_REF`] is tried again on top of a commit another +/// writer put there first. +const REF_TRIES: usize = 3; + +/// Commits `files` (path and bytes) on top of what [`SHOTS_REF`] holds and +/// moves the ref to the new commit without force, so a commit another +/// writer (another pull request's capture, an end-to-end run) added in the +/// meantime is never dropped; then the commit is built again on top of it. +/// The commit's id, which the images are linked by. +pub async fn keep_on_ref( + gh: &GitHubClient, + owner: &str, + repo: &str, + message: &str, + files: &[(String, Vec)], +) -> Result> { + let mut entries: Vec<(String, Option)> = Vec::new(); + for (path, bytes) in files { + let sha = gh.put_blob(owner, repo, bytes).await?; + entries.push(( + path.clone(), + Some(GitEntry { + mode: "100644".into(), + kind: "blob".into(), + sha, + }), + )); + } + let mut last: Box = "nothing was tried".into(); + for _ in 0..REF_TRIES { + let parent = gh.own_ref(owner, repo, SHOTS_REF).await; + let base_tree = match &parent { + Some(c) => gh.commit_tree_parents(owner, repo, c).await?.0, + None => String::new(), + }; + let tree = gh.put_tree(owner, repo, &base_tree, &entries).await?; + let commit = gh + .put_commit( + owner, + repo, + message, + &tree, + &parent.iter().cloned().collect::>(), + ) + .await?; + match gh + .advance_own_ref(owner, repo, SHOTS_REF, parent.as_deref(), &commit) + .await + { + Ok(()) => return Ok(commit), + Err(e) => last = e, + } + } + Err(format!("{SHOTS_REF} kept moving under this write: {last}").into()) +} + +/// The address of `path` on the screenshots ref at `commit`: it shows only +/// to people who can read the repository. +pub fn image_url(owner: &str, repo: &str, commit: &str, path: &str) -> String { + format!("https://github.com/{owner}/{repo}/blob/{commit}/{path}?raw=true") +} + #[cfg(test)] mod tests { use super::*;