Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions native/guard/src/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,36 @@ pub fn holds_proof(health: &serde_json::Value) -> bool {
health["folding"].as_u64().unwrap_or(0) > 0 || health["migrating"]["state"] == "running" || health["status"] == "migrating"
}

/// Whether a probe proves this build started cleanly: requires a healthy (`well`) answer, not already stable,
/// no fold/migration holding proof, and `up_s >= need_s` awake seconds since ready.
pub fn proven(well: bool, body: &serde_json::Value, stable: bool, up_s: u64, need_s: u64) -> bool {
well && !stable && !holds_proof(body) && up_s >= need_s
}

/// The machine slept since the last look: the wall clock moved this much more than the suspend-excluding awake clock.
/// A clock set by hand or by NTP can look the same; that only costs a short grace.
pub const SLEEP_JUMP_S: u64 = 10;
/// How long after a wake a failed health check is not counted: a Mac's DarkWake lasts about 2 s, too short for the hub's 10 s checks to run, and
/// a full wake gives the hub one round of them to catch up.
pub const WAKE_GRACE_S: u64 = 30;
/// Tells a sleep from a hang. `tick` each turn of the guard's loop: true when the machine slept since the last tick.
pub struct SleepClock { last: Option<(std::time::SystemTime, u64)>, woke: Option<u64> }
impl SleepClock {
pub fn new() -> SleepClock { SleepClock { last: None, woke: None } }
pub fn tick(&mut self, wall: std::time::SystemTime, awake_s: u64) -> bool {
let slept = self.last.map_or(false, |(w, a)| {
let dw = wall.duration_since(w).map_or(0, |d| d.as_secs());
let da = awake_s.saturating_sub(a);
dw > da + SLEEP_JUMP_S
});
self.last = Some((wall, awake_s));
if slept { self.woke = Some(awake_s) }
slept
}
/// Whether `awake_s` is within the grace after the last wake.
pub fn waking(&self, awake_s: u64) -> bool { self.woke.map_or(false, |w| awake_s.saturating_sub(w) < WAKE_GRACE_S) }
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -275,4 +305,52 @@ mod tests {
assert!(!holds_proof(&json!({"status": "ok", "folding": 0, "migrating": null})));
assert!(!holds_proof(&serde_json::Value::Null), "an old build's /hello says neither");
}

#[test]
fn a_sleep_is_told_from_a_hang_by_the_two_clocks() {
use std::time::{Duration, SystemTime};

let mut clock = SleepClock::new();
let mut wall = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
let mut awake = 100u64;

assert!(!clock.tick(wall, awake));
assert!(!clock.waking(awake));

// Normal awake advance (5s wall, 5s awake): not sleep.
wall += Duration::from_secs(5);
awake += 5;
assert!(!clock.tick(wall, awake));
assert!(!clock.waking(awake));

// 17-minute lid-close sleep: wall jumps 1020s while awake clock ticks only 1s.
wall += Duration::from_secs(17 * 60);
awake += 1;
assert!(clock.tick(wall, awake));
assert!(clock.waking(awake));
assert!(clock.waking(awake + WAKE_GRACE_S - 1));
assert!(!clock.waking(awake + WAKE_GRACE_S));

// Normal ticks right after waking stay false without clearing the grace window early.
wall += Duration::from_secs(SLEEP_JUMP_S - 5);
awake += SLEEP_JUMP_S - 5;
assert!(!clock.tick(wall, awake));
assert!(clock.waking(awake));

// Backward wall-clock jump (e.g. NTP step) is not treated as sleep.
wall -= Duration::from_secs(60);
awake += 2;
assert!(!clock.tick(wall, awake));
}

#[test]
fn a_failed_probe_never_proves_a_build_even_past_stable() {
use serde_json::json;
assert!(!proven(false, &serde_json::Value::Null, false, 120, 60));
assert!(!proven(false, &json!({"status": "starting"}), false, 120, 60));
assert!(!proven(true, &json!({"status": "ok", "folding": 1}), false, 120, 60));
assert!(!proven(true, &json!({"status": "ok", "folding": 0}), false, 59, 60));
assert!(proven(true, &json!({"status": "ok", "folding": 0}), false, 60, 60));
assert!(!proven(true, &json!({"status": "ok", "folding": 0}), true, 120, 60));
}
}
28 changes: 20 additions & 8 deletions native/guard/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,14 @@ impl Guard {
self.stable = false; self.hub_pid = 0; self.set("starting");
let mut child = match self.spawn() { Ok(c) => c, Err(e) => return e };
self.hub_pid = child.id(); self.pin(); self.publish();
let (t0, mut ready_at, mut misses, mut last_probe, mut last_said) = (Instant::now(), None::<Instant>, 0u32, Instant::now(), String::new());
let (t0, mut ready_at, mut misses, mut last_probe, mut last_said) = (Instant::now(), None::<u64>, 0u32, Instant::now(), String::new());
let start_awake = sys::awake_s();
// the start's progress on the suspend-excluding awake clock (`sys::awake_s`): both the phase file's age by the wall clock
// and Windows QPC/`Instant` count a night's sleep as a stall ("start stalled for 904 s" at the first wake after sleep, #1607 / #1497)
let (mut phase_seen, mut phase_at) = (None::<std::time::SystemTime>, start_awake);
let mut clock = plan::SleepClock::new();
loop {
if clock.tick(std::time::SystemTime::now(), sys::awake_s()) { misses = 0; say("the machine slept; health checks start counting again"); }
if sys::stop_asked() { self.quit(Some(&mut child)) }
match child.try_wait() {
Ok(Some(s)) => { self.hub_pid = 0; return self.classify(s) }
Expand All @@ -264,6 +270,7 @@ impl Guard {
if last_probe.elapsed().as_secs() >= self.tm.probe {
last_probe = Instant::now(); self.watch_space();
let (answered, well, said, control) = self.probe();
if clock.tick(std::time::SystemTime::now(), sys::awake_s()) { misses = 0; say("the machine slept; health checks start counting again"); }
if well {
let down: Vec<String> = serde_json::from_str::<Value>(&said).ok().and_then(|v| v["degraded"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())).unwrap_or_default();
// on probation, a part the build before had running and this one has not is the update failing: a start step panicked or ran out of time
Expand All @@ -279,19 +286,24 @@ impl Guard {
let why = self.wrong_build(&said).unwrap_or_default(); say(&format!("{} is not the build it was staged as: {why}; ending it", Self::short(&self.build)));
sys::stop_child(&mut child, 10_000); self.hub_pid = 0; return End::Failed(why)
}
None if well => { ready_at = Some(Instant::now()); say(&format!("{} answers, {} ms after its start", Self::short(&self.build), t0.elapsed().as_millis())); self.set(if self.mode == Mode::Safe { "safe" } else { "running" }); if control && !self.has_control(&self.build) { let mut c = self.d.lines("control"); c.push(self.build.clone()); let from = c.len().saturating_sub(32); let _ = self.d.put("control", &(c[from..].join("\n") + "\n")); } }
None if well => { ready_at = Some(sys::awake_s()); say(&format!("{} answers, {} ms after its start", Self::short(&self.build), t0.elapsed().as_millis())); self.set(if self.mode == Mode::Safe { "safe" } else { "running" }); if control && !self.has_control(&self.build) { let mut c = self.d.lines("control"); c.push(self.build.clone()); let from = c.len().saturating_sub(32); let _ = self.d.put("control", &(c[from..].join("\n") + "\n")); } }
None => {
let quiet = fs::metadata(self.d.path("phase")).ok().and_then(|m| m.modified().ok()).and_then(|m| m.elapsed().ok()).map_or(t0.elapsed().as_secs(), |e| e.as_secs());
if quiet >= self.tm.stall || t0.elapsed().as_secs() >= self.tm.boot { let ph = self.d.text("phase"); return self.kill_hung(&mut child, &format!("start stalled for {quiet} s at {}", if ph.trim().is_empty() { "its first step" } else { ph.trim() })) }
let now_awake = sys::awake_s();
let m = fs::metadata(self.d.path("phase")).ok().and_then(|m| m.modified().ok());
if m.is_some() && m != phase_seen { phase_seen = m; phase_at = now_awake; }
let quiet = now_awake.saturating_sub(phase_at);
if quiet >= self.tm.stall || now_awake.saturating_sub(start_awake) >= self.tm.boot { let ph = self.d.text("phase"); return self.kill_hung(&mut child, &format!("start stalled for {quiet} s at {}", if ph.trim().is_empty() { "its first step" } else { ph.trim() })) }
}
Some(at) => {
if well || answered { misses = 0 } else { misses += 1; last_said = said.clone(); say(&format!("health check {misses} of {} failed: {}", self.tm.misses, said.chars().take(160).collect::<String>())) }
let now_awake = sys::awake_s();
if well || answered { misses = 0 } else if clock.waking(now_awake) { say(&format!("health check failed just after a wake, not counted: {}", said.chars().take(160).collect::<String>())) } else { misses += 1; last_said = said.clone(); say(&format!("health check {misses} of {} failed: {}", self.tm.misses, said.chars().take(160).collect::<String>())) }
if misses >= self.tm.misses { let why = format!("stopped answering: {}", last_said.chars().take(160).collect::<String>()); return self.kill_hung(&mut child, &why) }
// the clock that proves a build starts when its folds and any migration are over: a crash at the end of a long fold or import is the
// start failing, while a long import itself is not (plan::holds_proof)
let busy = plan::holds_proof(&serde_json::from_str::<Value>(&said).unwrap_or(Value::Null));
if busy { ready_at = Some(Instant::now()); }
if !busy && !self.stable && at.elapsed().as_secs() >= self.tm.stable { self.stable = true; self.d.add_good(&self.build); self.pin(); say(&format!("{} started cleanly", Self::short(&self.build))); if self.probation.take().is_some() { if let Some(b) = &self.b { b.publish(&self.build); } } self.publish(); }
let body = serde_json::from_str::<Value>(&said).unwrap_or(Value::Null);
let busy = plan::holds_proof(&body);
if busy { ready_at = Some(now_awake); }
if plan::proven(well, &body, self.stable, now_awake.saturating_sub(at), self.tm.stable) { self.stable = true; self.d.add_good(&self.build); self.pin(); say(&format!("{} started cleanly", Self::short(&self.build))); if self.probation.take().is_some() { if let Some(b) = &self.b { b.publish(&self.build); } } self.publish(); }
}
}
}
Expand Down
19 changes: 17 additions & 2 deletions native/guard/src/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ use std::{path::Path, process::{Child, Command, ExitStatus}};
}
pub fn detach(c: &mut std::process::Command) { use std::os::unix::process::CommandExt; unsafe { c.pre_exec(|| { libc::setsid(); Ok(()) }); } }
pub fn signal_of(s: &std::process::ExitStatus) -> Option<i32> { use std::os::unix::process::ExitStatusExt; s.signal() }
/// Monotonic awake seconds since first call (pauses while macOS/Linux sleeps).
pub fn awake_s() -> u64 {
static T0: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
T0.get_or_init(std::time::Instant::now).elapsed().as_secs()
}
}
#[cfg(windows)] mod os {
pub fn watch_stop() {}
Expand All @@ -41,7 +46,17 @@ use std::{path::Path, process::{Child, Command, ExitStatus}};
pub fn term(pid: u32) { let _ = quiet("taskkill").args(["/PID", &pid.to_string()]).output(); }
pub fn abort(pid: u32) { let _ = quiet("taskkill").args(["/F", "/PID", &pid.to_string()]).output(); }
pub fn alive(pid: u32) -> bool { quiet("tasklist").args(["/FI", &format!("PID eq {pid}"), "/NH"]).output().map_or(false, |o| String::from_utf8_lossy(&o.stdout).contains(&pid.to_string())) }
#[link(name = "kernel32")] extern "system" { fn GetDiskFreeSpaceExW(dir: *const u16, free: *mut u64, total: *mut u64, all: *mut u64) -> i32; }
#[link(name = "kernel32")] extern "system" {
fn GetDiskFreeSpaceExW(dir: *const u16, free: *mut u64, total: *mut u64, all: *mut u64) -> i32;
fn QueryUnbiasedInterruptTime(unbiased_time: *mut u64) -> i32;
}
/// Monotonic awake seconds since first call (`QueryUnbiasedInterruptTime` excludes standby/hibernation).
pub fn awake_s() -> u64 {
static T0: std::sync::OnceLock<(Option<u64>, std::time::Instant)> = std::sync::OnceLock::new();
let read = || { let mut t = 0u64; (unsafe { QueryUnbiasedInterruptTime(&mut t) } != 0).then_some(t / 10_000_000) };
let (base, fallback) = *T0.get_or_init(|| (read(), std::time::Instant::now()));
match (base, read()) { (Some(b), Some(now)) => now.saturating_sub(b), _ => fallback.elapsed().as_secs() }
}
pub fn space(p: &std::path::Path) -> Option<(u64, u64)> {
use std::os::windows::ffi::OsStrExt;
let w: Vec<u16> = p.as_os_str().encode_wide().chain(Some(0)).collect(); let (mut a, mut b, mut c) = (0u64, 0u64, 0u64);
Expand All @@ -54,7 +69,7 @@ use std::{path::Path, process::{Child, Command, ExitStatus}};
fn quiet(name: &str) -> std::process::Command { use std::os::windows::process::CommandExt; let mut c = std::process::Command::new(name); c.creation_flags(NO_WINDOW); c }
pub fn signal_of(_: &std::process::ExitStatus) -> Option<i32> { None }
}
pub use os::{abort, alive, clean_signals, detach, signal_of, space, stop_asked, term, watch_stop};
pub use os::{abort, alive, awake_s, clean_signals, detach, signal_of, space, stop_asked, term, watch_stop};
pub fn free_bytes(p: &Path) -> Option<u64> { space(p).map(|s| s.0) }

/// The hub program in a build folder.
Expand Down
4 changes: 2 additions & 2 deletions native/host/src/agents/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -632,9 +632,9 @@ async fn remake_folder(cwd: &str, root: &str) -> Result<(), String> {
let p = std::path::Path::new(cwd);
if cwd.is_empty() { return Err("the thread has no folder".into()) }
if p.is_dir() { return Ok(()) }
if !root.is_empty() && std::path::Path::new(root).join(".git").exists() {
if !crate::copy::on() && !root.is_empty() && std::path::Path::new(root).join(".git").exists() {
if let Some(parent) = p.parent() { let _ = std::fs::create_dir_all(parent); }
let run = |args: Vec<&str>| { let mut c = tokio::process::Command::new("git"); c.arg("-C").arg(root).args(args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); c.status() };
let run = |args: Vec<&str>| { let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, "git"); c.arg("-C").arg(root).args(args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); c.status() };
let _ = run(vec!["worktree", "prune"]).await;
let _ = run(vec!["worktree", "add", "--detach", cwd, "HEAD"]).await;
}
Expand Down
15 changes: 14 additions & 1 deletion native/host/src/agents/proc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,20 @@ mod reaper {
#[cfg(test)] c.args(["agents::tests::reaper_child", "--exact", "--nocapture", "--test-threads=1"]).env("BP_REAPER_CHILD", "1"); // a test binary takes no such flag: its watcher is a test that only runs as that child
c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
crate::plat::proc::own_group(&mut c);
match c.spawn() { Ok(mut ch) => { *g = ch.stdin.take(); std::thread::spawn(move || { let _ = ch.wait(); }); } Err(_) => return false }
struct Reap(Option<std::process::Child>);
impl Drop for Reap { fn drop(&mut self) { if let Some(mut c) = self.0.take() { let _ = c.kill(); let _ = c.wait(); } } }
match c.spawn() {
Ok(mut ch) => {
let stdin = ch.stdin.take();
let mut guard = Reap(Some(ch));
if std::thread::Builder::new().name("agent-reaper-wait".into()).spawn(move || { if let Some(mut c) = guard.0.take() { let _ = c.wait(); } }).is_ok() {
*g = stdin;
} else {
return false;
}
}
Err(_) => return false,
}
}
let ok = g.as_mut().map_or(false, |w| w.write_all(line.as_bytes()).and_then(|_| w.flush()).is_ok());
if !ok { *g = None }
Expand Down
2 changes: 1 addition & 1 deletion native/host/src/commands/clone/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ fn uses_lfs(dest: &Path) -> bool {
std::fs::read_to_string(dest.join(".gitattributes")).map_or(false, |t| t.contains("filter=lfs")) || dest.join(".lfsconfig").is_file()
}
async fn lfs_installed() -> bool {
let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, "git"); c.args(["lfs", "version"]).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, "git"); c.args(["lfs", "version"]).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true);
matches!(tokio::time::timeout(std::time::Duration::from_secs(10), c.status()).await, Ok(Ok(s)) if s.success())
}

Expand Down
5 changes: 2 additions & 3 deletions native/host/src/data/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,8 +849,8 @@ mod pick_tests {
}

#[test] fn browser_plan_path_is_confined_to_authorized_projects() {
let base = std::env::temp_dir().join(format!("bp-ext-plan-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let base_guard = crate::plat::tmp::dir("ext-plan");
let base = base_guard.path();
let home = base.join("home");
let proj = base.join("proj");
let outside = base.join("outside");
Expand Down Expand Up @@ -891,6 +891,5 @@ mod pick_tests {
std::os::unix::fs::symlink(&outside_plan, &sub_sidecar).unwrap();
assert!(check_browser_plan_path(&roots, &home, sub_pro.to_str().unwrap()).is_err());
}
let _ = std::fs::remove_dir_all(&base);
}
}
Loading
Loading