Skip to main content

paper/core/models/
manager.rs

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