Skip to main content

weirdnet_backends/
fence.rs

1//! Fencing for placement leases on the model node (since 0.4.11).
2//!
3//! A scheduler that holds a lease (a `weirdnet_sync::Leases` lease, for example an inference
4//! node's placement lease) attaches the lease name and its term, a [`Fence`], to node/1 `Load`
5//! and `Unload` (`Command::LoadFenced` and `Command::UnloadFenced` with the `node` feature). The
6//! model node keeps a [`FenceGuard`]: for each lease name, the highest term it has seen. A command
7//! with an older term is refused ([`FenceRefusal::Stale`]) and changes nothing, so a holder that
8//! lost the lease cannot load or unload models once a newer holder has reached the node.
9//!
10//! The rule is `weirdnet_sync::FenceGuard`'s: one counter per lease name, a term equal to the
11//! highest seen passes, an older one is stale. The persisted bytes are the same too:
12//! [`FenceGuard::export`] and `weirdnet_sync::FenceGuard::export` read each other's output. This
13//! crate keeps its own copy so it does not require a newer `weirdnet-sync` than its callers use.
14
15use std::collections::HashMap;
16use std::io::Write;
17use std::path::Path;
18
19use serde::{Deserialize, Serialize};
20use weirdnet_agent::remote::{RemoteError, from_cbor, to_cbor};
21
22const MAX_NAME: usize = 200;
23/// Message prefix of a stale-term refusal ([`FenceRefusal::Stale`]).
24const STALE: &str = "stale fence: ";
25/// Message prefix of a refused unfenced command ([`FenceRefusal::Required`]).
26const REQUIRED: &str = "fence required: ";
27
28/// A lease name and term, attached to a command by the lease holder.
29#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[non_exhaustive]
31pub struct Fence {
32    /// The lease name, as `weirdnet_sync::LeaseName`: 1 to 200 of `A-Z a-z 0-9 . - _ : / + #`.
33    pub lease: String,
34    /// The holder's term (`weirdnet_sync::Term`): strictly increases per lease name across
35    /// holders.
36    pub term: u64,
37}
38
39impl Fence {
40    /// `lease` and `term` from the holder's lease handle (`handle.name().as_str()` and
41    /// `handle.term().0` with `weirdnet-sync`).
42    pub fn new(lease: impl Into<String>, term: u64) -> Self {
43        Self { lease: lease.into(), term }
44    }
45
46    /// Whether the lease name is one `weirdnet_sync::LeaseName` accepts.
47    pub fn is_valid(&self) -> bool {
48        valid_lease_name(&self.lease)
49    }
50}
51
52impl std::fmt::Display for Fence {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        write!(f, "{} term {}", self.lease, self.term)
55    }
56}
57
58/// Whether `name` is a lease name `weirdnet_sync::LeaseName` accepts: 1 to 200 of
59/// `A-Z a-z 0-9 . - _ : / + #`.
60pub fn valid_lease_name(name: &str) -> bool {
61    !name.is_empty() && name.len() <= MAX_NAME && name.chars().all(|c| c.is_ascii_alphanumeric() || ".-_:/+#".contains(c))
62}
63
64/// The resource side of fencing: refuses a command that carries an older term than one already
65/// seen for its lease name. Persist it ([`save`](Self::save) or [`export`](Self::export)) so a
66/// restart keeps refusing.
67#[derive(Debug, Clone, Default, PartialEq, Eq)]
68pub struct FenceGuard {
69    seen: HashMap<String, u64>,
70}
71
72/// A command from an older term than the guard has seen.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct Stale {
75    /// The highest term seen for the lease name.
76    pub seen: u64,
77}
78
79impl std::fmt::Display for Stale {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        write!(f, "stale term: {} already seen", self.seen)
82    }
83}
84
85impl std::error::Error for Stale {}
86
87impl FenceGuard {
88    pub fn new() -> Self {
89        Self::default()
90    }
91
92    /// Accepts `term` if it is at least the highest seen for `lease`, and records it.
93    pub fn check(&mut self, lease: &str, term: u64) -> Result<(), Stale> {
94        let seen = self.seen.entry(lease.to_string()).or_default();
95        if term < *seen {
96            return Err(Stale { seen: *seen });
97        }
98        *seen = term;
99        Ok(())
100    }
101
102    /// The highest term seen for `lease`.
103    pub fn seen(&self, lease: &str) -> Option<u64> {
104        self.seen.get(lease).copied()
105    }
106
107    /// Every lease name seen, with its highest term, sorted by name.
108    pub fn leases(&self) -> Vec<(String, u64)> {
109        let mut v: Vec<_> = self.seen.iter().map(|(n, t)| (n.clone(), *t)).collect();
110        v.sort();
111        v
112    }
113
114    /// CBOR, the same bytes as `weirdnet_sync::FenceGuard::export`.
115    pub fn export(&self) -> Vec<u8> {
116        to_cbor(&self.leases()).unwrap_or_default()
117    }
118
119    /// Reads [`export`](Self::export)'s or `weirdnet_sync::FenceGuard::export`'s bytes. Bad lease
120    /// names are refused.
121    pub fn import(bytes: &[u8]) -> Result<Self, RemoteError> {
122        let v: Vec<(String, u64)> = from_cbor(bytes)?;
123        if let Some((bad, _)) = v.iter().find(|(n, _)| !valid_lease_name(n)) {
124            return Err(RemoteError::protocol(format!("fence guard: bad lease name {bad:?}")));
125        }
126        Ok(Self { seen: v.into_iter().collect() })
127    }
128
129    /// The guard saved at `path`, or an empty one when there is no file yet.
130    pub fn load(path: impl AsRef<Path>) -> std::io::Result<Self> {
131        match std::fs::read(path.as_ref()) {
132            Ok(bytes) => Self::import(&bytes).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())),
133            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::new()),
134            Err(e) => Err(e),
135        }
136    }
137
138    /// Saves to `path`: written to a temporary file next to it, synced, then renamed over it.
139    pub fn save(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
140        let path = path.as_ref();
141        if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
142            std::fs::create_dir_all(dir)?;
143        }
144        let mut tmp = path.as_os_str().to_owned();
145        tmp.push(".tmp");
146        let tmp = std::path::PathBuf::from(tmp);
147        {
148            let mut f = std::fs::File::create(&tmp)?;
149            f.write_all(&self.export())?;
150            f.sync_all()?;
151        }
152        std::fs::rename(&tmp, path)
153    }
154}
155
156/// Why a model node refused a command for fencing. It travels as a [`RemoteError::Refused`]
157/// with a fixed message; [`from_error`](Self::from_error) reads it back, so a caller can tell a
158/// fencing refusal (stop: another holder has the lease, or the node wants a fence) from a
159/// transient failure (retry).
160#[derive(Debug, Clone, PartialEq, Eq)]
161#[non_exhaustive]
162pub enum FenceRefusal {
163    /// The node has seen a newer term for the lease; the command changed nothing.
164    Stale { lease: String, term: u64, seen: u64 },
165    /// The node takes `Load` and `Unload` only with a fence, and the command had none.
166    Required,
167}
168
169impl FenceRefusal {
170    /// The error sent to the caller: `Refused` with `stale fence: lease=NAME term=N seen=M` or
171    /// `fence required: ...`.
172    pub fn to_error(&self) -> RemoteError {
173        match self {
174            FenceRefusal::Stale { lease, term, seen } => RemoteError::refused(format!("{STALE}lease={lease} term={term} seen={seen}")),
175            FenceRefusal::Required => RemoteError::refused(format!("{REQUIRED}this node takes Load and Unload only with a lease fence")),
176        }
177    }
178
179    /// The refusal in `error`, if it is one.
180    pub fn from_error(error: &RemoteError) -> Option<Self> {
181        let RemoteError::Refused { message } = error else { return None };
182        if message.starts_with(REQUIRED) {
183            return Some(FenceRefusal::Required);
184        }
185        let rest = message.strip_prefix(STALE)?;
186        let (mut lease, mut term, mut seen) = (None, None, None);
187        for part in rest.split_whitespace() {
188            match part.split_once('=') {
189                Some(("lease", v)) => lease = Some(v.to_string()),
190                Some(("term", v)) => term = v.parse().ok(),
191                Some(("seen", v)) => seen = v.parse().ok(),
192                _ => {}
193            }
194        }
195        Some(FenceRefusal::Stale { lease: lease?, term: term?, seen: seen? })
196    }
197}
198
199impl std::fmt::Display for FenceRefusal {
200    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201        match self {
202            FenceRefusal::Stale { lease, term, seen } => write!(f, "stale fence: lease {lease} term {term}, term {seen} already seen"),
203            FenceRefusal::Required => f.write_str("fence required"),
204        }
205    }
206}
207
208impl std::error::Error for FenceRefusal {}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn terms_only_go_up_per_lease() {
216        let mut g = FenceGuard::new();
217        assert_eq!(g.seen("ymir.placement"), None);
218        g.check("ymir.placement", 1).unwrap();
219        g.check("ymir.placement", 1).unwrap();
220        g.check("ymir.placement", 2).unwrap();
221        assert_eq!(g.check("ymir.placement", 1), Err(Stale { seen: 2 }));
222        assert_eq!(g.seen("ymir.placement"), Some(2), "a refused term changes nothing");
223        // Another lease name has its own counter.
224        g.check("ymir.jobs/7", 1).unwrap();
225        assert_eq!((g.seen("ymir.placement"), g.seen("ymir.jobs/7")), (Some(2), Some(1)));
226        assert_eq!(g.leases(), vec![("ymir.jobs/7".to_string(), 1), ("ymir.placement".to_string(), 2)]);
227    }
228
229    #[test]
230    fn saved_guards_survive_a_restart() {
231        let dir = tempfile::tempdir().unwrap();
232        let path = dir.path().join("state").join("fence.cbor");
233        assert_eq!(FenceGuard::load(&path).unwrap(), FenceGuard::new(), "no file yet");
234        let mut g = FenceGuard::new();
235        g.check("ymir.placement", 5).unwrap();
236        g.save(&path).unwrap();
237        let mut back = FenceGuard::load(&path).unwrap();
238        assert_eq!(back, g);
239        assert_eq!(back.check("ymir.placement", 4), Err(Stale { seen: 5 }));
240        assert!(!dir.path().join("state").join("fence.cbor.tmp").exists());
241        std::fs::write(&path, b"not cbor").unwrap();
242        assert_eq!(FenceGuard::load(&path).unwrap_err().kind(), std::io::ErrorKind::InvalidData);
243        let bad = to_cbor(&vec![("bad name".to_string(), 1u64)]).unwrap();
244        assert!(FenceGuard::import(&bad).is_err());
245    }
246
247    #[test]
248    fn refusals_read_back_from_errors() {
249        for r in [FenceRefusal::Stale { lease: "ymir.placement".into(), term: 1, seen: 2 }, FenceRefusal::Required] {
250            let e = r.to_error();
251            assert!(matches!(e, RemoteError::Refused { .. }));
252            assert_eq!(FenceRefusal::from_error(&e), Some(r.clone()));
253            // Through the wire too.
254            let back: RemoteError = from_cbor(&to_cbor(&e).unwrap()).unwrap();
255            assert_eq!(FenceRefusal::from_error(&back), Some(r));
256        }
257        assert_eq!(FenceRefusal::from_error(&RemoteError::refused("not a linked device")), None);
258        assert_eq!(FenceRefusal::from_error(&RemoteError::unavailable("stale fence: lease=a term=1 seen=2")), None);
259        assert_eq!(FenceRefusal::from_error(&RemoteError::Busy), None);
260    }
261
262    /// The bytes `weirdnet_sync::FenceGuard::export` (0.8) gives after the same checks; CI also
263    /// tests against weirdnet-sync 0.5 and 0.7, which have no `FenceGuard`, so they are fixed here.
264    const SYNC_EXPORT: [u8; 32] = [
265        0x82, 0x82, 0x6b, b'y', b'm', b'i', b'r', b'.', b'j', b'o', b'b', b's', b'/', b'7', 0x02, 0x82, 0x6e, b'y', b'm', b'i', b'r', b'.', b'p',
266        b'l', b'a', b'c', b'e', b'm', b'e', b'n', b't', 0x03,
267    ];
268
269    #[test]
270    fn saved_bytes_match_weirdnet_sync() {
271        let mut g = FenceGuard::new();
272        // The same outcomes as weirdnet_sync::FenceGuard for these checks.
273        let outcomes: Vec<_> = [("ymir.placement", 1), ("ymir.placement", 3), ("ymir.jobs/7", 2), ("ymir.placement", 2), ("ymir.jobs/7", 2)]
274            .into_iter()
275            .map(|(lease, term)| g.check(lease, term).map_err(|s| s.seen))
276            .collect();
277        assert_eq!(outcomes, vec![Ok(()), Ok(()), Ok(()), Err(3), Ok(())]);
278        assert_eq!(g.export(), SYNC_EXPORT);
279        assert_eq!(FenceGuard::import(&SYNC_EXPORT).unwrap(), g);
280    }
281
282    #[test]
283    fn lease_names_follow_weirdnet_sync() {
284        assert!(Fence::new("ymir.placement", 1).is_valid());
285        assert!(Fence::new("ymir.jobs/a-1_b:c+d#e", 1).is_valid());
286        assert!(!Fence::new("", 1).is_valid());
287        assert!(!Fence::new("has space", 1).is_valid());
288        assert!(!Fence::new("x".repeat(201), 1).is_valid());
289        assert!(Fence::new("x".repeat(200), 1).is_valid());
290    }
291}