use std::collections::HashMap;
use std::fs;
use std::io::{self, Write as _};
use std::path::Path;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use openmoat_hosts::Host;
use crate::home::{self, Home};
const MAX_BYTES: u64 = 64 * 1024;
const WRITE_WAIT: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Phase {
Stdin,
Relay,
Lock,
Context,
Compile,
Taint,
Approval,
Cache,
Record,
Answer,
}
const PHASES: [Phase; 10] = [
Phase::Stdin,
Phase::Relay,
Phase::Lock,
Phase::Context,
Phase::Compile,
Phase::Taint,
Phase::Approval,
Phase::Cache,
Phase::Record,
Phase::Answer,
];
impl Phase {
pub fn name(self) -> &'static str {
match self {
Self::Stdin => "stdin",
Self::Relay => "relay",
Self::Lock => "lock",
Self::Context => "context",
Self::Compile => "compile",
Self::Taint => "taint",
Self::Approval => "approval",
Self::Cache => "cache",
Self::Record => "record",
Self::Answer => "answer",
}
}
pub fn doing(self) -> &'static str {
match self {
Self::Stdin => "reading the tool call",
Self::Relay => "waiting for `openmoat run` to decide",
Self::Lock => "checking the policy lock",
Self::Context => "loading the policy",
Self::Compile => "deciding",
Self::Taint => "reading the session's earlier calls",
Self::Approval => "waiting for an approver's answer",
Self::Cache => "writing the session cache",
Self::Record => "writing the audit log",
Self::Answer => "answering the host",
}
}
pub fn from_name(name: &str) -> Option<Self> {
PHASES.into_iter().find(|p| p.name() == name)
}
}
static CURRENT: AtomicU8 = AtomicU8::new(0);
pub fn enter(phase: Phase) {
let index = PHASES.iter().position(|p| *p == phase).unwrap_or(0);
CURRENT.store(u8::try_from(index).unwrap_or(0), Ordering::Relaxed);
stall_at(phase);
}
#[cfg(debug_assertions)]
const STALL_ENV: &str = "MOAT_TEST_STALL_AT";
#[cfg(debug_assertions)]
fn stall_at(phase: Phase) {
if std::env::var(STALL_ENV).is_ok_and(|v| v == phase.name()) {
loop {
thread::sleep(Duration::from_secs(1));
}
}
}
#[cfg(not(debug_assertions))]
fn stall_at(_: Phase) {}
pub fn current() -> Phase {
PHASES
.get(usize::from(CURRENT.load(Ordering::Relaxed)))
.copied()
.unwrap_or(Phase::Stdin)
}
pub fn record(
home: &Home,
host: Host,
(now_ms, phase, elapsed_ms): (i64, Phase, u128),
then: impl FnOnce() + Send + 'static,
) {
let (done, written) = mpsc::channel();
let path = home.hangs_path();
let line = line(now_ms, host, phase, elapsed_ms);
let writer = thread::Builder::new().spawn(move || {
let _ = append(&path, &line);
then();
let _ = done.send(());
});
if writer.is_ok() {
let _ = written.recv_timeout(WRITE_WAIT);
}
}
fn line(now_ms: i64, host: Host, phase: Phase, elapsed_ms: u128) -> String {
format!("{now_ms} {} {} {elapsed_ms}\n", host.id(), phase.name())
}
fn append(path: &Path, line: &str) -> io::Result<()> {
if let Ok(meta) = fs::symlink_metadata(path)
&& (!meta.is_file() || meta.len() >= MAX_BYTES)
{
return Err(io::ErrorKind::InvalidInput.into());
}
home::private_append_options()
.open(path)?
.write_all(line.as_bytes())
}
#[derive(Debug, PartialEq, Eq)]
pub struct Hangs {
pub count: usize,
pub newest_ms: i64,
pub common_phase: Option<Phase>,
}
pub fn since(path: &Path, since_ms: i64) -> Option<Hangs> {
if !fs::symlink_metadata(path).ok()?.is_file() {
return None;
}
let text = fs::read_to_string(path).ok()?;
let lines: Vec<(i64, Option<Phase>)> = text
.lines()
.filter_map(parse)
.filter(|(ms, _)| *ms >= since_ms)
.collect();
let newest_ms = lines.iter().map(|(ms, _)| *ms).max()?;
let mut counts: HashMap<Phase, usize> = HashMap::new();
for phase in lines.iter().filter_map(|(_, p)| *p) {
*counts.entry(phase).or_default() += 1;
}
let common_phase = PHASES
.into_iter()
.filter_map(|p| Some((p, *counts.get(&p)?)))
.fold(None::<(Phase, usize)>, |best, (p, n)| match best {
Some((_, m)) if m >= n => best,
_ => Some((p, n)),
})
.map(|(p, _)| p);
Some(Hangs {
count: lines.len(),
newest_ms,
common_phase,
})
}
pub fn per_host(path: &Path, since_ms: i64, until_ms: i64) -> Vec<(Host, u64)> {
let Some(text) = fs::symlink_metadata(path)
.ok()
.filter(fs::Metadata::is_file)
.and_then(|_| fs::read_to_string(path).ok())
else {
return Vec::new();
};
let mut counts: HashMap<Host, u64> = HashMap::new();
for line in text.lines() {
let mut fields = line.split(' ');
let Some(ms) = fields.next().and_then(|ms| ms.parse::<i64>().ok()) else {
continue;
};
let Some(host) = fields.next().and_then(|id| id.parse::<Host>().ok()) else {
continue;
};
if (since_ms..until_ms).contains(&ms) {
*counts.entry(host).or_default() += 1;
}
}
Host::EVERY
.into_iter()
.filter_map(|h| Some((h, *counts.get(&h)?)))
.collect()
}
fn parse(line: &str) -> Option<(i64, Option<Phase>)> {
let mut fields = line.split(' ');
let ms = fields.next()?.parse().ok()?;
let phase = fields.nth(1).and_then(Phase::from_name);
Some((ms, phase))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_deadline_and_the_write_wait_end_before_any_host_times_out() {
assert!(WRITE_WAIT < Duration::from_secs(openmoat_hosts::DEADLINE_MARGIN_S));
for host in Host::EVERY {
let spec = host.spec();
let gone = Duration::from_secs(spec.guard_deadline_s()) + WRITE_WAIT;
let limits = spec
.hook_failure
.timeout_s
.map(u64::from)
.into_iter()
.chain(
spec.install
.iter()
.flat_map(|i| i.hooks.iter().map(|h| h.timeout)),
);
for limit in limits {
assert!(
Duration::from_secs(limit) > gone,
"{host:?}: {limit} s leaves no margin after {gone:?}"
);
}
}
}
#[test]
fn concurrent_writers_lose_no_line() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("guard-hangs.log");
let writers: Vec<_> = (0..16)
.map(|i| {
let path = path.clone();
thread::spawn(move || append(&path, &format!("{i} codex stdin 30000\n")).unwrap())
})
.collect();
for writer in writers {
writer.join().unwrap();
}
let text = fs::read_to_string(&path).unwrap();
assert_eq!(text.lines().count(), 16, "{text}");
assert!(text.lines().all(|l| l.split(' ').count() == 4), "{text}");
}
#[test]
fn lines_are_counted_from_a_time_on() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("guard-hangs.log");
assert_eq!(since(&path, 0), None);
for line in ["100 codex\n", "not a line\n", "300 claude-code\n"] {
append(&path, line).unwrap();
}
let all = since(&path, 0).unwrap();
assert_eq!((all.count, all.newest_ms, all.common_phase), (2, 300, None));
assert_eq!(since(&path, 200).unwrap().count, 1);
assert_eq!(since(&path, 301), None);
}
#[test]
fn hangs_are_counted_per_agent_in_a_window() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("guard-hangs.log");
assert_eq!(per_host(&path, 0, i64::MAX), Vec::new());
let (a, b) = (Host::ALL[0], Host::ALL[1]);
for line in [
format!("100 {} record 30001\n", b.id()),
format!("200 {}\n", a.id()),
format!("300 {} lock 30002\n", b.id()),
"250 no-such-agent\n".to_owned(),
"garbage\n".to_owned(),
] {
append(&path, &line).unwrap();
}
assert_eq!(per_host(&path, 0, i64::MAX), [(a, 1), (b, 2)]);
assert_eq!(
per_host(&path, 150, 300),
[(a, 1)],
"the end is not included"
);
assert_eq!(per_host(dir.path(), 0, i64::MAX), Vec::new());
}
#[test]
fn a_full_file_or_a_directory_is_left_alone() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("guard-hangs.log");
fs::write(&path, vec![b'\n'; usize::try_from(MAX_BYTES).unwrap()]).unwrap();
assert!(append(&path, "1 codex\n").is_err());
assert_eq!(fs::metadata(&path).unwrap().len(), MAX_BYTES);
assert!(append(dir.path(), "1 codex\n").is_err());
assert_eq!(since(dir.path(), 0), None);
}
#[test]
fn every_phase_has_a_distinct_name_that_reads_back() {
let mut names: Vec<&str> = PHASES.iter().map(|p| p.name()).collect();
for phase in PHASES {
assert_eq!(Phase::from_name(phase.name()), Some(phase));
enter(phase);
assert_eq!(current(), phase);
}
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), PHASES.len());
assert_eq!(Phase::from_name("nap"), None);
}
#[test]
fn a_line_names_the_time_host_phase_and_elapsed_ms() {
let host = Host::EVERY[0];
let line = line(1_700, host, Phase::Record, 30_012);
assert_eq!(line, format!("1700 {} record 30012\n", host.id()));
assert_eq!(parse(line.trim_end()), Some((1_700, Some(Phase::Record))));
assert_eq!(parse("1700 codex"), Some((1_700, None)), "an older line");
assert_eq!(parse("1700 codex later 5"), Some((1_700, None)));
}
#[test]
fn the_most_common_phase_is_reported_and_older_lines_still_count() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("guard-hangs.log");
let text = "10 codex\n20 codex taint 30001\n30 cursor record 30002\n\
40 claude-code record 30500\n";
fs::write(&path, text).unwrap();
let hangs = since(&path, 0).unwrap();
assert_eq!(hangs.count, 4);
assert_eq!(hangs.newest_ms, 40);
assert_eq!(hangs.common_phase, Some(Phase::Record));
fs::write(&path, "20 codex taint 1\n30 codex record 1\n").unwrap();
assert_eq!(since(&path, 0).unwrap().common_phase, Some(Phase::Taint));
}
}