const CANCEL_SITE_FILES: &[(&str, &str)] = &[
("handle_token.rs", include_str!("handle_token.rs")),
(
"handle_token/detector_content.rs",
include_str!("handle_token/detector_content.rs"),
),
("tool_handlers.rs", include_str!("tool_handlers.rs")),
("state.rs", include_str!("state.rs")),
];
const GUARD_MARKERS: &[&str] = &[
"guard_stop = Some(",
"tool_loop_capped = true",
"stop_string_matched = true",
];
const WINDOW: usize = 25;
fn is_dead_path(preceding: &str) -> bool {
preceding.contains("pending_retry = Some(")
}
#[test]
fn every_cancel_flag_store_names_its_guard() {
let mut bare: Vec<String> = Vec::new();
let mut checked = 0usize;
for (name, src) in CANCEL_SITE_FILES {
let lines: Vec<&str> = src.lines().collect();
for (i, line) in lines.iter().enumerate() {
if !line.contains(".store(true") {
continue;
}
let lo = i.saturating_sub(3);
if !lines[lo..=i].iter().any(|l| l.contains("cancel_flag")) {
continue;
}
checked += 1;
let from = i.saturating_sub(WINDOW);
let preceding = lines[from..=i].join("\n");
if is_dead_path(&preceding) {
continue;
}
if !GUARD_MARKERS.iter().any(|m| preceding.contains(m)) {
bare.push(format!("{name}:{}", i + 1));
}
}
}
assert!(
checked >= 4,
"found only {checked} cancel_flag stores — the scan stopped matching. \
Fix the detection before trusting a green here."
);
assert!(
bare.is_empty(),
"cancel_flag flipped without naming a guard at: {bare:?}\n\
A bare cancel reaches the client as finish_reason \"stop\", claiming \
the model finished when it was truncated. Set guard_stop (or \
tool_loop_capped / stop_string_matched) at the site so the wire \
reason is \"length\"."
);
}
#[test]
fn the_scan_would_notice_a_bare_store() {
let synthetic = "\
if streak > MAX {\n\
\x20 tracing::warn!(\"ending stream\");\n\
\x20 state.loop_watchdog_triggered = true;\n\
\x20 state.cancel_flag.store(true, Ordering::Release);\n\
}\n";
let lines: Vec<&str> = synthetic.lines().collect();
let idx = lines
.iter()
.position(|l| l.contains(".store(true"))
.expect("fixture must contain a store");
let preceding = lines[..=idx].join("\n");
assert!(
!GUARD_MARKERS.iter().any(|m| preceding.contains(m)),
"the detector failed to flag a store with no guard marker — it \
would pass the real invariant test vacuously"
);
let fixed = preceding.replace(
"state.loop_watchdog_triggered = true;",
"state.guard_stop = Some(\"suppress_streak\");",
);
assert!(GUARD_MARKERS.iter().any(|m| fixed.contains(m)));
}