1use std::path::Path;
17
18use anyhow::{Result, bail};
19
20use crate::queue::{Queue, Source, Task, TaskStatus};
21use crate::run::{RunState, VerifyFlake};
22
23pub const NODE: &str = "flake";
25
26const SIGNATURE_LINES: usize = 16;
28
29const LINE_CLIP: usize = 160;
31
32const MAX_GENERATIONS: u32 = 16;
36
37const FAILURE_WORDS: &[&str] = &[
41 "fail",
42 "panick",
43 "assert",
44 "error",
45 "not ok",
46 "timed out",
47 "timeout",
48 "exception",
49 "traceback",
50 "\u{2717}",
51 "\u{2718}",
52 "\u{d7}",
53];
54
55#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Signature {
59 pub lines: Vec<String>,
61 pub label: String,
63}
64
65fn strip_ansi(line: &str) -> String {
66 let mut out = String::with_capacity(line.len());
67 let mut chars = line.chars();
68 while let Some(c) = chars.next() {
69 if c == '\x1b' && chars.clone().next() == Some('[') {
70 chars.next();
71 for c in chars.by_ref() {
72 if ('@'..='~').contains(&c) {
73 break;
74 }
75 }
76 } else {
77 out.push(c);
78 }
79 }
80 out
81}
82
83fn normalize(line: &str) -> String {
87 let mut out = String::with_capacity(line.len());
88 let mut token = String::new();
89 let flush = |token: &mut String, out: &mut String| {
90 if token.is_empty() {
91 return;
92 }
93 let hex = token.len() >= 8 && token.chars().all(|c| c.is_ascii_hexdigit());
94 if hex || (token.len() >= 7 && token.starts_with("tmp")) {
95 out.push('#');
96 } else {
97 let mut in_digits = false;
98 for c in token.chars() {
99 if c.is_ascii_digit() {
100 if !in_digits {
101 out.push('#');
102 }
103 in_digits = true;
104 } else {
105 in_digits = false;
106 out.push(c);
107 }
108 }
109 }
110 token.clear();
111 };
112 let mut space = false;
113 for c in line.trim().chars() {
114 if c.is_alphanumeric() || c == '_' {
115 if space {
116 out.push(' ');
117 space = false;
118 }
119 token.push(c);
120 } else if c.is_whitespace() {
121 flush(&mut token, &mut out);
122 space = true;
123 } else {
124 flush(&mut token, &mut out);
125 if space {
126 out.push(' ');
127 space = false;
128 }
129 out.push(c);
130 }
131 }
132 flush(&mut token, &mut out);
133 out.chars().take(LINE_CLIP).collect()
134}
135
136fn is_header(line: &str) -> bool {
137 let t = line.trim();
138 t.starts_with("[full output") || t.starts_with("[... output reduced") || t == "[...]"
139}
140
141fn is_failure_line(line: &str) -> bool {
142 let lower = line.trim().to_lowercase();
143 !lower.starts_with("test result: ok") && FAILURE_WORDS.iter().any(|word| lower.contains(word))
144}
145
146pub fn signature(output: &str, code: Option<i32>) -> Signature {
154 let plain: Vec<String> = output
155 .lines()
156 .filter(|l| !is_header(l))
157 .map(strip_ansi)
158 .filter(|l| !l.trim().is_empty())
159 .collect();
160 let failing: Vec<&String> = plain.iter().filter(|l| is_failure_line(l)).collect();
161 let (picked, label): (Vec<&String>, String) = if failing.is_empty() {
162 let tail: Vec<&String> = plain.iter().rev().take(3).rev().collect();
163 let label = tail.first().map(|l| l.trim().to_owned());
164 (tail, label.unwrap_or_default())
165 } else {
166 (failing.clone(), failing[0].trim().to_owned())
167 };
168 let mut lines: Vec<String> = picked.iter().map(|l| normalize(l)).collect();
169 lines.sort();
170 lines.dedup();
171 lines.truncate(SIGNATURE_LINES);
172 if lines.is_empty() {
173 lines.push(format!(
174 "exit code {}",
175 code.map_or("none".into(), |c| c.to_string())
176 ));
177 }
178 let label = if label.is_empty() {
179 lines[0].clone()
180 } else {
181 label.chars().take(100).collect()
182 };
183 Signature { lines, label }
184}
185
186pub fn fingerprint(repo: &Path, signature: &Signature) -> String {
191 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
192 let mut feed = |bytes: &[u8]| {
193 for b in bytes {
194 h ^= u64::from(*b);
195 h = h.wrapping_mul(0x0100_0000_01b3);
196 }
197 };
198 feed(repo.to_string_lossy().as_bytes());
199 for line in &signature.lines {
200 feed(&[0]);
201 feed(line.as_bytes());
202 }
203 format!("{:010x}", h & 0xff_ffff_ffff)
204}
205
206fn task_id(key: &str, generation: u32) -> String {
209 if generation <= 1 {
210 format!("flake-{key}")
211 } else {
212 format!("flake-r{generation}-{key}")
213 }
214}
215
216fn marker(key: &str) -> String {
217 format!("Failure fingerprint: {key}")
218}
219
220fn fenced(text: &str) -> String {
221 let longest = text
224 .split(|c| c != '`')
225 .map(str::len)
226 .max()
227 .unwrap_or(0)
228 .max(2);
229 let fence = "`".repeat(longest + 1);
230 format!("{fence}\n{}\n{fence}", text.trim_end())
231}
232
233fn build_task(state: &RunState, flake: &VerifyFlake, label: &str, id: String) -> Task {
234 let excerpt = crate::scrub::scrub(&flake.first_failure, &crate::scrub::Identity::current());
235 let instruction = format!(
236 "A verification command failed once and then passed when it was run again on the \
237 same commit, so magi recorded the failure as a flake instead of charging it to the \
238 change that was being verified. Find the root cause of the intermittent failure and \
239 fix it.\n\n\
240 Fix the cause, not the symptom: do not loosen the assertion, add a retry, raise a \
241 timeout or skip the check to make it quieter. Typical causes are a race or an \
242 ordering assumption in the code or the test, shared state between tests (a fixed \
243 port, a shared directory, process-global state), a time-based wait that is too \
244 tight under load, and a layout or timing measurement taken before the page or \
245 process settled. To reproduce, run the check repeatedly and with several copies at \
246 once. If it no longer fails on current main after a serious attempt, say so and \
247 change nothing.\n\n\
248 {marker}\n\
249 Command: `{command}`\n\
250 Seen in run {run} ({context}) on commit {head}\n\n\
251 ## First failure (the rerun passed)\n\n{excerpt}\n",
252 marker = marker(&flake.fingerprint),
253 command = flake.command,
254 run = state.id,
255 context = flake.context,
256 head = flake.head,
257 excerpt = fenced(&excerpt),
258 );
259 let mut task = Task::new(
260 crate::queue::title_from(&format!("flaky verification: {label}"), 90),
261 instruction,
262 state.repo.clone(),
263 Source::Agent {
264 run: state.id.clone(),
265 node: NODE.to_owned(),
266 },
267 );
268 task.id = id;
269 task.solo = true;
270 task
271}
272
273pub fn file(
281 state: &RunState,
282 flake: &VerifyFlake,
283 label: &str,
284 queue: &Queue,
285) -> Result<(String, bool)> {
286 for generation in 1..=MAX_GENERATIONS {
287 let id = task_id(&flake.fingerprint, generation);
288 let mut task = build_task(state, flake, label, id.clone());
289 let chat_cfg = crate::task_chat::prepare_filing(queue, &mut task);
290 if queue.create_new(&mut task)? {
291 crate::task_chat::finish_filing(queue, &mut task, chat_cfg.as_ref());
292 return Ok((id, true));
293 }
294 let existing = queue.get(&id)?;
295 if existing.status != TaskStatus::Done {
296 return Ok((id, false));
297 }
298 }
299 bail!("{MAX_GENERATIONS} earlier tasks for this failure are already done")
300}
301
302pub fn record(state: &mut RunState, mut flake: VerifyFlake, label: &str, queue: &Queue) {
305 match file(state, &flake, label, queue) {
306 Ok((id, created)) => {
307 state.event(
308 "verify",
309 format!(
310 "{}: `{}` failed, then passed on the same commit {} - a flake, not a \
311 verdict on the change; {} task {id} (failure {})",
312 flake.context,
313 flake.command,
314 short(&flake.head),
315 if created {
316 "filed"
317 } else {
318 "already tracked by"
319 },
320 flake.fingerprint,
321 ),
322 );
323 flake.task = Some(id);
324 flake.filed = created;
325 }
326 Err(e) => {
327 state.event(
328 "verify",
329 format!(
330 "{}: `{}` failed, then passed on the same commit {} - a flake, not a \
331 verdict on the change; no task could be filed: {e:#}",
332 flake.context,
333 flake.command,
334 short(&flake.head),
335 ),
336 );
337 flake.filing_error = Some(format!("{e:#}"));
338 }
339 }
340 state.verify_flakes.push(flake);
341}
342
343fn short(commit: &str) -> String {
344 commit.chars().take(7).collect()
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350
351 fn sig(text: &str) -> Signature {
352 signature(text, Some(101))
353 }
354
355 #[test]
356 fn the_same_failure_has_one_signature_whatever_the_numbers_and_order() {
357 let a = "[full output: artifacts/e2e-1.out]\n\
358 running 3 tests\n\
359 test web::tests::layout ... FAILED\n\
360 test talk::tests::turn ... FAILED\n\
361 thread 'web::tests::layout' panicked at src/web.rs:101:9:\n\
362 timed out after 5.31s waiting for 17 rows\n\
363 test result: FAILED. 1 passed; 2 failed; 0 ignored; finished in 6.02s\n";
364 let b = "[full output: artifacts/e2e-4.out]\n\
365 running 3 tests\n\
366 test talk::tests::turn ... FAILED\n\
367 thread 'web::tests::layout' panicked at src/web.rs:101:9:\n\
368 timed out after 7.9s waiting for 4 rows\n\
369 test web::tests::layout ... FAILED\n\
370 test result: FAILED. 1 passed; 2 failed; 0 ignored; finished in 8.11s\n";
371 assert_eq!(sig(a).lines, sig(b).lines);
372 let repo = Path::new("/repo");
373 assert_eq!(fingerprint(repo, &sig(a)), fingerprint(repo, &sig(b)));
374 }
375
376 #[test]
377 fn a_different_failing_test_is_a_different_failure() {
378 let a = "test web::tests::layout ... FAILED\n";
379 let b = "test talk::tests::turn ... FAILED\n";
380 let repo = Path::new("/repo");
381 assert_ne!(fingerprint(repo, &sig(a)), fingerprint(repo, &sig(b)));
382 assert_ne!(
383 fingerprint(Path::new("/one"), &sig(a)),
384 fingerprint(Path::new("/two"), &sig(a)),
385 "the same text in another repository is another defect"
386 );
387 }
388
389 #[test]
390 fn passing_noise_does_not_enter_the_signature() {
391 let s = sig(
392 "test a ... ok\ntest result: ok. 12 passed; 0 failed; 0 ignored\n\
393 test b ... FAILED\n",
394 );
395 assert_eq!(s.lines, vec!["test b ... FAILED".to_owned()]);
396 assert_eq!(s.label, "test b ... FAILED");
397 }
398
399 #[test]
400 fn output_without_a_failure_word_falls_back_to_its_tail_then_the_exit_code() {
401 assert_eq!(
402 sig("one\ntwo\nthree\nfour\n").lines,
403 ["four", "three", "two"]
404 );
405 assert_eq!(sig("").lines, ["exit code 101"]);
406 assert_eq!(signature("", None).lines, ["exit code none"]);
407 }
408
409 #[test]
410 fn random_names_and_hashes_are_normalised_away() {
411 let a = normalize("error: C:\\Temp\\.tmpAbC123 at deadbeef01 in 12ms");
412 let b = normalize("error: C:\\Temp\\.tmpZzZ999 at 0123abcd99 in 7ms");
413 assert_eq!(a, b);
414 }
415
416 #[test]
417 fn a_task_per_failure_is_filed_once_and_a_finished_one_does_not_cover() {
418 let dir = tempfile::tempdir().unwrap();
419 let queue = Queue::at(dir.path().join("queue"));
420 let state = RunState::new(
421 Path::new("/repo").to_path_buf(),
422 "main".into(),
423 "abc1234".into(),
424 "make a note".into(),
425 crate::config::Config::default(),
426 );
427 let s = sig("test web::tests::layout ... FAILED\n");
428 let flake = VerifyFlake {
429 round: Some(1),
430 context: "round 1".into(),
431 head: "abcdef1234567890".into(),
432 command: "cargo test".into(),
433 first_failure: "test web::tests::layout ... FAILED".into(),
434 fingerprint: fingerprint(&state.repo, &s),
435 at: jiff::Timestamp::now(),
436 task: None,
437 filed: false,
438 filing_error: None,
439 };
440 let (first, created) = file(&state, &flake, &s.label, &queue).unwrap();
441 assert!(created);
442 let (again, created) = file(&state, &flake, &s.label, &queue).unwrap();
443 assert_eq!((again.as_str(), created), (first.as_str(), false));
444 assert_eq!(queue.list().len(), 1);
445 let task = queue.get(&first).unwrap();
446 assert!(task.instruction.contains(&marker(&flake.fingerprint)));
447 assert!(task.instruction.contains("not the symptom"));
448 assert!(matches!(&task.source, Source::Agent { node, .. } if node == NODE));
449
450 queue
451 .modify(&first, |t| {
452 t.status = TaskStatus::Done;
453 true
454 })
455 .unwrap();
456 let (next, created) = file(&state, &flake, &s.label, &queue).unwrap();
457 assert!(created, "a recurrence after the task was done is new work");
458 assert_ne!(next, first);
459 assert_eq!(crate::queue::short(&next), crate::queue::short(&first));
460 }
461}