Skip to main content

weirdnet_backends/
node.rs

1//! `/weirdnet-backends/node/1`: how inference nodes drive model nodes over `weirdnet-net`.
2//!
3//! A model node pushes a [`Capability`] record to every subscriber: signed by the node's key,
4//! chained to the user by its [`NodeCert`], with a sequence number and a 90 second expiry,
5//! refreshed every 15 seconds and on every change. It takes [`Command`]s: `Load`, `Unload`,
6//! `Drain`, `Reserve`/`Release` (hold the node's GPU for one job: nothing is placed there until
7//! released; nodes before 0.4.3 fail these calls), `GroupUp`/`GroupDown` and `Health`.
8//!
9//! Fencing (since 0.4.11): a placement lease holder sends `LoadFenced`/`UnloadFenced` with its
10//! lease name and term ([`Fence`]). The node checks them against its [`FenceGuard`] before it
11//! loads or unloads anything and refuses an older term than it has seen for that lease
12//! ([`FenceRefusal::Stale`], a `Refused` error). Unfenced `Load`/`Unload` work as before unless
13//! the node requires a fence ([`NodeService::with_fence_required`]). Nodes before 0.4.11 fail
14//! fenced commands (they close the stream) and leave `fencing` out of their records. Inference itself is raw infer/2 framing through
15//! [`ModelHost`], served next to node/1 by [`NodeServer`] on [`RAW_INFER_PROTOCOL`]
16//! (`/weirdnet-backends/infer/1`) and, unless [`NodeServerOptions::legacy_infer2`] is off, on
17//! `/weirdnet-agent/infer/2` as in 0.1.0. Inference nodes dial model nodes through
18//! [`RawInferDialer`](crate::RawInferDialer), which prefers the new id.
19//!
20//! Each stream carries one [`ClientMsg`] (CBOR, with the caller's certificate) and its answers
21//! ([`ServerMsg`]); a `Subscribe` stream stays open for records until either side closes it or
22//! the node withdraws. Which nodes may drive a model node is the [`Authorize`] hook's decision
23//! (`weirdnet_agent::serve::RosterAuth` admits the user's linked devices).
24//!
25//! Swap groups that span machines (a Ray worker or an `rpc-server` bound to a private link)
26//! are started by the application's [`GroupWorkers`]; without one, a node answers `GroupUp`
27//! with `Unsupported` and says `group_jobs: false` in its record.
28
29use std::collections::{HashMap, VecDeque};
30use std::path::PathBuf;
31use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
32use std::sync::{Arc, Mutex};
33use std::time::{Duration, Instant};
34
35use async_trait::async_trait;
36use serde::{Deserialize, Serialize};
37use tokio::sync::watch;
38use weirdnet_agent::remote::infer::{Admission, InferHost};
39use weirdnet_agent::remote::{Authorize, Caller, Channel, Dialer, RemoteError, from_cbor, to_cbor};
40use weirdnet_agent::serve::{Server, Serving, channel, stream_limits};
41use weirdnet_model::hw::{Budget, Hardware};
42use weirdnet_net::node::{Message, Node};
43use weirdnet_net::profile::Profile;
44use weirdnet_net::user::NodeCert;
45use weirdnet_net::{AppBody, AppResponse, Keypair, PeerId, PublicKey};
46
47use crate::engine::EngineKind;
48pub use crate::fence::{Fence, FenceGuard, FenceRefusal, Stale};
49use crate::host::{ModelHost, RAW_INFER_PROTOCOL, Speed};
50pub use crate::link::{AddrClass, LinkInfo, LinkMeasure};
51use crate::supervisor::{ModelState, ModelStatus, Reservation, SupervisorEvent};
52use weirdnet_agent::serve::RosterView;
53
54/// The protocol id.
55pub const PROTOCOL: &str = "/weirdnet-backends/node/1";
56/// The app name model nodes announce (`Node::serve_app`), so inference nodes find them among
57/// the user's linked devices.
58pub const MODEL_NODE_APP: &str = "weirdnet-backends-node";
59/// How long a record is good for.
60pub const RECORD_TTL: Duration = Duration::from_secs(90);
61/// How often a subscriber gets a fresh record when nothing changed.
62pub const REFRESH: Duration = Duration::from_secs(15);
63/// Accepted clock skew on a record's issue time.
64const SKEW_MS: i64 = 60_000;
65/// Signatures cover this, then the record bytes.
66const DOMAIN: &[u8] = b"weirdnet-backends/node/1 capability record\n";
67/// Recent supervisor events kept for health reports.
68const RECENT: usize = 32;
69
70fn now_ms() -> i64 {
71    weirdnet_net::now_ms()
72}
73
74/// What a model node can do right now.
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[non_exhaustive]
77pub struct Capability {
78    /// The node's peer id; the record is signed by its key.
79    pub peer: String,
80    /// Increases with every record the node issues.
81    pub seq: u64,
82    pub issued_ms: i64,
83    pub expires_ms: i64,
84    /// Accelerators, memory and interconnects.
85    pub hardware: Option<Hardware>,
86    /// Memory models may use, and how much is free.
87    pub budget: Option<Budget>,
88    /// Engines the node can run.
89    pub engines: Vec<EngineKind>,
90    /// Every model the node is configured for: loaded or loadable from disk.
91    pub models: Vec<ModelEntry>,
92    pub load: Load,
93    /// Hashes of prompt prefixes the engines hold warm (supplied by the application).
94    pub warm_prefixes: Vec<String>,
95    /// Swap groups this node is in.
96    pub groups: Vec<String>,
97    /// Draining: no new requests.
98    pub draining: bool,
99    /// Takes group jobs (`GroupUp`).
100    pub group_jobs: bool,
101    /// Reserved for a job ([`Command::Reserve`]): it runs no model, and nothing should be
102    /// placed on it until it is released. Absent when not reserved, and in records from nodes
103    /// before 0.4.3.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub reserved: Option<Reservation>,
106    /// Private interfaces (never public or CGNAT addresses), for placing swap groups. Absent
107    /// in records from 0.1.1 nodes.
108    #[serde(default, skip_serializing_if = "Vec::is_empty")]
109    pub links: Vec<LinkInfo>,
110    /// Takes fenced `Load`/`Unload` ([`Command::LoadFenced`], [`Command::UnloadFenced`]) and
111    /// checks them against its [`FenceGuard`]. False (absent) in records from nodes before
112    /// 0.4.11, which fail fenced commands.
113    #[serde(default, skip_serializing_if = "is_false")]
114    pub fencing: bool,
115    /// Refuses `Load` and `Unload` without a fence ([`NodeService::with_fence_required`]).
116    /// Absent when false. Since 0.4.11.
117    #[serde(default, skip_serializing_if = "is_false")]
118    pub fence_required: bool,
119}
120
121fn is_false(b: &bool) -> bool {
122    !*b
123}
124
125/// One model in a [`Capability`] record.
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
127#[non_exhaustive]
128pub struct ModelEntry {
129    pub status: ModelStatus,
130    pub revision: Option<String>,
131    pub quant: Option<String>,
132    /// The last measured load time, else a size-based guess.
133    pub load_secs_estimate: Option<f32>,
134    pub speed: Speed,
135    /// Where the model came from: `hub`, `upload` or `train` (a weirdnet-model provenance
136    /// origin), or an app's own ([`NodeService::set_model_origin`]). Absent when unset, and in
137    /// records from nodes before 0.4.5.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub origin: Option<String>,
140    /// The model's license: an SPDX id, or `unknown` when the uploader said so. Absent when
141    /// unset, and in records from nodes before 0.4.5.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub license: Option<String>,
144}
145
146/// The node's load.
147#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
148#[non_exhaustive]
149pub struct Load {
150    /// Requests waiting for a slot (all priorities).
151    pub queued: u32,
152    /// Requests holding a slot.
153    pub active: u32,
154    /// Concurrent request slots.
155    pub slots: u32,
156    /// Requests under way in the engines.
157    pub in_flight: u32,
158}
159
160/// A capability record with its signature and certificate.
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
162pub struct SignedRecord {
163    /// The CBOR [`Capability`].
164    #[serde(with = "serde_bytes")]
165    pub record: Vec<u8>,
166    /// The node's public key (protobuf).
167    #[serde(with = "serde_bytes")]
168    pub public_key: Vec<u8>,
169    #[serde(with = "serde_bytes")]
170    pub signature: Vec<u8>,
171    /// The user's certificate for the node.
172    pub cert: Option<NodeCert>,
173}
174
175fn signed_bytes(record: &[u8]) -> Vec<u8> {
176    [DOMAIN, record].concat()
177}
178
179impl SignedRecord {
180    /// Signs `cap` with the node's key.
181    pub fn sign(keypair: &Keypair, cap: &Capability, cert: Option<NodeCert>) -> Result<Self, RemoteError> {
182        let record = to_cbor(cap)?;
183        let signature = keypair.sign(&signed_bytes(&record)).map_err(|e| RemoteError::Failed { message: format!("signing: {e}") })?;
184        Ok(Self { record, public_key: keypair.public().encode_protobuf(), signature, cert })
185    }
186
187    /// Checks the signature, that the record is `from_peer`'s own and that it has not expired.
188    /// Says nothing about the user: see [`Verifier`].
189    pub fn verify(&self, from_peer: &str, now_ms: i64) -> Result<Capability, RemoteError> {
190        let bad = |why: &str| RemoteError::protocol(format!("capability record: {why}"));
191        let key = PublicKey::try_decode_protobuf(&self.public_key).map_err(|_| bad("bad public key"))?;
192        if PeerId::from_public_key(&key).to_string() != from_peer {
193            return Err(bad("signed by another node"));
194        }
195        if !key.verify(&signed_bytes(&self.record), &self.signature) {
196            return Err(bad("bad signature"));
197        }
198        let cap: Capability = from_cbor(&self.record)?;
199        if cap.peer != from_peer {
200            return Err(bad("names another node"));
201        }
202        if cap.expires_ms <= now_ms {
203            return Err(bad("expired"));
204        }
205        if cap.issued_ms > now_ms + SKEW_MS {
206            return Err(bad("issued in the future"));
207        }
208        Ok(cap)
209    }
210}
211
212/// Checks records against the user: valid signature, and a valid, unexpired certificate from
213/// the user for the very node that signed. With [`with_roster`](Self::with_roster) the node
214/// must also be linked in the roster now, so a revoked node presenting its old certificate is
215/// refused.
216#[derive(Clone)]
217pub struct Verifier {
218    profile: &'static Profile,
219    user: Option<PublicKey>,
220    roster: Option<RosterView>,
221}
222
223impl Verifier {
224    pub fn new(profile: &'static Profile, user: PublicKey) -> Self {
225        Self { profile, user: Some(user), roster: None }
226    }
227
228    /// Signature and expiry only (tests, or when the dialer already checked the peer).
229    pub fn signature_only(profile: &'static Profile) -> Self {
230        Self { profile, user: None, roster: None }
231    }
232
233    /// Also checks the record's node against the roster (`Roster::check_caller`): unknown,
234    /// revoked and wrong-user nodes are refused. Data-key admission doesn't matter here.
235    pub fn with_roster(mut self, roster: RosterView) -> Self {
236        self.roster = Some(roster);
237        self
238    }
239
240    pub fn verify(&self, record: &SignedRecord, from_peer: &str, now_ms: i64) -> Result<Capability, RemoteError> {
241        let cap = record.verify(from_peer, now_ms)?;
242        if let Some(user) = &self.user {
243            let ok = match &record.cert {
244                Some(c) => c.peer_id == from_peer && c.active() && self.profile.verify_cert(user, c),
245                None => false,
246            };
247            if !ok {
248                return Err(RemoteError::refused("capability record: no valid certificate from the user"));
249            }
250            if let Some(roster) = &self.roster {
251                use weirdnet_sync::CallerCheck;
252                match roster().check_caller(self.profile, user, from_peer, record.cert.as_ref()) {
253                    CallerCheck::Linked | CallerCheck::NotAdmitted => {}
254                    other => {
255                        let reason = other.reason().unwrap_or("unknown-device");
256                        return Err(RemoteError::refused(format!("capability record: {reason}")));
257                    }
258                }
259            }
260        }
261        Ok(cap)
262    }
263}
264
265/// A swap group spanning machines, as the coordinator planned it.
266#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
267#[non_exhaustive]
268pub struct GroupPlan {
269    pub group: String,
270    /// The peer that serves the group's model.
271    pub leader: String,
272    pub members: Vec<String>,
273    /// Models to unload here first.
274    pub drop: Vec<String>,
275    /// The model the leader serves.
276    pub model: Option<String>,
277    /// The private link address workers bind to.
278    pub link: Option<String>,
279    /// Worker kind, for example `ray` or `rpc-server`.
280    pub worker: Option<String>,
281    /// Anything else the application's workers need.
282    pub extra: HashMap<String, String>,
283}
284
285impl GroupPlan {
286    pub fn new(group: impl Into<String>, leader: impl Into<String>) -> Self {
287        Self { group: group.into(), leader: leader.into(), ..Default::default() }
288    }
289
290    pub fn with_members(mut self, members: Vec<String>) -> Self {
291        self.members = members;
292        self
293    }
294
295    pub fn with_drop(mut self, drop: Vec<String>) -> Self {
296        self.drop = drop;
297        self
298    }
299
300    pub fn with_model(mut self, model: impl Into<String>) -> Self {
301        self.model = Some(model.into());
302        self
303    }
304
305    pub fn with_link(mut self, link: impl Into<String>) -> Self {
306        self.link = Some(link.into());
307        self
308    }
309
310    pub fn with_worker(mut self, worker: impl Into<String>) -> Self {
311        self.worker = Some(worker.into());
312        self
313    }
314}
315
316/// Starts and stops the processes of a cross-machine swap group (a Ray worker, an
317/// `rpc-server`). The application provides it; this crate has no such adapters.
318#[async_trait]
319pub trait GroupWorkers: Send + Sync {
320    /// Join `plan` as `me` (the leader or a member), after the plan's `drop` models unloaded.
321    async fn up(&self, me: &str, plan: &GroupPlan) -> Result<(), RemoteError>;
322    async fn down(&self, group: &str) -> Result<(), RemoteError>;
323}
324
325/// A node/1 request.
326#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
327#[non_exhaustive]
328pub enum Command {
329    /// Records now and on every change, until either side closes.
330    Subscribe,
331    /// One record.
332    Record,
333    Load {
334        model: String,
335        force: bool,
336    },
337    Unload {
338        model: String,
339    },
340    /// Stop taking requests (`on`) and wait for the ones under way; or take them again.
341    Drain {
342        on: bool,
343    },
344    /// Hold the node's GPU for `holder`: drain and stop every engine and start none (loads,
345    /// requests and group jobs are refused) until `Release` by the same holder
346    /// ([`Supervisor::reserve`](crate::Supervisor::reserve)). Since 0.4.3.
347    Reserve {
348        holder: String,
349    },
350    /// End `holder`'s reservation. Since 0.4.3.
351    Release {
352        holder: String,
353    },
354    GroupUp {
355        plan: GroupPlan,
356    },
357    GroupDown {
358        group: String,
359    },
360    Health,
361    /// `Load` from a lease holder ([`Command::load_fenced`]): refused with
362    /// [`FenceRefusal::Stale`], nothing loaded, when the node has seen a newer term for the
363    /// lease. Since 0.4.11; older nodes fail the call.
364    #[non_exhaustive]
365    LoadFenced {
366        model: String,
367        force: bool,
368        fence: Fence,
369    },
370    /// `Unload` from a lease holder ([`Command::unload_fenced`]): refused with
371    /// [`FenceRefusal::Stale`], the model left as it is, when the node has seen a newer term for
372    /// the lease. Since 0.4.11; older nodes fail the call.
373    #[non_exhaustive]
374    UnloadFenced {
375        model: String,
376        fence: Fence,
377    },
378}
379
380impl Command {
381    /// [`Command::LoadFenced`].
382    pub fn load_fenced(model: impl Into<String>, force: bool, fence: Fence) -> Self {
383        Command::LoadFenced { model: model.into(), force, fence }
384    }
385
386    /// [`Command::UnloadFenced`].
387    pub fn unload_fenced(model: impl Into<String>, fence: Fence) -> Self {
388        Command::UnloadFenced { model: model.into(), fence }
389    }
390
391    /// The fence a command carries.
392    pub fn fence(&self) -> Option<&Fence> {
393        match self {
394            Command::LoadFenced { fence, .. } | Command::UnloadFenced { fence, .. } => Some(fence),
395            _ => None,
396        }
397    }
398}
399
400/// What a client sends: its certificate and one command.
401#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
402pub struct ClientMsg {
403    /// The caller's CBOR `NodeCert`, for the authorize hook.
404    #[serde(default, with = "serde_bytes")]
405    pub cert: Option<Vec<u8>>,
406    pub command: Command,
407}
408
409/// What a model node answers.
410#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
411#[non_exhaustive]
412pub enum ServerMsg {
413    Record(SignedRecord),
414    /// The command succeeded.
415    Done,
416    Health(Health),
417    Failed(RemoteError),
418    /// The node is leaving; its records are void.
419    Withdrawn {
420        peer: String,
421        seq: u64,
422    },
423}
424
425/// A health report.
426#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
427#[non_exhaustive]
428pub struct Health {
429    pub peer: String,
430    pub at_ms: i64,
431    /// No model failed or in a crash loop.
432    pub ok: bool,
433    pub draining: bool,
434    /// The node's reservation (since 0.4.3).
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub reserved: Option<Reservation>,
437    pub in_flight: u32,
438    pub uptime_secs: u64,
439    pub models: Vec<ModelHealth>,
440    /// Recent supervisor events, oldest first.
441    pub events: Vec<SupervisorEvent>,
442}
443
444#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
445#[non_exhaustive]
446pub struct ModelHealth {
447    pub id: String,
448    pub state: ModelState,
449    pub crashes: usize,
450}
451
452/// What the node says about a model in its record beyond the supervisor's status.
453#[derive(Debug, Clone, Default)]
454struct ModelInfo {
455    revision: Option<String>,
456    quant: Option<String>,
457    origin: Option<String>,
458    license: Option<String>,
459}
460
461/// A model node's node/1 side: issues records and runs commands against its [`ModelHost`].
462/// Transport-neutral ([`NodeService::serve`] takes a channel); [`NodeServer`] runs it on a
463/// `weirdnet-net` node.
464pub struct NodeService {
465    host: Arc<ModelHost>,
466    admission: Admission,
467    slots: usize,
468    keypair: Keypair,
469    peer: String,
470    cert: Option<NodeCert>,
471    auth: Arc<dyn Authorize>,
472    hardware: Option<Hardware>,
473    budget: Option<Budget>,
474    engines: Vec<EngineKind>,
475    workers: Option<Arc<dyn GroupWorkers>>,
476    drain_timeout: Duration,
477    info: Mutex<HashMap<String, ModelInfo>>,
478    warm: Mutex<Vec<String>>,
479    groups: Mutex<Vec<String>>,
480    links: Mutex<Vec<LinkInfo>>,
481    recent: Mutex<VecDeque<SupervisorEvent>>,
482    seq: AtomicU64,
483    withdrawn: AtomicBool,
484    changed: watch::Sender<u64>,
485    started: Instant,
486    fence: Mutex<FenceGuard>,
487    fence_file: Option<PathBuf>,
488    fence_required: bool,
489}
490
491impl NodeService {
492    /// `keypair` is the node's own (records are signed with it); `cert` the user's certificate
493    /// for it; `auth` decides who may drive the node.
494    pub fn new(host: Arc<ModelHost>, keypair: Keypair, cert: Option<NodeCert>, auth: Arc<dyn Authorize>) -> Self {
495        let peer = keypair.public().to_peer_id().to_string();
496        let engines = host.supervisor().status().iter().map(|m| m.engine).fold(Vec::new(), |mut v, e| {
497            if !v.contains(&e) {
498                v.push(e);
499            }
500            v
501        });
502        Self {
503            host,
504            admission: Admission::new(4),
505            slots: 4,
506            keypair,
507            peer,
508            cert,
509            auth,
510            hardware: None,
511            budget: None,
512            engines,
513            workers: None,
514            drain_timeout: Duration::from_secs(60),
515            info: Mutex::default(),
516            warm: Mutex::default(),
517            groups: Mutex::default(),
518            links: Mutex::default(),
519            recent: Mutex::default(),
520            seq: AtomicU64::new(now_ms().max(0) as u64),
521            withdrawn: AtomicBool::new(false),
522            changed: watch::Sender::new(0),
523            started: Instant::now(),
524            fence: Mutex::default(),
525            fence_file: None,
526            fence_required: false,
527        }
528    }
529
530    /// Starts fencing from `guard` (for example one the application saved). Without this or
531    /// [`with_fence_file`](Self::with_fence_file) the node still checks fenced commands, from an
532    /// empty guard kept in memory only, so a restart forgets the terms it has seen.
533    pub fn with_fence_guard(mut self, guard: FenceGuard) -> Self {
534        self.fence = Mutex::new(guard);
535        self
536    }
537
538    /// Keeps the [`FenceGuard`] in `path`: read now (an empty guard when there is no file yet)
539    /// and saved before a command with a newer term runs, so a restart keeps refusing old terms.
540    /// When the save fails, the command is refused (`Failed`) and the guard stays as it was.
541    pub fn with_fence_file(mut self, path: impl Into<PathBuf>) -> std::io::Result<Self> {
542        let path = path.into();
543        self.fence = Mutex::new(FenceGuard::load(&path)?);
544        self.fence_file = Some(path);
545        Ok(self)
546    }
547
548    /// Refuse `Load` and `Unload` without a fence ([`FenceRefusal::Required`]). Default off:
549    /// unfenced commands run as before 0.4.11, and only fenced ones are checked.
550    pub fn with_fence_required(mut self, on: bool) -> Self {
551        self.fence_required = on;
552        self
553    }
554
555    /// The terms the node has seen, per lease name.
556    pub fn fence_guard(&self) -> FenceGuard {
557        self.fence.lock().unwrap_or_else(|e| e.into_inner()).clone()
558    }
559
560    /// Checks a `Load`/`Unload`'s fence (or its absence) and records a newer term.
561    fn admit(&self, fence: Option<&Fence>) -> Result<(), RemoteError> {
562        let Some(fence) = fence else {
563            return if self.fence_required { Err(FenceRefusal::Required.to_error()) } else { Ok(()) };
564        };
565        if !fence.is_valid() {
566            return Err(RemoteError::BadRequest { message: format!("bad lease name {:?}", fence.lease) });
567        }
568        let mut guard = self.fence.lock().unwrap_or_else(|e| e.into_inner());
569        let before = guard.seen(&fence.lease);
570        let mut next = guard.clone();
571        next.check(&fence.lease, fence.term)
572            .map_err(|s| FenceRefusal::Stale { lease: fence.lease.clone(), term: fence.term, seen: s.seen }.to_error())?;
573        if before != Some(fence.term)
574            && let Some(path) = &self.fence_file
575        {
576            next.save(path).map_err(|e| RemoteError::Failed { message: format!("could not save the fence guard: {e}") })?;
577        }
578        *guard = next;
579        Ok(())
580    }
581
582    async fn load(&self, model: &str, force: bool) -> Result<(), RemoteError> {
583        if self.host.draining() {
584            return Err(RemoteError::unavailable("this node is draining"));
585        }
586        self.host.supervisor().load_with(model, force).await
587    }
588
589    /// Infer/2 admission: `slots` concurrent requests, `queue` waiting (default 4 and 0).
590    pub fn with_admission(mut self, slots: usize, queue: usize) -> Self {
591        self.admission = Admission::with_queue(slots, queue);
592        self.slots = slots;
593        self
594    }
595
596    /// The hardware and memory budget for the record (`weirdnet_model::hw::detect` and `budget`).
597    pub fn with_hardware(mut self, hardware: Hardware, budget: Budget) -> Self {
598        self.hardware = Some(hardware);
599        self.budget = Some(budget);
600        self
601    }
602
603    pub fn with_group_workers(mut self, workers: Arc<dyn GroupWorkers>) -> Self {
604        self.workers = Some(workers);
605        self
606    }
607
608    /// How long `Drain` waits for requests under way (default 60 s).
609    pub fn with_drain_timeout(mut self, d: Duration) -> Self {
610        self.drain_timeout = d;
611        self
612    }
613
614    pub fn peer(&self) -> &str {
615        &self.peer
616    }
617
618    pub fn host(&self) -> &Arc<ModelHost> {
619        &self.host
620    }
621
622    pub fn admission(&self) -> &Admission {
623        &self.admission
624    }
625
626    /// A model's revision and quantization, for the record.
627    pub fn set_model_info(&self, model: &str, revision: Option<String>, quant: Option<String>) {
628        let mut info = self.info.lock().unwrap_or_else(|e| e.into_inner());
629        let entry = info.entry(model.into()).or_default();
630        (entry.revision, entry.quant) = (revision, quant);
631        drop(info);
632        self.touch();
633    }
634
635    /// A model's origin (`hub`, `upload`, `train` or an app's own: a weirdnet-model provenance
636    /// origin) and license (an SPDX id, or `unknown`), for the record. Leaves the revision and
637    /// quantization from [`set_model_info`](Self::set_model_info) as they are; `None` clears.
638    pub fn set_model_origin(&self, model: &str, origin: Option<String>, license: Option<String>) {
639        let mut info = self.info.lock().unwrap_or_else(|e| e.into_inner());
640        let entry = info.entry(model.into()).or_default();
641        (entry.origin, entry.license) = (origin, license);
642        drop(info);
643        self.touch();
644    }
645
646    /// The private links for the record (for example `link::local_links()` with the operator's
647    /// declared speeds). Public and CGNAT addresses are dropped.
648    pub fn set_links(&self, links: Vec<LinkInfo>) {
649        *self.links.lock().unwrap_or_else(|e| e.into_inner()) = crate::link::advertised(links);
650        self.touch();
651    }
652
653    /// Prefix hashes the engines hold warm.
654    pub fn set_warm_prefixes(&self, hashes: Vec<String>) {
655        *self.warm.lock().unwrap_or_else(|e| e.into_inner()) = hashes;
656        self.touch();
657    }
658
659    /// Something in the record changed: subscribers get a fresh one.
660    pub fn touch(&self) {
661        self.changed.send_modify(|v| *v += 1);
662    }
663
664    /// The node is leaving: subscribers get `Withdrawn` and their streams end.
665    pub fn withdraw(&self) {
666        self.withdrawn.store(true, Ordering::SeqCst);
667        self.touch();
668    }
669
670    /// The current capability.
671    pub fn capability(&self) -> Capability {
672        let issued_ms = now_ms();
673        let seq = self.seq.fetch_add(1, Ordering::SeqCst) + 1;
674        let info = self.info.lock().unwrap_or_else(|e| e.into_inner()).clone();
675        let models = self
676            .host
677            .supervisor()
678            .status()
679            .into_iter()
680            .map(|status| {
681                let ModelInfo { revision, quant, origin, license } = info.get(&status.id).cloned().unwrap_or_default();
682                // Without a measured load, assume about 1 GB/s from disk plus a few seconds.
683                let load_secs_estimate = status.last_load_secs.or(status.size_bytes.map(|b| b as f32 / 1e9 + 3.0));
684                let speed = self.host.speed(&status.id);
685                ModelEntry { status, revision, quant, load_secs_estimate, speed, origin, license }
686            })
687            .collect::<Vec<_>>();
688        let in_flight = self.host.supervisor().in_flight() as u32;
689        let free = self.admission.free();
690        let load =
691            Load { queued: self.admission.waiting() as u32, active: self.slots.saturating_sub(free) as u32, slots: self.slots as u32, in_flight };
692        Capability {
693            peer: self.peer.clone(),
694            seq,
695            issued_ms,
696            expires_ms: issued_ms + RECORD_TTL.as_millis() as i64,
697            hardware: self.hardware.clone(),
698            budget: self.budget,
699            engines: self.engines.clone(),
700            models,
701            load,
702            warm_prefixes: self.warm.lock().unwrap_or_else(|e| e.into_inner()).clone(),
703            groups: self.groups.lock().unwrap_or_else(|e| e.into_inner()).clone(),
704            draining: self.host.draining(),
705            group_jobs: self.workers.is_some(),
706            reserved: self.host.supervisor().reservation(),
707            links: self.links.lock().unwrap_or_else(|e| e.into_inner()).clone(),
708            fencing: true,
709            fence_required: self.fence_required,
710        }
711    }
712
713    /// The current capability, signed.
714    pub fn record(&self) -> Result<SignedRecord, RemoteError> {
715        SignedRecord::sign(&self.keypair, &self.capability(), self.cert.clone())
716    }
717
718    pub fn health(&self) -> Health {
719        let status = self.host.supervisor().status();
720        let ok = status.iter().all(|m| !matches!(m.state, ModelState::Failed(_)));
721        Health {
722            peer: self.peer.clone(),
723            at_ms: now_ms(),
724            ok,
725            draining: self.host.draining(),
726            reserved: self.host.supervisor().reservation(),
727            in_flight: self.host.supervisor().in_flight() as u32,
728            uptime_secs: self.started.elapsed().as_secs(),
729            models: status.into_iter().map(|m| ModelHealth { id: m.id, state: m.state, crashes: m.crashes }).collect(),
730            events: self.recent.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect(),
731        }
732    }
733
734    /// Keeps the record current with the supervisor's events. Runs until the supervisor goes.
735    pub fn watch(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
736        let me = self.clone();
737        let mut events = self.host.supervisor().subscribe();
738        let mut reserved = self.host.supervisor().reservation_changes();
739        tokio::spawn(async move {
740            loop {
741                let ev = tokio::select! {
742                    ev = events.recv() => ev,
743                    r = reserved.changed() => {
744                        if r.is_err() {
745                            return;
746                        }
747                        me.touch();
748                        continue;
749                    }
750                };
751                match ev {
752                    Ok(ev) => {
753                        let mut recent = me.recent.lock().unwrap_or_else(|e| e.into_inner());
754                        if recent.len() == RECENT {
755                            recent.pop_front();
756                        }
757                        recent.push_back(ev);
758                    }
759                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
760                    Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
761                }
762                me.touch();
763            }
764        })
765    }
766
767    async fn run(&self, command: Command) -> Result<ServerMsg, RemoteError> {
768        let sup = self.host.supervisor();
769        let done = match command {
770            Command::Record => return Ok(ServerMsg::Record(self.record()?)),
771            Command::Health => return Ok(ServerMsg::Health(self.health())),
772            Command::Load { model, force } => {
773                self.admit(None)?;
774                self.load(&model, force).await
775            }
776            Command::LoadFenced { model, force, fence } => {
777                self.admit(Some(&fence))?;
778                self.load(&model, force).await
779            }
780            Command::Unload { model } => {
781                self.admit(None)?;
782                sup.unload(&model).await
783            }
784            Command::UnloadFenced { model, fence } => {
785                self.admit(Some(&fence))?;
786                sup.unload(&model).await
787            }
788            Command::Drain { on } => {
789                self.host.set_draining(on);
790                self.touch();
791                if on {
792                    let deadline = Instant::now() + self.drain_timeout;
793                    while sup.in_flight() > 0 || self.admission.free() < self.slots {
794                        if Instant::now() >= deadline {
795                            return Err(RemoteError::Timeout);
796                        }
797                        tokio::time::sleep(Duration::from_millis(50)).await;
798                    }
799                }
800                Ok(())
801            }
802            Command::Reserve { holder } => sup.reserve(&holder).await.map(|_| ()),
803            Command::Release { holder } => sup.release(&holder).map(|_| ()),
804            Command::GroupUp { plan } => {
805                if let Some(r) = sup.reservation() {
806                    return Err(RemoteError::unavailable(format!("this node is reserved by {}", r.holder)));
807                }
808                let workers = self.workers.as_ref().ok_or_else(|| RemoteError::Unsupported { message: "this node takes no group jobs".into() })?;
809                for model in &plan.drop {
810                    sup.unload(model).await?;
811                }
812                workers.up(&self.peer, &plan).await?;
813                let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
814                if !groups.contains(&plan.group) {
815                    groups.push(plan.group.clone());
816                }
817                Ok(())
818            }
819            Command::GroupDown { group } => {
820                let workers = self.workers.as_ref().ok_or_else(|| RemoteError::Unsupported { message: "this node takes no group jobs".into() })?;
821                workers.down(&group).await?;
822                self.groups.lock().unwrap_or_else(|e| e.into_inner()).retain(|g| *g != group);
823                Ok(())
824            }
825            Command::Subscribe => unreachable!("handled by serve"),
826        };
827        self.touch();
828        done.map(|()| ServerMsg::Done)
829    }
830
831    /// Serves one node/1 stream. `caller` is the transport-authenticated peer.
832    pub async fn serve(&self, mut ch: Channel, caller: Caller) -> Result<(), RemoteError> {
833        let Some(msg) = ch.recv_cbor::<ClientMsg>().await? else { return Ok(()) };
834        let caller = match (caller.cert_bytes.is_some(), msg.cert) {
835            (false, Some(cert)) => caller.with_cert(cert),
836            (_, _) => caller,
837        };
838        if let Err(e) = self.auth.authorize(&caller) {
839            return ch.send_cbor(&ServerMsg::Failed(e)).await;
840        }
841        if msg.command != Command::Subscribe {
842            let answer = self.run(msg.command).await.unwrap_or_else(ServerMsg::Failed);
843            return ch.send_cbor(&answer).await;
844        }
845        let mut changed = self.changed.subscribe();
846        loop {
847            if self.withdrawn.load(Ordering::SeqCst) {
848                let seq = self.seq.fetch_add(1, Ordering::SeqCst) + 1;
849                return ch.send_cbor(&ServerMsg::Withdrawn { peer: self.peer.clone(), seq }).await;
850            }
851            ch.send_cbor(&ServerMsg::Record(self.record()?)).await?;
852            changed.mark_unchanged();
853            tokio::select! {
854                r = changed.changed() => if r.is_err() { return Ok(()) },
855                _ = tokio::time::sleep(REFRESH) => {}
856                r = ch.rx.recv() => match r {
857                    Ok(None) | Err(_) => return Ok(()),
858                    Ok(Some(_)) => return Err(RemoteError::protocol("unexpected message on a subscription")),
859                },
860            }
861        }
862    }
863}
864
865/// How a [`NodeServer`] serves raw inference.
866#[derive(Debug, Clone, Copy, PartialEq, Eq)]
867#[non_exhaustive]
868pub struct NodeServerOptions {
869    /// Also serve raw inference on `/weirdnet-agent/infer/2` (and infer/1), for inference nodes
870    /// on backends 0.1.0. Default on. Turn it off on a node that is also an inference node, so
871    /// its inference role can serve infer/2 to apps.
872    pub legacy_infer2: bool,
873}
874
875impl Default for NodeServerOptions {
876    fn default() -> Self {
877        Self { legacy_infer2: true }
878    }
879}
880
881impl NodeServerOptions {
882    pub fn with_legacy_infer2(mut self, on: bool) -> Self {
883        self.legacy_infer2 = on;
884        self
885    }
886}
887
888/// Serves a [`NodeService`] on a `weirdnet-net` node: node/1, raw inference through the
889/// service's [`ModelHost`] on [`RAW_INFER_PROTOCOL`] (and infer/2, see [`NodeServerOptions`];
890/// no catalog, no inference announcement) and the [`MODEL_NODE_APP`] announcement, which lists
891/// the protocols served. Dropping it stops serving.
892pub struct NodeServer {
893    _infer: Option<Server>,
894    tasks: Vec<tokio::task::JoinHandle<()>>,
895    stop_app: Box<dyn Fn() + Send + Sync>,
896}
897
898impl NodeServer {
899    /// Starts serving with the default [`NodeServerOptions`] (raw inference on both ids). Call
900    /// from a Tokio runtime. The service's key must be the node's.
901    pub fn start<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, service: Arc<NodeService>) -> Result<NodeServer, RemoteError> {
902        Self::start_with(node, service, NodeServerOptions::default())
903    }
904
905    /// Starts serving with `options`.
906    pub fn start_with<Q: Message, R: Message>(
907        node: &Arc<Node<Q, R>>,
908        service: Arc<NodeService>,
909        options: NodeServerOptions,
910    ) -> Result<NodeServer, RemoteError> {
911        let net = |e: weirdnet_net::NetError| RemoteError::Failed { message: e.to_string() };
912        if node.peer_id().to_string() != service.peer {
913            return Err(RemoteError::Failed { message: "the service's keypair is not this node's".into() });
914        }
915        let host: Arc<dyn InferHost> = service.host.clone();
916        let mut raw = node.accept_streams(RAW_INFER_PROTOCOL, stream_limits()).map_err(net)?;
917        let (h, a) = (host.clone(), service.admission.clone());
918        let raw_accept = tokio::spawn(async move {
919            while let Some(stream) = futures::StreamExt::next(&mut raw).await {
920                let caller = Caller::new(stream.peer().to_string());
921                let (h, a) = (h.clone(), a.clone());
922                tokio::spawn(async move {
923                    let _ = weirdnet_agent::remote::infer::v2::serve(channel(stream), caller, h.as_ref(), &a).await;
924                });
925            }
926        });
927        let infer = if options.legacy_infer2 {
928            Some(Server::start(node, Serving { infer: Some((host, service.admission.clone())), catalog: None, announce: false })?)
929        } else {
930            None
931        };
932        let mut incoming = node.accept_streams(PROTOCOL, stream_limits()).map_err(net)?;
933        let svc = service.clone();
934        let accept = tokio::spawn(async move {
935            while let Some(stream) = futures::StreamExt::next(&mut incoming).await {
936                let caller = Caller::new(stream.peer().to_string());
937                let svc = svc.clone();
938                tokio::spawn(async move {
939                    let _ = svc.serve(channel(stream), caller).await;
940                });
941            }
942        });
943        let mut protocols = vec![PROTOCOL, RAW_INFER_PROTOCOL];
944        if options.legacy_infer2 {
945            protocols.push(weirdnet_agent::remote::infer::v2::PROTOCOL);
946        }
947        let body = to_cbor(&protocols)?;
948        node.serve_app(
949            MODEL_NODE_APP,
950            Arc::new(move |_peer, _req| {
951                let body = body.clone();
952                async move { Ok(AppResponse::new(200).header("content-type", "application/cbor").body(AppBody::bytes(body))) }
953            }),
954        )
955        .map_err(|e| RemoteError::Failed { message: e.to_string() })?;
956        let n = node.clone();
957        Ok(NodeServer {
958            _infer: infer,
959            tasks: vec![accept, raw_accept, service.watch()],
960            stop_app: Box::new(move || {
961                n.stop_serving_app(MODEL_NODE_APP);
962            }),
963        })
964    }
965}
966
967impl Drop for NodeServer {
968    fn drop(&mut self) {
969        for t in &self.tasks {
970            t.abort();
971        }
972        (self.stop_app)();
973    }
974}
975
976/// An update on a [`Subscription`].
977#[derive(Debug, Clone, PartialEq)]
978#[non_exhaustive]
979pub enum Update {
980    Record(Box<Capability>),
981    /// The node left; forget its records.
982    Withdrawn,
983}
984
985/// Verified records from one model node.
986pub struct Subscription {
987    ch: Channel,
988    node: String,
989    verifier: Verifier,
990    last_seq: u64,
991    done: bool,
992}
993
994impl Subscription {
995    /// The next update; `None` when the stream ended. Records are verified and their sequence
996    /// numbers must increase.
997    pub async fn next(&mut self) -> Option<Result<Update, RemoteError>> {
998        if self.done {
999            return None;
1000        }
1001        let msg = match self.ch.recv_cbor::<ServerMsg>().await {
1002            Ok(Some(m)) => m,
1003            Ok(None) => {
1004                self.done = true;
1005                return None;
1006            }
1007            Err(e) => {
1008                self.done = true;
1009                return Some(Err(e));
1010            }
1011        };
1012        let out = match msg {
1013            ServerMsg::Record(r) => self.verifier.verify(&r, &self.node, now_ms()).and_then(|cap| {
1014                if cap.seq <= self.last_seq {
1015                    return Err(RemoteError::protocol("capability record: sequence went backwards"));
1016                }
1017                self.last_seq = cap.seq;
1018                Ok(Update::Record(Box::new(cap)))
1019            }),
1020            ServerMsg::Withdrawn { seq, .. } if seq > self.last_seq => Ok(Update::Withdrawn),
1021            ServerMsg::Failed(e) => Err(e),
1022            other => Err(RemoteError::protocol(format!("unexpected {other:?} on a subscription"))),
1023        };
1024        if !matches!(out, Ok(Update::Record(_))) {
1025            self.done = true;
1026        }
1027        Some(out)
1028    }
1029}
1030
1031/// An inference node's side of node/1: drives model nodes over a [`Dialer`]
1032/// (`weirdnet_agent::pool::NetDialer` on Weirdnet).
1033pub struct NodeClient {
1034    dialer: Arc<dyn Dialer>,
1035    verifier: Verifier,
1036    cert: Option<Vec<u8>>,
1037}
1038
1039impl NodeClient {
1040    pub fn new(dialer: Arc<dyn Dialer>, verifier: Verifier) -> Self {
1041        Self { dialer, verifier, cert: None }
1042    }
1043
1044    /// This node's CBOR `NodeCert` (`weirdnet_agent::pool::encode_cert`), presented to model nodes.
1045    pub fn with_cert(mut self, cert: Option<Vec<u8>>) -> Self {
1046        self.cert = cert;
1047        self
1048    }
1049
1050    async fn open(&self, node: &str, command: Command) -> Result<Channel, RemoteError> {
1051        let mut ch = self.dialer.open(node, PROTOCOL).await?;
1052        ch.send_cbor(&ClientMsg { cert: self.cert.clone(), command }).await?;
1053        Ok(ch)
1054    }
1055
1056    async fn call(&self, node: &str, command: Command) -> Result<ServerMsg, RemoteError> {
1057        let mut ch = self.open(node, command).await?;
1058        match ch.recv_cbor::<ServerMsg>().await? {
1059            Some(ServerMsg::Failed(e)) => Err(e),
1060            Some(m) => Ok(m),
1061            None => Err(RemoteError::Closed),
1062        }
1063    }
1064
1065    async fn done(&self, node: &str, command: Command) -> Result<(), RemoteError> {
1066        match self.call(node, command).await? {
1067            ServerMsg::Done => Ok(()),
1068            other => Err(RemoteError::protocol(format!("expected done, got {other:?}"))),
1069        }
1070    }
1071
1072    /// The node's current record, verified.
1073    pub async fn record(&self, node: &str) -> Result<Capability, RemoteError> {
1074        match self.call(node, Command::Record).await? {
1075            ServerMsg::Record(r) => self.verifier.verify(&r, node, now_ms()),
1076            other => Err(RemoteError::protocol(format!("expected a record, got {other:?}"))),
1077        }
1078    }
1079
1080    /// Records now and on every change.
1081    pub async fn subscribe(&self, node: &str) -> Result<Subscription, RemoteError> {
1082        let ch = self.open(node, Command::Subscribe).await?;
1083        Ok(Subscription { ch, node: node.into(), verifier: self.verifier.clone(), last_seq: 0, done: false })
1084    }
1085
1086    /// Loads `model` and waits until it is ready. `force` also loads a model in a crash loop.
1087    pub async fn load(&self, node: &str, model: &str, force: bool) -> Result<(), RemoteError> {
1088        self.done(node, Command::Load { model: model.into(), force }).await
1089    }
1090
1091    pub async fn unload(&self, node: &str, model: &str) -> Result<(), RemoteError> {
1092        self.done(node, Command::Unload { model: model.into() }).await
1093    }
1094
1095    /// [`load`](Self::load) under a lease: the node refuses it, loading nothing, when it has
1096    /// seen a newer term for `fence`'s lease ([`FenceRefusal::from_error`] reads the refusal;
1097    /// don't retry it). Needs a node at 0.4.11 or later (`Capability::fencing`).
1098    pub async fn load_fenced(&self, node: &str, model: &str, force: bool, fence: &Fence) -> Result<(), RemoteError> {
1099        self.done(node, Command::load_fenced(model, force, fence.clone())).await
1100    }
1101
1102    /// [`unload`](Self::unload) under a lease: refused, the model left as it is, when the node
1103    /// has seen a newer term for `fence`'s lease. Needs a node at 0.4.11 or later.
1104    pub async fn unload_fenced(&self, node: &str, model: &str, fence: &Fence) -> Result<(), RemoteError> {
1105        self.done(node, Command::unload_fenced(model, fence.clone())).await
1106    }
1107
1108    /// Drains (waiting for requests under way) or resumes.
1109    pub async fn drain(&self, node: &str, on: bool) -> Result<(), RemoteError> {
1110        self.done(node, Command::Drain { on }).await
1111    }
1112
1113    /// Reserves the node's GPU for `holder` ([`Command::Reserve`]): returns once its engines are
1114    /// stopped. A node before 0.4.3 fails the call.
1115    pub async fn reserve(&self, node: &str, holder: &str) -> Result<(), RemoteError> {
1116        self.done(node, Command::Reserve { holder: holder.into() }).await
1117    }
1118
1119    /// Ends `holder`'s reservation.
1120    pub async fn release(&self, node: &str, holder: &str) -> Result<(), RemoteError> {
1121        self.done(node, Command::Release { holder: holder.into() }).await
1122    }
1123
1124    pub async fn group_up(&self, node: &str, plan: GroupPlan) -> Result<(), RemoteError> {
1125        self.done(node, Command::GroupUp { plan }).await
1126    }
1127
1128    pub async fn group_down(&self, node: &str, group: &str) -> Result<(), RemoteError> {
1129        self.done(node, Command::GroupDown { group: group.into() }).await
1130    }
1131
1132    pub async fn health(&self, node: &str) -> Result<Health, RemoteError> {
1133        match self.call(node, Command::Health).await? {
1134            ServerMsg::Health(h) => Ok(h),
1135            other => Err(RemoteError::protocol(format!("expected health, got {other:?}"))),
1136        }
1137    }
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142    use super::*;
1143    use crate::supervisor::{Supervisor, SupervisorOptions};
1144    use weirdnet_agent::remote::{from_cbor, to_cbor};
1145    use weirdnet_net::WEIRDNET;
1146
1147    fn service() -> (NodeService, Keypair) {
1148        let sup = Supervisor::new(vec![], vec![], SupervisorOptions::default());
1149        let auth: Arc<dyn Authorize> = Arc::new(|_: &Caller| Ok(()));
1150        let host = Arc::new(ModelHost::new(sup, auth.clone()));
1151        let kp = Keypair::generate_ed25519();
1152        (NodeService::new(host, kp.clone(), None, auth), kp)
1153    }
1154
1155    #[test]
1156    fn records_verify_and_tampering_fails() {
1157        let (svc, _) = service();
1158        let rec = svc.record().unwrap();
1159        let v = Verifier::signature_only(&WEIRDNET);
1160        let cap = v.verify(&rec, svc.peer(), now_ms()).unwrap();
1161        assert_eq!((cap.peer.as_str(), cap.draining, cap.group_jobs), (svc.peer(), false, false));
1162        assert!(cap.expires_ms - cap.issued_ms == 90_000);
1163        let mut bad = rec.clone();
1164        let mid = bad.record.len() / 2;
1165        bad.record[mid] ^= 1;
1166        assert!(v.verify(&bad, svc.peer(), now_ms()).is_err());
1167        assert!(v.verify(&rec, &PeerId::random().to_string(), now_ms()).is_err(), "another peer's record");
1168        assert!(v.verify(&rec, svc.peer(), cap.expires_ms).is_err(), "expired");
1169        let user = Keypair::generate_ed25519();
1170        assert!(Verifier::new(&WEIRDNET, user.public()).verify(&rec, svc.peer(), now_ms()).is_err(), "no certificate");
1171        assert!(svc.record().unwrap().verify(svc.peer(), now_ms()).unwrap().seq > cap.seq);
1172    }
1173
1174    /// node/1 commands as a 0.4.10 node reads them.
1175    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1176    enum OldCommand {
1177        Load { model: String, force: bool },
1178        Unload { model: String },
1179        Health,
1180    }
1181
1182    #[derive(Debug, Serialize, Deserialize)]
1183    struct OldClientMsg {
1184        #[serde(default, with = "serde_bytes")]
1185        cert: Option<Vec<u8>>,
1186        command: OldCommand,
1187    }
1188
1189    fn msg(command: Command) -> Vec<u8> {
1190        to_cbor(&ClientMsg { cert: None, command }).unwrap()
1191    }
1192
1193    #[test]
1194    fn fenced_commands_on_the_wire() {
1195        let fence = Fence::new("ymir.placement", 7);
1196        // Unfenced commands are the same bytes as before, both ways.
1197        for (new, old) in [
1198            (Command::Load { model: "chat".into(), force: true }, OldCommand::Load { model: "chat".into(), force: true }),
1199            (Command::Unload { model: "chat".into() }, OldCommand::Unload { model: "chat".into() }),
1200        ] {
1201            let bytes = msg(new.clone());
1202            assert_eq!(bytes, to_cbor(&OldClientMsg { cert: None, command: old.clone() }).unwrap(), "same bytes as 0.4.10");
1203            assert_eq!(from_cbor::<OldClientMsg>(&bytes).unwrap().command, old, "an old node reads it");
1204            assert_eq!(from_cbor::<Command>(&to_cbor(&old).unwrap()).unwrap(), new, "a new node reads an old client's");
1205            assert_eq!(new.fence(), None);
1206        }
1207        // Fenced commands round-trip (CBOR and JSON).
1208        for cmd in [Command::load_fenced("chat", false, fence.clone()), Command::unload_fenced("chat", fence.clone())] {
1209            assert_eq!(cmd.fence(), Some(&fence));
1210            let back: ClientMsg = from_cbor(&msg(cmd.clone())).unwrap();
1211            assert_eq!(back.command, cmd);
1212            let json = serde_json::to_value(&cmd).unwrap();
1213            assert_eq!(serde_json::from_value::<Command>(json.clone()).unwrap(), cmd);
1214            assert_eq!(json.as_object().unwrap().values().next().unwrap()["fence"], serde_json::json!({ "lease": "ymir.placement", "term": 7 }));
1215            // An old node can't read it: the call fails rather than running unfenced.
1216            assert!(from_cbor::<OldClientMsg>(&msg(cmd)).is_err());
1217        }
1218    }
1219
1220    #[test]
1221    fn records_say_fencing() {
1222        let (svc, _) = service();
1223        let cap = svc.capability();
1224        assert!(cap.fencing && !cap.fence_required);
1225        let bytes = to_cbor(&cap).unwrap();
1226        assert!(!bytes.windows(14).any(|w| w == b"fence_required"), "false is left out");
1227        // A record from an older node has neither field.
1228        let mut old = serde_json::to_value(&cap).unwrap();
1229        old.as_object_mut().unwrap().remove("fencing");
1230        let back: Capability = serde_json::from_value(old).unwrap();
1231        assert!(!back.fencing && !back.fence_required);
1232        let (svc, _) = service();
1233        assert!(svc.with_fence_required(true).capability().fence_required);
1234    }
1235
1236    fn refusal(r: Result<ServerMsg, RemoteError>) -> Option<FenceRefusal> {
1237        FenceRefusal::from_error(&r.unwrap_err())
1238    }
1239
1240    #[tokio::test]
1241    async fn the_guard_refuses_old_terms() {
1242        let (svc, _) = service();
1243        let f = |lease: &str, term| Fence::new(lease, term);
1244        // No model "m" on this node: a command that passes the fence fails as unknown model,
1245        // one that doesn't is a fencing refusal.
1246        let passed = |r: Result<ServerMsg, RemoteError>| matches!(r, Err(RemoteError::Unavailable { .. }));
1247        assert!(passed(svc.run(Command::load_fenced("m", false, f("ymir.placement", 1))).await));
1248        assert!(passed(svc.run(Command::load_fenced("m", false, f("ymir.placement", 2))).await));
1249        assert!(passed(svc.run(Command::unload_fenced("m", f("ymir.placement", 2))).await), "the same term again");
1250        assert_eq!(
1251            refusal(svc.run(Command::load_fenced("m", false, f("ymir.placement", 1))).await),
1252            Some(FenceRefusal::Stale { lease: "ymir.placement".into(), term: 1, seen: 2 })
1253        );
1254        assert_eq!(
1255            refusal(svc.run(Command::unload_fenced("m", f("ymir.placement", 1))).await),
1256            Some(FenceRefusal::Stale { lease: "ymir.placement".into(), term: 1, seen: 2 })
1257        );
1258        // Another lease keeps its own term.
1259        assert!(passed(svc.run(Command::unload_fenced("m", f("other.lease", 1))).await));
1260        assert_eq!((svc.fence_guard().seen("ymir.placement"), svc.fence_guard().seen("other.lease")), (Some(2), Some(1)));
1261        // Unfenced commands run as before while a fence isn't required.
1262        assert!(passed(svc.run(Command::Load { model: "m".into(), force: false }).await));
1263        assert!(passed(svc.run(Command::Unload { model: "m".into() }).await));
1264        // Bad lease names are bad requests and record nothing.
1265        assert!(matches!(svc.run(Command::load_fenced("m", false, f("bad name", 9))).await, Err(RemoteError::BadRequest { .. })));
1266        assert_eq!(svc.fence_guard().leases().len(), 2);
1267    }
1268
1269    #[tokio::test]
1270    async fn a_required_fence_refuses_unfenced_commands() {
1271        let (svc, _) = service();
1272        let svc = svc.with_fence_required(true);
1273        assert_eq!(refusal(svc.run(Command::Load { model: "m".into(), force: false }).await), Some(FenceRefusal::Required));
1274        assert_eq!(refusal(svc.run(Command::Unload { model: "m".into() }).await), Some(FenceRefusal::Required));
1275        assert!(matches!(svc.run(Command::load_fenced("m", false, Fence::new("ymir.placement", 1))).await, Err(RemoteError::Unavailable { .. })));
1276        // Other commands don't need one.
1277        assert!(matches!(svc.run(Command::Health).await, Ok(ServerMsg::Health(_))));
1278    }
1279
1280    #[tokio::test]
1281    async fn a_fence_file_keeps_terms_across_restarts() {
1282        let dir = tempfile::tempdir().unwrap();
1283        let path = dir.path().join("fence.cbor");
1284        let (svc, _) = service();
1285        let svc = svc.with_fence_file(&path).unwrap();
1286        let _ = svc.run(Command::load_fenced("m", false, Fence::new("ymir.placement", 3))).await;
1287        assert_eq!(FenceGuard::load(&path).unwrap().seen("ymir.placement"), Some(3));
1288        // A restarted node reads it back and still refuses term 2.
1289        let (svc, _) = service();
1290        let svc = svc.with_fence_file(&path).unwrap();
1291        assert_eq!(
1292            refusal(svc.run(Command::unload_fenced("m", Fence::new("ymir.placement", 2))).await),
1293            Some(FenceRefusal::Stale { lease: "ymir.placement".into(), term: 2, seen: 3 })
1294        );
1295        // A guard handed over by the application works the same.
1296        let (svc, _) = service();
1297        let svc = svc.with_fence_guard(FenceGuard::load(&path).unwrap());
1298        assert!(refusal(svc.run(Command::load_fenced("m", false, Fence::new("ymir.placement", 1))).await).is_some());
1299        // When the guard can't be saved, a newer term is refused and not recorded.
1300        let blocker = dir.path().join("not-a-dir");
1301        let (svc, _) = service();
1302        let svc = svc.with_fence_file(blocker.join("fence.cbor")).unwrap();
1303        std::fs::write(&blocker, b"").unwrap();
1304        assert!(matches!(svc.run(Command::load_fenced("m", false, Fence::new("ymir.placement", 4))).await, Err(RemoteError::Failed { .. })));
1305        assert_eq!(svc.fence_guard().seen("ymir.placement"), None);
1306    }
1307}