fix(daemon): address review findings

Idle paused loop no longer spins, local snapshots continue during network
backoff, debounce has a maximum wait, sync accepts non-canonical paths, removed
repos are dropped, socket dir mode is enforced. adopt_if_identical now skips
worktrees with staged changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 13:05:38 +01:00
1 parent 3f5ef28503
commit 0e77dd26d9
6 files changed
+182 -18

No files matched your search

+44 -9
View File
@@ -233,6 +233,7 @@ impl Watch {
fn rescan(root: &Path, watch: &mut Watch, ctx: &Ctx) -> Vec<PathBuf> {
let found = discover(root);
let mut shared = ctx.shared.lock().unwrap();
shared.repos.retain(|p, _| found.contains(p));
for r in &found {
shared.repos.entry(r.clone()).or_default();
}
@@ -254,6 +255,10 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
let mut backoff_until: HashMap<PathBuf, Instant> = HashMap::new();
// first_at: first unsynced event of a repo, so a constant stream of events cannot postpone
// its snapshot beyond `max_wait`.
let mut first_at: HashMap<PathBuf, Instant> = HashMap::new();
let max_wait = (debounce * 10).max(Duration::from_secs(5));
let mut next_full = Instant::now();
loop {
@@ -264,12 +269,20 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
.chain([next_full])
.min()
.unwrap_or(next_full);
let timeout = wake
let mut timeout = wake
.saturating_duration_since(now)
.min(Duration::from_secs(1));
if ctx.shared.lock().unwrap().paused {
// Nothing is due while paused: only wait for commands, never spin on past deadlines.
timeout = Duration::from_secs(1);
}
match rx.recv_timeout(timeout) {
Ok(Msg::Changed(r)) => {
let at = Instant::now() + debounce;
let now = Instant::now();
let first = *first_at.entry(r.clone()).or_insert(now);
let at = (now + debounce).min(first + max_wait);
// An earlier deadline (e.g. an immediate `sync`) is never pushed back.
let at = due_at.get(&r).map_or(at, |old| at.min(*old));
due_at.insert(r.clone(), at);
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(&r)
&& s.phase == "idle"
@@ -293,7 +306,9 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
}
let now = Instant::now();
if now >= next_full {
for r in rescan(&root, &mut watch, &ctx) {
let found = rescan(&root, &mut watch, &ctx);
due_at.retain(|r, _| found.contains(r));
for r in found {
due_at.insert(r, now);
}
next_full = now + fetch_every;
@@ -305,12 +320,19 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
.collect();
due.sort();
for r in due {
if let Some(until) = backoff_until.get(&r).filter(|u| **u > now) {
due_at.insert(r, *until);
if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
due_at.remove(&r);
continue;
}
due_at.remove(&r);
let failures = pass(&r, &cfg, &st, materialize, &ctx);
first_at.remove(&r);
// While backing off after a failure, still snapshot local work (no network needed);
// the network is retried at the first pass after the backoff expires.
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
let failures = pass(&r, &cfg, &st, materialize, offline, &ctx);
if offline {
continue;
}
if failures == 0 {
backoff_until.remove(&r);
} else {
@@ -327,14 +349,21 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
}
/// One sync pass for `repo`; returns the number of consecutive failures (0 = success).
fn pass(repo: &Path, cfg: &Config, st: &Settings, materialize: bool, ctx: &Ctx) -> u32 {
fn pass(
repo: &Path,
cfg: &Config,
st: &Settings,
materialize: bool,
offline: bool,
ctx: &Ctx,
) -> u32 {
let name = repo.display().to_string();
set_phase(ctx, repo, "syncing");
let opts = Options {
machine: cfg.machine.name.clone(),
stamp: stamp(),
remote: st.remote.clone(),
offline: false,
offline,
materialize,
};
let result = sync_repo(repo, &opts);
@@ -394,7 +423,13 @@ fn pass(repo: &Path, cfg: &Config, st: &Settings, materialize: bool, ctx: &Ctx)
}
}
}
if errors.is_empty() {
if offline {
// A snapshot-only pass during backoff changes neither the failure count nor the phase.
status.phase = if status.failures > 0 { "error" } else { "idle" };
if !errors.is_empty() {
ctx.activity.log("error", Some(&name), errors.join("; "));
}
} else if errors.is_empty() {
status.phase = "idle";
status.failures = 0;
status.last_error = None;
+17 -5
View File
@@ -49,6 +49,8 @@ pub fn serve(socket: &Path, ctx: Ctx, stop: Arc<AtomicBool>) -> std::io::Result<
.recursive(true)
.mode(0o700)
.create(dir)?;
// The mode above only applies to a directory we create: enforce it on an existing one.
std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?;
}
if socket.exists() {
if UnixStream::connect(socket).is_ok() {
@@ -187,11 +189,21 @@ fn handle(req: &Request, ctx: &Ctx) -> Value {
}
"sync" => {
let target = req.repo.as_ref().map(PathBuf::from);
if let Some(t) = &target
&& !ctx.shared.lock().unwrap().repos.contains_key(t)
{
return err("unknown repo");
}
// Match by canonical path so `.`, relative and symlinked paths work.
let target = match target {
None => None,
Some(t) => {
let want = std::fs::canonicalize(&t).unwrap_or(t);
let shared = ctx.shared.lock().unwrap();
let found = shared.repos.keys().find(|k| {
std::fs::canonicalize(k).unwrap_or_else(|_| (*k).clone()) == want
});
match found {
Some(k) => Some(k.clone()),
None => return err("unknown repo"),
}
}
};
let _ = ctx.tx.send(Msg::SyncNow(target));
ok(json!("queued"))
}
+62
View File
@@ -307,3 +307,65 @@ fn work_in_progress_then_committed_on_a_leaves_b_clean() {
a.shutdown();
b.shutdown();
}
fn cpu_ticks(pid: u32) -> u64 {
let stat = fs::read_to_string(format!("/proc/{pid}/stat")).unwrap();
let rest = stat.rsplit_once(')').unwrap().1;
let f: Vec<&str> = rest.split_whitespace().collect();
f[11].parse::<u64>().unwrap() + f[12].parse::<u64>().unwrap() // utime + stime
}
#[test]
fn paused_daemon_does_not_spin() {
let w = world("spin", &["pca"]);
let cfg_path = w.base.join("config.toml");
fs::write(
&cfg_path,
format!(
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n",
w.base.join("pca").display()
),
)
.unwrap();
let runtime = w.base.join("run");
fs::create_dir_all(&runtime).unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_groved"))
.arg("--config")
.arg(&cfg_path)
.env("XDG_RUNTIME_DIR", &runtime)
.env("XDG_STATE_HOME", w.base.join("state"))
.spawn()
.unwrap();
let sock = runtime.join("grove/grove.sock");
wait_until("daemon up", 10, || {
ipc::request(&sock, &json!({"v":1,"cmd":"ping"})).is_ok()
});
ipc::request(&sock, &json!({"v":1,"cmd":"pause"})).unwrap();
std::thread::sleep(Duration::from_millis(1500)); // let any in-flight pass finish
let before = cpu_ticks(child.id());
std::thread::sleep(Duration::from_secs(3)); // well past several fetch intervals
let used = cpu_ticks(child.id()) - before;
child.kill().unwrap();
child.wait().unwrap();
assert!(used < 30, "paused daemon burned {used} ticks of CPU in 3 s");
}
#[test]
fn sync_accepts_a_non_canonical_repo_path_and_unknown_repos_are_rejected() {
let w = world("path", &["pca"]);
let st = settings(&w, "pca");
let sock = st.socket.clone();
let d = Daemon::start(config(&w, "pca", 200, 60), st).unwrap();
let repo = w.base.join("pca/repo");
wait_until("repo listed", 10, || {
ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap()["data"]["repos"]
.as_array()
.is_some_and(|r| r.len() == 1)
});
let odd = format!("{}/../repo/.", repo.display());
let ok = ipc::request(&sock, &json!({"v":1,"cmd":"sync","repo":odd})).unwrap();
assert_eq!(ok["ok"], true, "{ok}");
let bad = ipc::request(&sock, &json!({"v":1,"cmd":"sync","repo":"/nonexistent"})).unwrap();
assert_eq!(bad["ok"], false);
d.shutdown();
}