From 885a8862ef5d994f9ac98e73409640c745ff2aa0 Mon Sep 17 00:00:00 2001 From: Sebastian Gieseler Date: Mon, 16 Nov 2026 14:46:14 +0100 Subject: [PATCH] fix(lane): a lane started on a node checks its ports here, and the registry reads an entry again (#539) A lane started on a node forwards its ports here by its number, without the check a start here got in #535: one rule now decides for both (`number_to_start`, `free_range_for`), before the lease, and says a new number in the log (`lane_renumbered`). `registry::list` skipped an entry it could not read or parse: its stack then looked as if it claimed nothing, and another stack's lane could be numbered onto its ports. A read is tried again for up to 200 ms (on Windows the rename that replaces an entry can fail a reader for a moment); one that still fails is said in the log, once per file. A lane moved to a node, or back here, keeps its number on purpose: it holds its range here throughout, as its own instances or its forwards. Closes #539 Bug-Class: race-on-start Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++ crates/devstack-daemon/src/lanes.rs | 127 +++++++++++++++++++------ crates/devstack-daemon/src/registry.rs | 58 ++++++++++- 3 files changed, 164 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2681699..3bb164f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,14 @@ and listed with their assets on the number on those ports and its services failed later with "already in use". The start now also checks what other stacks claim, its containers' host ports included, and takes another number if its range is claimed. +- **A lane started on a node checks its ports here the same way** (#539): + it forwards them by its number, so a range another stack claims, or + another process holds, gives it another number before the lease. +- **An entry of the stacks' registry that cannot be read for a moment is + read again** (#539), instead of being skipped: skipped, its stack looked + as if it claimed nothing, and another stack's lane could be numbered onto + its ports. One that does not read within 200 ms is said in the daemon's + log. ## [0.47.0] - 2026-11-13 diff --git a/crates/devstack-daemon/src/lanes.rs b/crates/devstack-daemon/src/lanes.rs index c09ed73b..781e7bc1 100644 --- a/crates/devstack-daemon/src/lanes.rs +++ b/crates/devstack-daemon/src/lanes.rs @@ -328,6 +328,26 @@ fn range_taken( .any(|p| p.checked_add(off).is_none_or(|q| foreign.contains(&q))) } +/// The number a lane numbered `number` starts with: its own while its range +/// is free ([`range_taken`]), else the first free one ([`free_number_in`], +/// `others` the numbers of the stack's other lanes). `None`: none is free. +fn number_to_start( + number: u16, + base: &[u16], + services: &[u16], + step: u16, + others: &[u16], + foreign: &BTreeSet, + in_use: impl Fn(u16) -> bool, +) -> Option { + let taken = lane_offset(number, step) + .is_none_or(|off| range_taken(base, services, off, foreign, &in_use)); + if !taken { + return Some(number); + } + free_number_in(base, others, step, foreign, in_use) +} + /// Whom each lane is shared with, from `.devstack/lane-shares.json`. The /// separate viewers devstack 0.11 kept (`lane-views.json`, ADR-0040 before /// its amendment of 2026-10-20) could use the lane as well: they are added @@ -1561,6 +1581,43 @@ impl Lanes { ) } + /// `entry` with the number it starts with ([`number_to_start`]): its + /// range taken since it was found, by another process or by what + /// another stack claims (#535), a new one, saved. For a start here and + /// a start on a node alike: a lane on a node listens on its range here + /// too (#539). + fn free_range_for(&self, mut entry: LaneEntry) -> Result { + let stack = self.main.stack(); + let mut known = self.known.lock().unwrap(); + let others: Vec = known + .iter() + .filter(|(n, _)| **n != entry.name) + .map(|(_, k)| k.entry.number) + .collect(); + let number = number_to_start( + entry.number, + &self.lane_base(), + &ports(&stack), + stack.lanes.port_step, + &others, + &crate::registry::foreign_claims(&self.own_id()), + crate::supervisor::port_in_use, + ) + .ok_or("no free port range for another lane")?; + if number != entry.number { + crate::diag::info( + "lane_renumbered", + serde_json::json!({ "lane": entry.name, "from": entry.number, "number": number }), + ); + entry.number = number; + if let Some(k) = known.get_mut(&entry.name) { + k.entry.number = number; + } + self.save(&known); + } + Ok(entry) + } + /// This stack's id in the registry of stacks. fn own_id(&self) -> String { crate::registry::id_for(self.main.stack_file()) @@ -2390,34 +2447,7 @@ impl Lanes { } let t0 = std::time::Instant::now(); let result = (|| { - // Its range taken since it was found, by another process or by - // what another stack claims: a new one. - let step = self.main.stack().lanes.port_step; - let mut entry = entry; - let busy = lane_offset(entry.number, step).is_none_or(|off| { - range_taken( - &self.lane_base(), - &ports(&self.main.stack()), - off, - &crate::registry::foreign_claims(&self.own_id()), - crate::supervisor::port_in_use, - ) - }); - if busy { - let mut known = self.known.lock().unwrap(); - let others: BTreeMap = known - .iter() - .filter(|(n, _)| **n != name) - .map(|(n, k)| (n.clone(), k.clone())) - .collect(); - entry.number = self - .free_number(&others, true) - .ok_or("no free port range for another lane")?; - if let Some(k) = known.get_mut(&name) { - k.entry.number = entry.number; - } - self.save(&known); - } + let entry = self.free_range_for(entry)?; let lane = self.open(&entry)?; self.map.lock().unwrap().insert(name.clone(), lane.clone()); crate::diag::info( @@ -3515,6 +3545,16 @@ impl Lanes { self.workers.lock().unwrap().remove(&name); } self.begin_move(&name, "start", on, 3); + // Its ports here are forwarded by its number: not onto a range + // another stack claims or another process holds (#539). + let entry = match self.free_range_for(entry) { + Ok(e) => e, + Err(e) => { + let e = format!("lane `{name}`: {e}"); + self.start_failed(&name, on, &e); + return Err(e); + } + }; let leased = { let step = self.step_fn(&name); self.with_spec(&entry, on, &need, true, &step, |spec| { @@ -4252,6 +4292,37 @@ port = 8080 )); } + #[test] + fn a_lane_keeps_its_number_until_its_range_is_claimed_or_held() { + // #539: one rule for a start here and on a node. + let base = [1430, 4400, 4401]; + let services = [4400, 4401]; + let free = |_| false; + let none = BTreeSet::new(); + // Its range is free: it keeps its number, even beside other lanes. + assert_eq!( + number_to_start(2, &base, &services, 100, &[1, 3], &none, free), + Some(2) + ); + // Another stack claims lane 2's 4600: the first free one, past the + // stack's own lanes 1 and 3. + let foreign = BTreeSet::from([4600]); + assert_eq!( + number_to_start(2, &base, &services, 100, &[1, 3], &foreign, free), + Some(4) + ); + // Another process holds lane 2's 4601: the same. + assert_eq!( + number_to_start(2, &base, &services, 100, &[1, 3], &none, |p| p == 4601), + Some(4) + ); + // Nothing is free below 65536. + assert_eq!( + number_to_start(1, &[65000], &[65000], 1000, &[], &none, |_| true), + None + ); + } + #[test] fn lane_offsets_never_wrap() { assert_eq!(lane_offset(3, 100), Some(300)); diff --git a/crates/devstack-daemon/src/registry.rs b/crates/devstack-daemon/src/registry.rs index 755aa7b1..81eec94c 100644 --- a/crates/devstack-daemon/src/registry.rs +++ b/crates/devstack-daemon/src/registry.rs @@ -194,13 +194,42 @@ pub fn list() -> Vec { list_in(&dir()) } +/// The entry in the file `path`; `None` once it is gone. A read that meets +/// the file while its daemon replaces it (on Windows the rename over it can +/// fail a reader for a moment) is tried again for up to 200 ms: an entry +/// skipped would read as a stack that claims nothing, and another stack's +/// lane could be numbered onto its ports (#535, #539). One that still does +/// not read is said in the log, once per file. +fn read_entry(path: &Path) -> Option { + static SAID: std::sync::Mutex> = std::sync::Mutex::new(BTreeSet::new()); + let mut error = String::new(); + for _ in 0..10 { + match std::fs::read(path) { + Ok(bytes) => match serde_json::from_slice(&bytes) { + Ok(e) => return Some(e), + Err(e) => error = e.to_string(), + }, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, + Err(e) => error = e.to_string(), + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + if SAID.lock().unwrap().insert(path.to_path_buf()) { + crate::diag::warn( + "registry_entry_unreadable", + serde_json::json!({ "file": path, "error": error }), + ); + } + None +} + fn list_in(d: &Path) -> Vec { let mut out: Vec = std::fs::read_dir(d) .into_iter() .flatten() .flatten() .filter(|e| e.path().extension().is_some_and(|x| x == "json")) - .filter_map(|e| serde_json::from_slice(&std::fs::read(e.path()).ok()?).ok()) + .filter_map(|e| read_entry(&e.path())) .collect(); out.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.cmp(&b.id))); out @@ -337,4 +366,31 @@ mod tests { assert_eq!((e.name.as_str(), e.shift), ("shop", 2000)); assert!(change(d.path(), "../x", |_| {}).is_err()); } + + /// #539: an entry met while its daemon replaces it is read again, not + /// taken for a stack that claims nothing (its lanes' ports then looked + /// free to another stack's numbering). + #[test] + fn an_entry_met_while_it_is_replaced_is_read_again() { + let d = tempfile::tempdir().unwrap(); + let path = path_of(d.path(), "abc"); + // Half of it now (what a reader sees of a file not yet complete, or + // not at all while it is renamed over), all of it a moment later. + std::fs::write(&path, "{\"id\":\"abc\",").unwrap(); + let mut whole = entry("abc"); + whole.claims.main = vec![4600]; + let full = serde_json::to_vec(&whole).unwrap(); + let later = path.clone(); + let writer = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(30)); + std::fs::write(later, full).unwrap(); + }); + let read = read_entry(&path); + writer.join().unwrap(); + assert_eq!(read.map(|e| e.claims.main), Some(vec![4600])); + // Gone is gone at once; what never parses is given up. + assert!(read_entry(&path_of(d.path(), "nope")).is_none()); + std::fs::write(&path, "not json").unwrap(); + assert!(read_entry(&path).is_none()); + } }