Skip to main content

weirdnet_backends/models/
placed.rs

1//! Placement hooks: the app hears about every entry a [`ModelsService`] puts in its store.
2//!
3//! [`ModelsService::on_placed`] registers a callback that runs after an upload, a copy from
4//! another node ([`PullSource::Peer`](super::PullSource::Peer), which is also what [`ModelsClient::replicate`](super::ModelsClient::replicate) makes each
5//! target do) or a Hub pull has placed its files (and served them, when asked). It gets a
6//! [`Placed`]: the stored entry as `List` would show it (with its provenance), the
7//! [`Pulled`] answer (with the content revision) and how it arrived. Apps use it to update their
8//! own records and the node's capability record without a protocol of their own;
9//! [`ModelsService::with_node_info`] does the capability part.
10//!
11//! Uploads and peer copies fire once their files are placed, even when serving them then fails
12//! ([`Placed::serve_error`]); Hub pulls fire when the pull succeeds.
13//!
14//! Callbacks run on the task that placed the entry, before the client gets its answer, so they
15//! should be quick: hand slow work to a task or a channel. A panicking callback is caught and
16//! does not fail the placement.
17
18use std::panic::{AssertUnwindSafe, catch_unwind};
19use std::sync::Arc;
20
21use weirdnet_agent::remote::RemoteError;
22use weirdnet_model::artifact::Provenance;
23use weirdnet_model::{Imported, ModelLayout};
24
25use super::{ModelsService, Pulled, StoredEntry};
26use crate::node::NodeService;
27
28/// How a placed entry arrived.
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum PlacedVia {
32    /// Uploaded by a client ([`super::ModelsCommand::Upload`]).
33    Upload,
34    /// Copied from node `node` ([`PullSource::Peer`](super::PullSource::Peer)).
35    Peer { node: String },
36    /// Downloaded from Hub repo `repo` ([`super::ModelsCommand::Pull`]).
37    Hub { repo: String },
38}
39
40/// One entry placed in the store; see [`ModelsService::on_placed`].
41#[derive(Debug, Clone, PartialEq)]
42#[non_exhaustive]
43pub struct Placed {
44    /// The stored model, adapter or projector, with its provenance and serving state.
45    pub entry: StoredEntry,
46    /// The answer the client gets (files, size, whether it is served, the revision).
47    pub pulled: Pulled,
48    pub via: PlacedVia,
49    /// Set when the files were placed but serving them failed (the client gets this error);
50    /// the entry stays in the store.
51    pub serve_error: Option<RemoteError>,
52}
53
54impl Placed {
55    /// The entry's id in the store.
56    pub fn id(&self) -> &str {
57        &self.pulled.id
58    }
59
60    /// The content revision (uploads and peer copies; `None` for Hub pulls).
61    pub fn revision(&self) -> Option<&str> {
62        self.pulled.revision.as_deref()
63    }
64
65    /// Where it came from, for uploaded (and trained) entries.
66    pub fn provenance(&self) -> Option<&Provenance> {
67        self.entry.provenance()
68    }
69
70    /// The supervisor id it is served under, if it is served.
71    pub fn served_as(&self) -> Option<&str> {
72        self.entry.served_as.as_deref().or(self.pulled.served.then_some(self.pulled.id.as_str()))
73    }
74
75    /// Its origin (`hub`, `upload`, `train` or an app's own) and license, for the capability
76    /// record: the provenance's, else `upload` or `hub` by how it arrived (a peer copy without
77    /// provenance has none).
78    pub fn origin_and_license(&self) -> (Option<String>, Option<String>) {
79        let p = self.provenance();
80        let origin = p.map(|p| p.origin.clone()).filter(|o| !o.is_empty()).or_else(|| match self.via {
81            PlacedVia::Upload => Some(weirdnet_model::artifact::ORIGIN_UPLOAD.into()),
82            PlacedVia::Hub { .. } => Some(weirdnet_model::artifact::ORIGIN_HUB.into()),
83            _ => None,
84        });
85        (origin, p.and_then(|p| p.license.clone()))
86    }
87
88    /// The quantization in a GGUF model's file name (`Q4_K_M`), if any.
89    pub fn quant(&self) -> Option<String> {
90        let model = self.entry.model.as_ref().filter(|m| m.layout == ModelLayout::Gguf)?;
91        let name = model.files.first()?.rsplit('/').next()?;
92        weirdnet_model::hf::quant_of(name)
93    }
94}
95
96/// A placement callback ([`ModelsService::on_placed`]).
97pub type OnPlaced = Arc<dyn Fn(&Placed) + Send + Sync>;
98
99impl ModelsService {
100    /// Calls `hook` after each upload, peer copy or Hub pull is placed (see [`Placed`]).
101    /// Several hooks run in the order they were added.
102    pub fn on_placed(mut self, hook: impl Fn(&Placed) + Send + Sync + 'static) -> Self {
103        self.placed.push(Arc::new(hook));
104        self
105    }
106
107    /// Keeps `node`'s capability record current: each placed entry with a revision (uploads and
108    /// peer copies) goes to [`NodeService::set_model_info`] under the id it is served as (its
109    /// store id when it is not served), with the quantization from a GGUF model's file name.
110    /// Hub pulls carry no revision and leave those alone. Each placed entry's origin (its
111    /// provenance's, else `upload` or `hub` by how it arrived) and license go to
112    /// [`NodeService::set_model_origin`].
113    pub fn with_node_info(self, node: Arc<NodeService>) -> Self {
114        self.on_placed(move |p| {
115            if let Some(revision) = p.revision() {
116                let id = p.served_as().unwrap_or(p.id()).to_string();
117                node.set_model_info(&id, Some(revision.to_string()), p.quant());
118            }
119            let (origin, license) = p.origin_and_license();
120            if origin.is_some() || license.is_some() {
121                node.set_model_origin(p.served_as().unwrap_or(p.id()), origin, license);
122            }
123        })
124    }
125
126    /// Runs the placement hooks for `pulled`, finding its entry in the store.
127    pub(super) fn fire_placed(&self, pulled: &Pulled, via: PlacedVia, imported: Option<&Imported>, serve_error: Option<&RemoteError>) {
128        if self.placed.is_empty() {
129            return;
130        }
131        let Some(entry) = self.placed_entry(pulled, imported) else { return };
132        let placed = Placed { entry, pulled: pulled.clone(), via, serve_error: serve_error.cloned() };
133        for hook in &self.placed {
134            let _ = catch_unwind(AssertUnwindSafe(|| hook(&placed)));
135        }
136    }
137
138    fn placed_entry(&self, pulled: &Pulled, imported: Option<&Imported>) -> Option<StoredEntry> {
139        let projector = pulled.projector_for.is_some() || matches!(imported, Some(Imported::Projector(_)));
140        let adapter = pulled.adapter_for.is_some() || matches!(imported, Some(Imported::Adapter(_)));
141        let first = pulled.files.first();
142        let found = self.list().into_iter().find(|e| match (&e.model, &e.adapter, &e.projector) {
143            (Some(m), _, _) if !adapter && !projector => m.id == pulled.id || first.is_some_and(|f| m.files.first() == Some(f)),
144            (_, Some(a), _) if adapter => a.id == pulled.id,
145            (_, _, Some(p)) if projector => p.id == pulled.id,
146            _ => false,
147        });
148        found.or_else(|| match imported? {
149            Imported::Model(m) => Some(StoredEntry::from_model(m.clone())),
150            Imported::Adapter(a) => Some(StoredEntry::from_adapter(a.clone())),
151            Imported::Projector(p) => Some(StoredEntry::from_projector(p.clone())),
152            _ => None,
153        })
154    }
155}