Skip to main content

paper/core/models/
manager.rs

1use super::specs::{
2    all_specs, LanguageCoverage, ModelFile, ModelKind, ModelSpec, MULTILINGUAL_EMBEDDING,
3};
4use super::{Embedder, Reranker};
5use crate::core::paths::Paths;
6use crate::core::remote_config::{RemoteConfig, RemoteModel};
7use anyhow::{bail, Context, Result};
8use indicatif::{ProgressBar, ProgressStyle};
9use reqwest::Client;
10use sha2::{Digest, Sha256};
11use std::collections::HashSet;
12use std::path::{Path, PathBuf};
13use std::sync::Mutex;
14use tokio::io::AsyncWriteExt;
15
16/// Downloads, verifies and loads models. Every artifact is pinned by commit and
17/// SHA256; nothing is fetched implicitly during search.
18pub struct ModelManager {
19    cache_dir: PathBuf,
20    client: Client,
21    specs: Vec<ModelSpec>,
22    offline: bool,
23    /// Verified model IDs cached in memory so repeated `is_verified()` calls
24    /// don't re-hash multi-GB model files on every search (I1).
25    installed_cache: Mutex<HashSet<String>>,
26}
27
28impl Default for ModelManager {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl ModelManager {
35    pub fn new() -> Self {
36        Self::with_cache_dir(Paths::new().model_cache_dir())
37    }
38
39    pub fn with_cache_dir(cache_dir: PathBuf) -> Self {
40        let offline = std::env::var("PAPER_OFFLINE")
41            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
42            .unwrap_or(false);
43        Self {
44            cache_dir,
45            client: Client::new(),
46            specs: all_specs(),
47            offline,
48            installed_cache: Mutex::new(HashSet::new()),
49        }
50    }
51
52    /// Add the models a verified remote config carries (already validated by
53    /// `remote_config`, so ids never collide with built-ins).
54    pub fn with_remote(mut self, remote: Option<&RemoteConfig>) -> Self {
55        for m in remote.into_iter().flat_map(|r| &r.models) {
56            self.specs.push(remote_spec(m));
57        }
58        self
59    }
60
61    pub fn cache_dir(&self) -> &Path {
62        &self.cache_dir
63    }
64
65    pub fn specs(&self) -> &[ModelSpec] {
66        &self.specs
67    }
68
69    pub fn spec(&self, model_id: &str) -> Result<&ModelSpec> {
70        self.specs
71            .iter()
72            .find(|s| s.id == model_id)
73            .ok_or_else(|| anyhow::anyhow!("unknown model: {model_id}"))
74    }
75
76    pub fn model_dir(&self, model_id: &str) -> PathBuf {
77        self.cache_dir.join(model_id)
78    }
79
80    pub fn file_path(&self, model_id: &str, file: &str) -> PathBuf {
81        self.model_dir(model_id).join(file)
82    }
83
84    /// Load-time gate: every artifact exists, has its pinned size and is
85    /// hash-verified. The hash is computed once and recorded in a stamp next to
86    /// the file (`<file>.verified`: sha256, size, mtime); later calls trust the
87    /// stamp only while all three still match, otherwise the file is re-hashed.
88    /// An unwritable stamp just means hashing every time, never trusting blindly.
89    pub fn is_installed(&self, model_id: &str) -> bool {
90        let Ok(spec) = self.spec(model_id) else {
91            return false;
92        };
93        spec.files
94            .iter()
95            .all(|f| check_file(&self.file_path(model_id, f.name), f, false))
96    }
97
98    /// True when every artifact is present *and* matches its pinned hash.
99    /// Always hashes (stamps are ignored; `paper doctor` relies on that), but
100    /// the result is cached in memory so repeated calls don't re-hash (I1).
101    pub fn is_verified(&self, model_id: &str) -> bool {
102        if self.installed_cache.lock().unwrap().contains(model_id) {
103            return true;
104        }
105        let Ok(spec) = self.spec(model_id) else {
106            return false;
107        };
108        let verified = spec
109            .files
110            .iter()
111            .all(|f| check_file(&self.file_path(model_id, f.name), f, true));
112        if verified {
113            self.installed_cache
114                .lock()
115                .unwrap()
116                .insert(model_id.to_string());
117        }
118        verified
119    }
120
121    /// Ensure every file of `model_id` is present and verified, downloading what
122    /// is missing or corrupt. Returns the model directory.
123    pub async fn ensure(&self, model_id: &str) -> Result<PathBuf> {
124        let spec = self.spec(model_id)?.clone();
125        let dir = self.model_dir(model_id);
126        tokio::fs::create_dir_all(&dir).await?;
127
128        for file in spec.files {
129            let dest = dir.join(file.name);
130            if dest.exists() && check_file(&dest, file, true) {
131                continue;
132            }
133            if dest.exists() {
134                tracing::warn!("{} failed checksum verification; re-downloading", file.name);
135            }
136            if self.offline {
137                bail!(
138                    "{model_id}/{} is missing or corrupt and PAPER_OFFLINE is set",
139                    file.name
140                );
141            }
142            // GitHub Releases first, Hugging Face as fallback (see
143            // `ModelSpec::download_urls`). Both are SHA256-verified below.
144            let mut last_error = None;
145            for url in spec.download_urls(file.name) {
146                match self
147                    .download(&url, &dest, &format!("{model_id}/{}", file.name), file.size)
148                    .await
149                {
150                    Ok(()) => {
151                        last_error = None;
152                        break;
153                    }
154                    Err(e) => {
155                        tracing::warn!("download failed from {url}: {e:#}; trying next source");
156                        last_error = Some(e);
157                    }
158                }
159            }
160            if let Some(e) = last_error {
161                return Err(e);
162            }
163            if !check_file(&dest, file, true) {
164                let _ = tokio::fs::remove_file(&dest).await;
165                bail!(
166                    "checksum mismatch for {model_id}/{}; deleted the corrupt download",
167                    file.name
168                );
169            }
170        }
171        self.installed_cache
172            .lock()
173            .unwrap()
174            .insert(model_id.to_string());
175        Ok(dir)
176    }
177
178    async fn download(&self, url: &str, dest: &Path, label: &str, size: u64) -> Result<()> {
179        // Resume support: if a `.partial` file exists, request bytes from where
180        // we left off (I2). Hugging Face supports Range requests.
181        let tmp = dest.with_extension("partial");
182        let mut downloaded = if tmp.exists() {
183            tmp.metadata().map(|m| m.len()).unwrap_or(0)
184        } else {
185            0
186        };
187
188        let pb = ProgressBar::new(size);
189        pb.set_style(
190            ProgressStyle::with_template(
191                "{msg} [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})",
192            )
193            .unwrap_or_else(|_| ProgressStyle::default_bar())
194            .progress_chars("##-"),
195        );
196        pb.set_message(format!("Downloading {label}"));
197        pb.set_position(downloaded);
198
199        let mut builder = self.client.get(url);
200        if downloaded > 0 {
201            builder = builder.header(reqwest::header::RANGE, format!("bytes={downloaded}-"));
202        }
203        let mut resp = builder
204            .send()
205            .await
206            .with_context(|| format!("downloading {url}"))?
207            .error_for_status()
208            .with_context(|| format!("download failed for {url}"))?;
209
210        // A resumed request must be answered with 206 Partial Content. If the
211        // server ignored the Range header and sent the whole file (200), the
212        // existing `.partial` prefix is stale: start it over instead of
213        // appending a second copy and failing the checksum later.
214        if downloaded > 0 && resp.status() != reqwest::StatusCode::PARTIAL_CONTENT {
215            tracing::debug!("server ignored Range for {label}; restarting download");
216            tokio::fs::remove_file(&tmp).await?;
217            downloaded = 0;
218            pb.set_position(0);
219        }
220
221        // `.partial` first: an interrupted download is never mistaken for a model.
222        let mut file = tokio::fs::OpenOptions::new()
223            .create(true)
224            .append(true)
225            .open(&tmp)
226            .await?;
227        while let Some(chunk) = resp.chunk().await? {
228            file.write_all(&chunk).await?;
229            downloaded += chunk.len() as u64;
230            pb.set_position(downloaded);
231        }
232        file.flush().await?;
233        drop(file);
234        tokio::fs::rename(&tmp, dest).await?;
235        pb.finish_and_clear();
236        Ok(())
237    }
238
239    pub fn list(&self) -> Vec<ModelInfo> {
240        self.specs
241            .iter()
242            .map(|s| ModelInfo {
243                id: s.id.to_string(),
244                name: s.name.to_string(),
245                size_mb: s.size_mb(),
246                kind: s.kind,
247                license: s.license.to_string(),
248                languages: s.languages.to_string(),
249                installed: self.is_installed(s.id),
250                is_default: s.id == MULTILINGUAL_EMBEDDING,
251            })
252            .collect()
253    }
254
255    pub fn load_embedder(&self, model_id: &str) -> Result<Embedder> {
256        let spec = self.spec(model_id)?;
257        if spec.kind != ModelKind::Embedding {
258            bail!("{model_id} is not an embedding model");
259        }
260        if !self.is_installed(model_id) {
261            bail!("{model_id} is not installed or failed verification");
262        }
263        Embedder::new(&self.model_dir(model_id), spec)
264    }
265
266    /// Load the default embedder if (and only if) it is already on disk.
267    pub fn embedder_if_installed(&self, model_id: &str) -> Option<Embedder> {
268        match self.load_embedder(model_id) {
269            Ok(e) => Some(e),
270            Err(e) => {
271                tracing::debug!("embedder {model_id} unavailable: {e:#}");
272                None
273            }
274        }
275    }
276
277    pub fn load_reranker(&self, model_id: &str) -> Result<Reranker> {
278        let spec = self.spec(model_id)?;
279        if spec.kind != ModelKind::Reranker {
280            bail!("{model_id} is not a reranker");
281        }
282        if !self.is_installed(model_id) {
283            bail!("{model_id} is not installed or failed verification");
284        }
285        Reranker::new(&self.model_dir(model_id), spec)
286    }
287
288    pub fn reranker_if_installed(&self, model_id: &str) -> Option<Reranker> {
289        match self.load_reranker(model_id) {
290            Ok(r) => Some(r),
291            Err(e) => {
292                tracing::debug!("reranker {model_id} unavailable: {e:#}");
293                None
294            }
295        }
296    }
297
298    pub async fn remove(&self, model_id: &str) -> Result<()> {
299        self.spec(model_id)?;
300        let dir = self.model_dir(model_id);
301        if dir.exists() {
302            tokio::fs::remove_dir_all(&dir).await?;
303        }
304        Ok(())
305    }
306}
307
308fn remote_spec(m: &RemoteModel) -> ModelSpec {
309    // shortcut: leaks a few strings once per process; switch ModelSpec to owned strings if specs ever reload in-process.
310    let leak = |s: &str| -> &'static str { Box::leak(s.to_string().into_boxed_str()) };
311    let files: Vec<ModelFile> = m
312        .files
313        .iter()
314        .map(|f| ModelFile {
315            name: leak(&f.name),
316            sha256: leak(&f.sha256),
317            size: f.size,
318        })
319        .collect();
320    let embedder = m.kind == "embedder";
321    // Same query/document prefixes as the built-in model family of that org.
322    let (query_prefix, document_prefix) = match (embedder, m.repo.split('/').next()) {
323        (true, Some("intfloat")) => ("query: ", "passage: "),
324        (true, Some("BAAI")) => (
325            "Represent this sentence for searching relevant passages: ",
326            "",
327        ),
328        _ => ("", ""),
329    };
330    ModelSpec {
331        id: leak(&m.id),
332        name: leak(&format!("{} (remote)", m.id)),
333        kind: if embedder {
334            ModelKind::Embedding
335        } else {
336            ModelKind::Reranker
337        },
338        repo: leak(&m.repo),
339        revision: leak(&m.revision),
340        files: Box::leak(files.into_boxed_slice()),
341        license: "see model card",
342        languages: leak(&m.languages),
343        coverage: match m.languages.as_str() {
344            "en" => LanguageCoverage::English,
345            "en-zh" => LanguageCoverage::EnglishChinese,
346            _ => LanguageCoverage::Multilingual,
347        },
348        mirrored: false,
349        dims: m.dims.unwrap_or(0),
350        max_tokens: 512,
351        query_prefix: m.query_prefix.as_deref().map_or(query_prefix, leak),
352        document_prefix: m.document_prefix.as_deref().map_or(document_prefix, leak),
353    }
354}
355
356fn stamp_path(path: &Path) -> PathBuf {
357    let mut p = path.as_os_str().to_owned();
358    p.push(".verified");
359    PathBuf::from(p)
360}
361
362/// "sha256\nsize\nmtime_nanos\n" for the file as it is now.
363fn stamp_text(path: &Path, sha256: &str) -> Option<String> {
364    let m = std::fs::metadata(path).ok()?;
365    let nanos = m
366        .modified()
367        .ok()?
368        .duration_since(std::time::UNIX_EPOCH)
369        .ok()?
370        .as_nanos();
371    Some(format!(
372        "{}\n{}\n{nanos}\n",
373        sha256.to_ascii_lowercase(),
374        m.len()
375    ))
376}
377
378/// Size matches and the content hash is verified. `force` skips the stamp.
379fn check_file(path: &Path, f: &ModelFile, force: bool) -> bool {
380    if !std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() == f.size) {
381        return false;
382    }
383    // Fingerprint before hashing, so a change during the hash invalidates the stamp.
384    let Some(expected) = stamp_text(path, f.sha256) else {
385        return verify_sha256(path, f.sha256).unwrap_or(false);
386    };
387    let stamp = stamp_path(path);
388    if !force && std::fs::read_to_string(&stamp).is_ok_and(|s| s == expected) {
389        return true;
390    }
391    if !verify_sha256(path, f.sha256).unwrap_or(false) {
392        let _ = std::fs::remove_file(&stamp);
393        return false;
394    }
395    let _ = std::fs::write(&stamp, expected);
396    true
397}
398
399pub fn verify_sha256(path: &Path, expected: &str) -> Result<bool> {
400    let mut file = std::fs::File::open(path)?;
401    let mut hasher = Sha256::new();
402    std::io::copy(&mut file, &mut hasher)?;
403    let actual = hex::encode(hasher.finalize());
404    Ok(actual.eq_ignore_ascii_case(expected))
405}
406
407#[derive(Debug, serde::Serialize)]
408pub struct ModelInfo {
409    pub id: String,
410    pub name: String,
411    pub size_mb: u64,
412    pub kind: ModelKind,
413    pub license: String,
414    pub languages: String,
415    pub installed: bool,
416    pub is_default: bool,
417}