1use crate::utils::calculate_sha256;
12
13const MAX_SITE_CHARS: usize = 120;
15const FINGERPRINT_CHARS: usize = 16;
17const MARKER_WINDOW_BYTES: usize = 512;
22const MAX_MARKER_ATTEMPTS: usize = 64;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
27pub enum VerificationFailureKind {
28 Panic,
30 TestFailed,
32 CompileError,
34 Timeout,
36 #[default]
38 Other,
39}
40
41impl VerificationFailureKind {
42 #[must_use]
44 pub const fn as_str(self) -> &'static str {
45 match self {
46 Self::Panic => "panic",
47 Self::TestFailed => "test",
48 Self::CompileError => "compile",
49 Self::Timeout => "timeout",
50 Self::Other => "other",
51 }
52 }
53}
54
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
59pub struct VerificationFailureShape {
60 pub kind: VerificationFailureKind,
62 pub site: Option<String>,
64 pub fingerprint: Option<String>,
68}
69
70impl VerificationFailureShape {
71 #[must_use]
79 pub fn describe(&self) -> String {
80 let base = match self.site.as_deref() {
81 Some(site) => format!("{} at {site}", self.kind.as_str()),
82 None => self.kind.as_str().to_string(),
83 };
84 match self.fingerprint.as_deref() {
85 Some(fingerprint) => format!("{base} (fingerprint {fingerprint})"),
86 None => base,
87 }
88 }
89}
90
91#[must_use]
110pub fn repeated_shape_note(streak: u8) -> String {
111 if streak >= 2 {
112 format!(
113 " This failure shape has repeated {streak} times consecutively; change your approach instead of \
114 retrying the same fix."
115 )
116 } else {
117 String::new()
118 }
119}
120
121#[must_use]
141pub fn extract_verification_failure_shape(output: &str) -> VerificationFailureShape {
142 let (kind, site) = classify(output);
143 let fingerprint = fingerprint(kind, site.as_deref());
144 VerificationFailureShape { kind, site, fingerprint }
145}
146
147fn classify(output: &str) -> (VerificationFailureKind, Option<String>) {
148 if let Some(site) = location_after(output, "panicked at ") {
149 return (VerificationFailureKind::Panic, Some(site));
150 }
151 if let Some(name) = failed_test_name(output) {
152 return (VerificationFailureKind::TestFailed, Some(name));
153 }
154 if output.contains("test result: FAILED") {
155 return (VerificationFailureKind::TestFailed, None);
156 }
157 if output.contains("error[E") || output.contains("error: could not compile") {
158 return (VerificationFailureKind::CompileError, location_after(output, "--> "));
159 }
160 let lowered = output.to_ascii_lowercase();
161 if is_timeout(&lowered) {
162 return (VerificationFailureKind::Timeout, None);
163 }
164 if output.contains("panicked at ") {
167 return (VerificationFailureKind::Panic, None);
168 }
169 (VerificationFailureKind::Other, None)
170}
171
172fn is_timeout(lowered: &str) -> bool {
176 if lowered.contains("timed out") {
177 return true;
178 }
179 const FAILURE_CONTEXT: [&str; 7] = ["error", "fail", "exceed", "expire", "killed", "abort", "deadline"];
180 lowered.contains("timeout") && FAILURE_CONTEXT.iter().any(|word| lowered.contains(word))
181}
182
183fn failed_test_name(output: &str) -> Option<String> {
185 let mut rest = output;
186 for _ in 0..MAX_MARKER_ATTEMPTS {
187 let Some((_, after)) = rest.split_once("test ") else {
188 break;
189 };
190 let window = bounded_window(after).trim_start();
193 let Some(name) = window.split_whitespace().next() else {
194 rest = after;
195 continue;
196 };
197 if !name.is_empty()
201 && !name.contains(['\n', '"', '\\'])
202 && window.strip_prefix(name).is_some_and(|tail| tail.starts_with(" ... FAILED"))
203 {
204 return Some(bound_site(name));
205 }
206 rest = after;
207 }
208
209 let mut rest = output;
213 for _ in 0..MAX_MARKER_ATTEMPTS {
214 let Some((_, after)) = rest.split_once("---- ") else {
215 break;
216 };
217 let window = bounded_window(after);
218 if let Some((name, _)) = window.split_once(" stdout ----")
219 && !name.is_empty()
220 && !name.contains(['\n', '"', '\\'])
221 {
222 return Some(bound_site(name));
223 }
224 rest = after;
225 }
226 None
227}
228
229fn bounded_window(text: &str) -> &str {
231 if text.len() <= MARKER_WINDOW_BYTES {
232 return text;
233 }
234 let mut end = MARKER_WINDOW_BYTES;
235 while !text.is_char_boundary(end) {
236 end -= 1;
237 }
238 text.get(..end).unwrap_or(text)
239}
240
241fn location_after(output: &str, marker: &str) -> Option<String> {
243 let (_, after) = output.split_once(marker)?;
244 let token = after
245 .split(|c: char| c.is_whitespace() || matches!(c, '"' | '\\'))
246 .next()?
247 .trim_end_matches(':');
248 normalize_location(token)
249}
250
251fn normalize_location(token: &str) -> Option<String> {
252 let mut segments = token.rsplitn(3, ':');
253 let first = segments.next()?;
254 let second = segments.next();
255 let third = segments.next();
256 let (line, path) = match (second, third) {
257 (Some(line), Some(path)) if is_number(first) => (line, path),
258 (Some(path), None) => (first, path),
259 _ => return None,
260 };
261 if !is_number(line) {
262 return None;
263 }
264 let file = path.rsplit(['/', '\\']).next().unwrap_or(path);
265 Some(bound_site(&format!("{file}:{line}")))
266}
267
268fn is_number(text: &str) -> bool {
269 !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())
270}
271
272fn bound_site(text: &str) -> String {
273 text.chars().take(MAX_SITE_CHARS).collect()
274}
275
276fn fingerprint(kind: VerificationFailureKind, site: Option<&str>) -> Option<String> {
277 if kind == VerificationFailureKind::Other {
278 return None;
279 }
280 let input = format!("{}|{}", kind.as_str(), site.unwrap_or(""));
281 let digest = calculate_sha256(input.as_bytes());
282 debug_assert!(digest.len() >= FINGERPRINT_CHARS && digest.is_ascii(), "sha256 hex digest invariant violated");
283 Some(digest.get(..FINGERPRINT_CHARS).unwrap_or_default().to_string())
285}
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290
291 #[test]
292 fn test_failure_localizes_the_individual_test_name() {
293 let shape = extract_verification_failure_shape(
294 "running 3 tests\ntest auth::expired_token ... FAILED\ntest cache::hit ... ok\n",
295 );
296
297 assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
298 assert_eq!(shape.site.as_deref(), Some("auth::expired_token"));
299 assert!(shape.describe().contains("auth::expired_token"), "{}", shape.describe());
300 }
301
302 #[test]
303 fn test_summary_without_an_individual_name_keeps_the_kind_but_no_site() {
304 let shape = extract_verification_failure_shape("test result: FAILED. 1 failed, 2 passed");
305
306 assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
307 assert_eq!(shape.site, None);
308 }
309
310 #[test]
311 fn panic_localizes_the_trailing_file_and_line_not_the_full_path() {
312 let shape = extract_verification_failure_shape(
313 "thread 'main' panicked at /Users/someone/project/crates/foo/src/lib.rs:42:9:\nassertion failed",
314 );
315
316 assert_eq!(shape.kind, VerificationFailureKind::Panic);
317 assert_eq!(shape.site.as_deref(), Some("lib.rs:42"));
318 assert!(!shape.describe().contains("/Users/"), "site must not leak an absolute path");
319 }
320
321 #[test]
322 fn compile_error_uses_the_arrow_location() {
323 let shape = extract_verification_failure_shape("error[E0308]: mismatched types\n --> src/main.rs:7:5\n");
324
325 assert_eq!(shape.kind, VerificationFailureKind::CompileError);
326 assert_eq!(shape.site.as_deref(), Some("main.rs:7"));
327 }
328
329 #[test]
330 fn timeout_is_recognized_without_a_site() {
331 let shape = extract_verification_failure_shape("Error: operation timed out after 30s");
332
333 assert_eq!(shape.kind, VerificationFailureKind::Timeout);
334 assert_eq!(shape.site, None);
335 }
336
337 #[test]
338 fn json_escaped_output_is_recognized_like_plain_text() {
339 let escaped = r#"{"exit_code":1,"output":"test auth::expired_token ... FAILED\nboom"}"#;
340 let shape = extract_verification_failure_shape(escaped);
341
342 assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
343 assert_eq!(shape.site.as_deref(), Some("auth::expired_token"));
344 }
345
346 #[test]
347 fn equivalent_failures_share_a_fingerprint_but_distinct_sites_do_not() {
348 let first = extract_verification_failure_shape("test auth::expired ... FAILED\nassertion a == b failed");
349 let same_bug = extract_verification_failure_shape("test auth::expired ... FAILED\nleft == right differs");
350 let other_bug = extract_verification_failure_shape("test cache::expired ... FAILED\nassertion a == b failed");
351
352 let first_fp = first.fingerprint.as_deref().expect("fingerprint");
353 assert_eq!(first_fp, same_bug.fingerprint.as_deref().expect("fingerprint"));
354 assert_ne!(first_fp, other_bug.fingerprint.as_deref().expect("fingerprint"));
355 assert_eq!(first_fp.len(), FINGERPRINT_CHARS);
356 assert!(first_fp.bytes().all(|byte| byte.is_ascii_hexdigit()));
357 }
358
359 #[test]
360 fn oversized_test_names_are_bounded_on_both_sides_of_the_limit() {
361 let under_limit = extract_verification_failure_shape(&format!("test {} ... FAILED", "a".repeat(119)));
362 assert_eq!(under_limit.site.as_ref().expect("site").chars().count(), 119);
363
364 let over_limit = extract_verification_failure_shape(&format!("test {} ... FAILED", "b".repeat(200)));
365 assert_eq!(over_limit.site.as_ref().expect("site").chars().count(), MAX_SITE_CHARS);
366 assert_eq!(over_limit.fingerprint.as_deref().expect("fingerprint").len(), FINGERPRINT_CHARS);
367 assert_ne!(under_limit.fingerprint, over_limit.fingerprint);
368 }
369
370 #[test]
371 fn unrecognized_output_has_no_grouping_fingerprint() {
372 let first = extract_verification_failure_shape("something odd happened");
373 let second = extract_verification_failure_shape("a completely different oddity");
374
375 assert_eq!(first.kind, VerificationFailureKind::Other);
376 assert_eq!(first.site, None);
377 assert_eq!(first.fingerprint, None);
378 assert_eq!(second.fingerprint, None);
379 assert!(!first.describe().contains("fingerprint"), "{}", first.describe());
380 }
381
382 #[test]
383 fn captured_output_header_localizes_even_when_the_failed_line_is_cut() {
384 let shape =
385 extract_verification_failure_shape("---- auth::expired_token stdout ----\nassertion failed: left == right");
386
387 assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
388 assert_eq!(shape.site.as_deref(), Some("auth::expired_token"));
389 assert!(shape.fingerprint.is_some());
390 }
391
392 #[test]
393 fn arbitrary_output_content_never_appears_in_the_description() {
394 let secret = "SECRET_USER_TOKEN_XYZ";
395 let shape = extract_verification_failure_shape(&format!("leftover {secret} after the failure"));
396
397 assert!(!shape.describe().contains(secret), "{}", shape.describe());
398 assert_eq!(shape.kind, VerificationFailureKind::Other);
399 }
400
401 #[test]
402 fn panic_without_a_parseable_location_keeps_the_kind_but_no_site() {
403 let shape = extract_verification_failure_shape("thread 'main' panicked at 'assertion failed'");
404
405 assert_eq!(shape.kind, VerificationFailureKind::Panic);
406 assert_eq!(shape.site, None);
407 assert!(shape.fingerprint.is_some(), "kind-only failures still group");
408 }
409
410 #[test]
411 fn timeout_mention_without_failure_context_is_not_a_timeout() {
412 for output in [
413 "setting timeout=30s for cache\nall green",
414 "request timeout: 5s (default)\nerror[E0308]: mismatched types",
415 ] {
416 let shape = extract_verification_failure_shape(output);
417 assert_ne!(shape.kind, VerificationFailureKind::Timeout, "{output}");
418 }
419 let compile = extract_verification_failure_shape("request timeout: 5s\nerror[E0308]: boom");
421 assert_eq!(compile.kind, VerificationFailureKind::CompileError);
422 }
423
424 #[test]
425 fn timeout_with_failure_context_keeps_the_kind() {
426 let mut fingerprints = Vec::new();
427 for output in [
428 "Error: connection timeout on upstream",
429 "Timeout exceeded after 3 retries",
430 ] {
431 let shape = extract_verification_failure_shape(output);
432 assert_eq!(shape.kind, VerificationFailureKind::Timeout, "{output}");
433 assert_eq!(shape.site, None);
434 fingerprints.push(shape.fingerprint.clone().expect("fingerprint"));
435 }
436 assert_eq!(fingerprints[0], fingerprints[1]);
439 }
440
441 #[test]
442 fn siteless_panics_share_one_kind_level_fingerprint() {
443 let first = extract_verification_failure_shape("thread 'main' panicked at 'assertion failed'");
444 let second = extract_verification_failure_shape("thread 'worker' panicked at 'index out of bounds'");
445
446 assert_eq!(first.kind, VerificationFailureKind::Panic);
447 assert_eq!(second.kind, VerificationFailureKind::Panic);
448 assert_eq!(first.fingerprint, second.fingerprint);
449 assert_ne!(
450 first.fingerprint,
451 extract_verification_failure_shape("Error: operation timed out").fingerprint,
452 "kind levels must not collide across kinds"
453 );
454 }
455
456 #[test]
457 fn json_escaped_panic_keeps_the_kind_without_a_site() {
458 let escaped = r#"{"exit_code":101,"output":"thread 'main' panicked at src\/lib.rs:42:9\nboom"}"#;
461 let shape = extract_verification_failure_shape(escaped);
462
463 assert_eq!(shape.kind, VerificationFailureKind::Panic);
464 assert_eq!(shape.site, None);
465 assert!(shape.fingerprint.is_some());
466 }
467
468 #[test]
469 fn quoted_or_escaped_test_name_is_rejected() {
470 let shape = extract_verification_failure_shape(r#"test injected\"name ... FAILED"#);
471
472 assert_eq!(shape.kind, VerificationFailureKind::Other);
475 assert_eq!(shape.site, None);
476 assert_eq!(shape.fingerprint, None);
477 }
478
479 #[test]
480 fn extra_whitespace_between_test_and_name_still_localizes() {
481 let shape = extract_verification_failure_shape("test foo ... FAILED");
482
483 assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
484 assert_eq!(shape.site.as_deref(), Some("foo"));
485 }
486
487 #[test]
488 fn multibyte_site_is_bounded_by_chars_not_bytes() {
489 let shape = extract_verification_failure_shape(&format!("test {} ... FAILED", "é".repeat(200)));
492
493 assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
494 let site = shape.site.as_deref().expect("site");
495 assert_eq!(site.chars().count(), MAX_SITE_CHARS);
496 assert!(site.is_char_boundary(site.len()));
497 }
498
499 #[test]
500 fn repeated_shape_note_emits_only_from_the_second_sighting() {
501 assert!(repeated_shape_note(0).is_empty());
502 assert!(repeated_shape_note(1).is_empty());
503
504 let note = repeated_shape_note(3);
505 assert!(note.contains("3 times consecutively"), "{note}");
506 assert!(note.contains("change your approach"), "{note}");
507 }
508}