From e5d095ad8b7d387463bbb318cdeb86ddfb7cdc3b Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Wed, 18 Nov 2026 14:30:09 +0100 Subject: [PATCH] fix(pool): leases of cut-off starts stay noted until let go; a start waiting for its slot is not gone Review of #565 and #563 before 0.49.4: - The node ended a lease as `gone` while its start waited (up to 120 s) for the lane's last lease to take its containers down: its stack file was set, its container not there yet and it not yet in `starting`. A lease whose slot is busy is no longer judged. - `leasing.json` holds a list: a new start no longer writes over the note of a lease whose release did not get through (its node did not answer). - A start that failed keeps its lease's note when the release did not get through (only a release or a 404 drops it), so the next daemon or start tries again. - A daemon releases only the leases noted when it started, read before its API serves, not the note of a start begun through it since. Bug-Class: stale-state Co-Authored-By: Claude Opus 5.5 --- crates/devstack-daemon/src/lanes.rs | 38 +++-- crates/devstack-daemon/src/lib.rs | 4 +- crates/devstack-daemon/src/remote.rs | 202 ++++++++++++++++++++++----- crates/devstack-node/src/node.rs | 47 +++++-- 4 files changed, 239 insertions(+), 52 deletions(-) diff --git a/crates/devstack-daemon/src/lanes.rs b/crates/devstack-daemon/src/lanes.rs index 0069681f..6d6f0ae4 100644 --- a/crates/devstack-daemon/src/lanes.rs +++ b/crates/devstack-daemon/src/lanes.rs @@ -3139,7 +3139,9 @@ impl Lanes { /// lanes on nodes it followed when it ended without stopping them /// ([`Self::unfollowed`]); then the lanes here and the main slot. /// Blocking: on a thread of its own. - pub fn take_up(self: &Arc) { + /// `left`: the starts on nodes cut off by a daemon before this one + /// ([`Self::unlaunched_left`]). + pub fn take_up(self: &Arc, left: Vec<(String, Vec)>) { let (lanes, main) = self .carried() .map(|c| (c.lanes, c.main)) @@ -3150,7 +3152,7 @@ impl Lanes { self.take_up_remote(l); } self.unfollowed(); - self.unlaunched(); + self.unlaunched(left); for l in local { self.take_up_local(l); } @@ -3194,12 +3196,15 @@ impl Lanes { /// (#563): their leases were admitted there, the lanes never followed. /// Released, as a start that fails releases its lease, and said with the /// lane; the node would otherwise keep the lease for its grace and - /// refuse the lane's next start as running there already. - fn unlaunched(&self) { - let names: Vec = self.known.lock().unwrap().keys().cloned().collect(); - for name in names { - if let Some(Ok(u)) = - crate::remote::release_unlaunched(&self.rt, &name, &self.state_dir(&name)) + /// refuse the lane's next start as running there already. Only the + /// leases noted when this daemon started: by the time the lanes it + /// carried are taken up, a start begun here may have noted its own. + fn unlaunched(&self, left: Vec<(String, Vec)>) { + for (name, leases) in left { + let state = self.state_dir(&name); + for u in crate::remote::release_unlaunched(&self.rt, &name, &state, Some(&leases)) + .into_iter() + .flatten() { self.not_carried( &name, @@ -3211,6 +3216,23 @@ impl Lanes { } } + /// The leases of starts on nodes a daemon before this one left noted + /// (#563), by lane: read when this daemon starts, before any start of + /// its own. + pub fn unlaunched_left(&self) -> Vec<(String, Vec)> { + let names: Vec = self.known.lock().unwrap().keys().cloned().collect(); + names + .into_iter() + .filter_map(|name| { + let leases: Vec = crate::remote::unlaunched(&self.state_dir(&name)) + .into_iter() + .map(|u| u.lease) + .collect(); + (!leases.is_empty()).then_some((name, leases)) + }) + .collect() + } + /// What a daemon before this one left running for a restart (ADR-0052 /// point 2), if it is for this stack and recent. The word is read once. fn carried(&self) -> Option { diff --git a/crates/devstack-daemon/src/lib.rs b/crates/devstack-daemon/src/lib.rs index 70a71d45..1e4997dd 100644 --- a/crates/devstack-daemon/src/lib.rs +++ b/crates/devstack-daemon/src/lib.rs @@ -468,9 +468,11 @@ pub fn serve(stack_file: &Path) -> Result<(), String> { // (ADR-0052), taken up beside the main tree's start. { let lanes = lanes.clone(); + // Read here, before a start through the API can note its own. + let left = lanes.unlaunched_left(); let _ = std::thread::Builder::new() .name("lanes-take-up".into()) - .spawn(move || lanes.take_up()); + .spawn(move || lanes.take_up(left)); } let (stopping_tx, stopping_rx) = tokio::sync::oneshot::channel::<()>(); let stopping_info = (info_path(&state_dir), info.clone()); diff --git a/crates/devstack-daemon/src/remote.rs b/crates/devstack-daemon/src/remote.rs index 9c039e63..285fd242 100644 --- a/crates/devstack-daemon/src/remote.rs +++ b/crates/devstack-daemon/src/remote.rs @@ -157,58 +157,110 @@ pub struct Unlaunched { pub lease: String, } -fn unlaunched(state: &Path) -> Option { - std::fs::read(state.join(LEASING)) - .ok() - .and_then(|b| serde_json::from_slice(&b).ok()) +/// The notes in `state`, oldest first. The first builds with the note +/// wrote one, not a list. +pub fn unlaunched(state: &Path) -> Vec { + let Ok(b) = std::fs::read(state.join(LEASING)) else { + return Vec::new(); + }; + serde_json::from_slice::>(&b) + .or_else(|_| serde_json::from_slice::(&b).map(|u| vec![u])) + .unwrap_or_default() } -fn note_unlaunched(state: &Path, u: &Unlaunched) { +fn write_unlaunched(state: &Path, all: &[Unlaunched]) { + if all.is_empty() { + let _ = std::fs::remove_file(state.join(LEASING)); + return; + } let _ = std::fs::create_dir_all(state); let tmp = state.join(format!("{LEASING}.tmp")); - let _ = serde_json::to_vec_pretty(u) + let _ = serde_json::to_vec_pretty(all) .map_err(std::io::Error::other) .and_then(|b| std::fs::write(&tmp, b)) .and_then(|()| std::fs::rename(&tmp, state.join(LEASING))); } +/// The notes are read, changed and written by the start of a lane and by +/// the release of what an earlier daemon left, on different threads. +static LEASING_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn note_unlaunched(state: &Path, u: &Unlaunched) { + let _held = LEASING_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + // Beside the notes of leases not released yet (their node did not + // answer), never over them. + let mut all = unlaunched(state); + all.retain(|x| x.lease != u.lease); + all.push(u.clone()); + write_unlaunched(state, &all); +} + /// Remove the note of lease `lease` in `state`; a note of another lease /// stays. fn forget_unlaunched(state: &Path, lease: &str) { - if unlaunched(state).is_some_and(|u| u.lease == lease) { - let _ = std::fs::remove_file(state.join(LEASING)); + let _held = LEASING_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let mut all = unlaunched(state); + let before = all.len(); + all.retain(|u| u.lease != lease); + if all.len() != before { + write_unlaunched(state, &all); + } +} + +/// The end of a start that failed: its lease's note goes once the node +/// let the lease go (released, or over already: 404). A release that did +/// not get through keeps it, for the next daemon or start to try again. +fn released_unlaunched( + state: &Path, + lease: &str, + released: &Result<(), devstack_node::nodeclient::ClientError>, +) { + if matches!( + released, + Ok(()) | Err(devstack_node::nodeclient::ClientError::Status(404, _)) + ) { + forget_unlaunched(state, lease); } } -/// Release the lease a start of the lane `name`, whose state is `state`, -/// left admitted on its node, when a daemon ended before the start was over -/// (#563); said in the log. `None`: there is none (or the lane is followed -/// on it); else the lease, or why it could not be released (the note stays -/// for the next try). Blocking. +/// Release the leases starts of the lane `name`, whose state is `state`, +/// left admitted on their nodes, when a daemon ended before a start was +/// over (#563); said in the log. `only`: just these leases (those noted +/// when this daemon started, not a start of its own begun since), else +/// all. Each released lease, or why it could not be (its note stays for +/// the next try); none when nothing is noted (or the lane is followed on +/// it). Blocking. pub fn release_unlaunched( rt: &tokio::runtime::Handle, name: &str, state: &Path, -) -> Option> { - let r = release_unlaunched_quietly(rt, state)?; - match &r { - Ok(u) => crate::diag::info( - "remote_lane_start_released", - serde_json::json!({ "lane": name, "node": u.node.name, "lease": u.lease }), - ), - Err(e) => crate::diag::warn( - "remote_lane_start_not_released", - serde_json::json!({ "lane": name, "error": e }), - ), - } - Some(r) + only: Option<&[String]>, +) -> Vec> { + let out: Vec> = unlaunched(state) + .into_iter() + .filter(|u| only.is_none_or(|o| o.contains(&u.lease))) + .filter_map(|u| release_one(rt, state, u)) + .collect(); + for r in &out { + match r { + Ok(u) => crate::diag::info( + "remote_lane_start_released", + serde_json::json!({ "lane": name, "node": u.node.name, "lease": u.lease }), + ), + Err(e) => crate::diag::warn( + "remote_lane_start_not_released", + serde_json::json!({ "lane": name, "error": e }), + ), + } + } + out } -fn release_unlaunched_quietly( +fn release_one( rt: &tokio::runtime::Handle, state: &Path, + u: Unlaunched, ) -> Option> { - let u = unlaunched(state)?; // Followed after all: it ended between the two notes. if followed(state).is_some_and(|c| c.lease == u.lease) { forget_unlaunched(state, &u.lease); @@ -731,7 +783,7 @@ impl RemoteLane { // already. A warm lease is no lane's. let state = spec.scratch.parent().filter(|_| !spec.warm); if let Some(state) = state { - release_unlaunched(rt, spec.name, state); + release_unlaunched(rt, spec.name, state, None); } let request = LeaseRequest { node, @@ -1117,9 +1169,9 @@ impl RemoteLane { let started = match started { Ok(st) => st, Err(e) => { - let _ = rt.block_on(client.release(&offer.id)); + let released = rt.block_on(client.release(&offer.id)); if let Some(state) = state { - forget_unlaunched(state, &offer.id); + released_unlaunched(state, &offer.id, &released); } return Err(format!("lane `{name}` on {}: {e}", offer.node.name)); } @@ -2412,7 +2464,7 @@ mod tests { devstack: None, }; let rt = tokio::runtime::Runtime::new().unwrap(); - assert!(super::release_unlaunched(rt.handle(), "wt", state.path()).is_none()); + assert!(super::release_unlaunched(rt.handle(), "wt", state.path(), None).is_empty()); super::note_unlaunched( state.path(), &super::Unlaunched { @@ -2423,7 +2475,7 @@ mod tests { ); // Another lease's end leaves the note. super::forget_unlaunched(state.path(), "l0"); - assert_eq!(super::unlaunched(state.path()).expect("noted").lease, "l1"); + assert_eq!(super::unlaunched(state.path())[0].lease, "l1"); // The lane was followed on it before the daemon ended: nothing to // release, and the note goes. let carried = super::Carried { @@ -2439,8 +2491,8 @@ mod tests { serde_json::to_vec(&carried).unwrap(), ) .unwrap(); - assert!(super::release_unlaunched(rt.handle(), "wt", state.path()).is_none()); - assert!(super::unlaunched(state.path()).is_none()); + assert!(super::release_unlaunched(rt.handle(), "wt", state.path(), None).is_empty()); + assert!(super::unlaunched(state.path()).is_empty()); // Started and followed: the note went with the start. super::note_unlaunched( state.path(), @@ -2454,6 +2506,86 @@ mod tests { assert!(!state.path().join(super::LEASING).exists()); } + fn unlaunched_on(node: &str, lease: &str) -> super::Unlaunched { + super::Unlaunched { + // A pool this machine is no member of: a release cannot get + // through. + pool: "no-such-pool".into(), + node: NodeRef { + id: node.into(), + name: node.into(), + api: "https://127.0.0.1:1".into(), + devstack: None, + }, + lease: lease.into(), + } + } + + #[test] + fn a_lease_whose_release_failed_stays_noted_beside_a_new_one() { + let state = tempfile::tempdir().unwrap(); + let rt = tokio::runtime::Runtime::new().unwrap(); + super::note_unlaunched(state.path(), &unlaunched_on("a", "l1")); + // Its node does not answer: the note stays for the next try. + let r = super::release_unlaunched(rt.handle(), "wt", state.path(), None); + assert!(matches!(r.as_slice(), [Err(_)]), "{r:?}"); + // The lane starts on another node meanwhile: both are noted. + super::note_unlaunched(state.path(), &unlaunched_on("b", "l2")); + let leases: Vec = super::unlaunched(state.path()) + .into_iter() + .map(|u| u.lease) + .collect(); + assert_eq!(leases, ["l1", "l2"]); + // The new one followed: the old one is still noted. + super::forget_unlaunched(state.path(), "l2"); + assert_eq!(super::unlaunched(state.path())[0].lease, "l1"); + } + + #[test] + fn a_failed_start_keeps_its_note_until_its_lease_is_let_go() { + use devstack_node::nodeclient::ClientError; + let state = tempfile::tempdir().unwrap(); + super::note_unlaunched(state.path(), &unlaunched_on("a", "l1")); + // The release did not get through: noted still. + super::released_unlaunched(state.path(), "l1", &Err(ClientError::Other("down".into()))); + assert_eq!(super::unlaunched(state.path()).len(), 1); + // Over on the node already: the note goes. + super::released_unlaunched( + state.path(), + "l1", + &Err(ClientError::Status(404, "no lease".into())), + ); + assert!(super::unlaunched(state.path()).is_empty()); + super::note_unlaunched(state.path(), &unlaunched_on("a", "l2")); + super::released_unlaunched(state.path(), "l2", &Ok(())); + assert!(super::unlaunched(state.path()).is_empty()); + } + + #[test] + fn the_leases_left_by_an_earlier_daemon_are_the_only_ones_released() { + let state = tempfile::tempdir().unwrap(); + let rt = tokio::runtime::Runtime::new().unwrap(); + super::note_unlaunched(state.path(), &unlaunched_on("a", "left")); + // A start through this daemon's API noted its own meanwhile. + super::note_unlaunched(state.path(), &unlaunched_on("a", "mine")); + let r = + super::release_unlaunched(rt.handle(), "wt", state.path(), Some(&["left".to_string()])); + // Only the one left was tried (its node does not answer here). + assert_eq!(r.len(), 1, "{r:?}"); + assert!(r[0].as_ref().unwrap_err().contains("left"), "{r:?}"); + } + + #[test] + fn a_note_of_an_earlier_release_is_read_as_one() { + let state = tempfile::tempdir().unwrap(); + std::fs::write( + state.path().join(super::LEASING), + serde_json::to_vec(&unlaunched_on("a", "old")).unwrap(), + ) + .unwrap(); + assert_eq!(super::unlaunched(state.path())[0].lease, "old"); + } + #[test] fn a_peer_hanging_up_is_how_a_tunnel_ends() { use std::io::{Error, ErrorKind}; diff --git a/crates/devstack-node/src/node.rs b/crates/devstack-node/src/node.rs index 3f702076..86a0744c 100644 --- a/crates/devstack-node/src/node.rs +++ b/crates/devstack-node/src/node.rs @@ -3616,16 +3616,24 @@ fn running_lanes() -> Option> { /// (`starting` has it), nor one not started yet. Seen so in this round /// and the one before (`missed`, carried from round to round): a lane that /// starts between the look at its container and the look at `starting` -/// is not taken for gone. +/// is not taken for gone. Nor one whose slot is busy (`busy`): its start +/// waits there, before it is in `starting`, for the lane's last lease to +/// take its containers down. fn gone_leases( leases: &HashMap, running: &HashSet, starting: &HashSet, + busy: &HashSet, missed: &mut HashSet, ) -> Vec { let now: HashSet = leases .values() - .filter(|l| l.stack_file.is_some() && !starting.contains(&l.id) && !running.contains(&l.id)) + .filter(|l| { + l.stack_file.is_some() + && !starting.contains(&l.id) + && !running.contains(&l.id) + && !l.slot.as_ref().is_some_and(|s| busy.contains(s)) + }) .map(|l| l.id.clone()) .collect(); let mut gone: Vec = now.intersection(missed).cloned().collect(); @@ -3872,9 +3880,10 @@ async fn background(s: Shared) { // their grace. Nothing ends while Docker does not answer. if let Ok(Some(running)) = tokio::task::spawn_blocking(running_lanes).await { let starting: HashSet = s.starting.lock().unwrap().keys().cloned().collect(); + let busy: HashSet = s.slot_busy.lock().unwrap().keys().cloned().collect(); let gone: Vec = { let mut leases = s.leases.lock().unwrap(); - let ids = gone_leases(&leases, &running, &starting, &mut missed); + let ids = gone_leases(&leases, &running, &starting, &busy, &mut missed); let out: Vec = ids.iter().filter_map(|id| leases.remove(id)).collect(); if !out.is_empty() { s.save(&leases); @@ -4393,19 +4402,41 @@ mod tests { let running: HashSet = ["runs".to_string()].into(); // A start under way, and one that failed: both in `starting`. let starting: HashSet = ["starting".to_string(), "failed".to_string()].into(); + let none = HashSet::new(); let mut missed = HashSet::new(); // The first round only notes it. - assert!(gone_leases(&leases, &running, &starting, &mut missed).is_empty()); + assert!(gone_leases(&leases, &running, &starting, &none, &mut missed).is_empty()); assert_eq!( - gone_leases(&leases, &running, &starting, &mut missed), + gone_leases(&leases, &running, &starting, &none, &mut missed), ["gone".to_string()] ); // Its container came back between two rounds: it stays. let mut missed = HashSet::new(); - gone_leases(&leases, &running, &starting, &mut missed); + gone_leases(&leases, &running, &starting, &none, &mut missed); let back: HashSet = ["runs".to_string(), "gone".to_string()].into(); - assert!(gone_leases(&leases, &back, &starting, &mut missed).is_empty()); - assert!(gone_leases(&leases, &running, &starting, &mut missed).is_empty()); + assert!(gone_leases(&leases, &back, &starting, &none, &mut missed).is_empty()); + assert!(gone_leases(&leases, &running, &starting, &none, &mut missed).is_empty()); + } + + #[test] + fn a_start_waiting_for_its_slot_is_not_gone() { + // Started (its stack file is set), waiting for the lane's last + // lease to take its containers down: no container, not starting yet. + let leases: HashMap = + [("waits".to_string(), lease("waits", true))].into(); + let busy: HashSet = ["waits".to_string()].into(); + let (running, starting) = (HashSet::new(), HashSet::new()); + let mut missed = HashSet::new(); + for _ in 0..3 { + assert!(gone_leases(&leases, &running, &starting, &busy, &mut missed).is_empty()); + } + // Its slot free again and still no container after two rounds: gone. + let none = HashSet::new(); + gone_leases(&leases, &running, &starting, &none, &mut missed); + assert_eq!( + gone_leases(&leases, &running, &starting, &none, &mut missed), + ["waits".to_string()] + ); } #[test]