troupekit-local 0.4.0

On-device models for the Troupekit LLM agent framework: the LocalModel trait, model catalog and llama.cpp.
Documentation
use crate::catalog::LocalSpec;
use crate::error::LocalError;
use crate::sha256::{to_hex, Sha256};
use std::collections::BTreeMap;
use std::fs::{File, Metadata, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, PoisonError};
use std::time::SystemTime;

const PART_TRIES: usize = 64;
const HASH_CHUNK: usize = 1024 * 1024;

static VERIFIED: Mutex<BTreeMap<PathBuf, Identity>> = Mutex::new(BTreeMap::new());

const MAX_REDIRECTS: u32 = 5;
use troupekit_core::http::{HttpRequest, Transport};

/// A folder of downloaded model files, one `<id>-<sha256>.gguf` per row,
/// so a row with another digest never reuses a file. A file is used only
/// when its size and SHA-256 match, hashed once per process; `fetch`
/// checks the SHA-256 before a file gets its final name. No call
/// downloads alone.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelCache {
    dir: PathBuf,
}

impl ModelCache {
    /// Uses `dir` as the model folder; it is created on the first fetch.
    /// Mobile apps pass their own app folder here.
    /// Output: the cache.
    pub fn new(dir: impl Into<PathBuf>) -> Self {
        Self { dir: dir.into() }
    }

    /// Picks the default folder: `$TROUPEKIT_MODEL_DIR`, else
    /// `$HOME/.cache/troupekit/models`, else `%LOCALAPPDATA%\troupekit\models`.
    /// Output: the cache, or `Cache` asking for `ModelCache::new(dir)`.
    pub fn default_dir() -> Result<Self, LocalError> {
        let non_empty = |name: &str| {
            std::env::var_os(name)
                .filter(|v| !v.is_empty())
                .map(PathBuf::from)
        };
        if let Some(dir) = non_empty("TROUPEKIT_MODEL_DIR") {
            return Ok(Self::new(dir));
        }
        if let Some(home) = non_empty("HOME") {
            return Ok(Self::new(
                home.join(".cache").join("troupekit").join("models"),
            ));
        }
        if let Some(local) = non_empty("LOCALAPPDATA") {
            return Ok(Self::new(local.join("troupekit").join("models")));
        }
        Err(LocalError::Cache(
            "no model folder: set TROUPEKIT_MODEL_DIR or build the cache with ModelCache::new(dir)"
                .into(),
        ))
    }

    /// Returns the model folder.
    /// Input: none.
    /// Output: the folder path.
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Returns the file of a row when it is a regular file of exactly the
    /// declared size whose SHA-256 matches the row. The first call in a
    /// process hashes the file; later calls skip it while the file keeps
    /// its identity (device, inode, size, mtime). A partial or other file
    /// gives `None`. Never touches the network.
    pub fn path(&self, spec: &LocalSpec) -> Option<PathBuf> {
        let path = self.file_of(spec);
        let meta = std::fs::symlink_metadata(&path).ok()?;
        if !meta.is_file() || meta.len() != spec.bytes() {
            return None;
        }
        let identity = Identity::of(&meta);
        let known = VERIFIED
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(&path)
            == Some(&identity);
        if known {
            return Some(path);
        }
        let mut file = File::open(&path).ok()?;
        if Identity::of(&file.metadata().ok()?) != identity {
            return None;
        }
        if hash_file(&mut file).ok()? != spec.sha256() {
            return None;
        }
        VERIFIED
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(path.clone(), identity);
        Some(path)
    }

    /// Downloads a row through `transport` unless `path` already finds
    /// it, following up to 5 redirects that stay on https: into a part file of its own (created exclusively, 0600), refused
    /// past the declared size or on a hash mismatch, then renamed. Output: the path.
    pub async fn fetch(
        &self,
        spec: &LocalSpec,
        transport: &dyn Transport,
    ) -> Result<PathBuf, LocalError> {
        if let Some(path) = self.path(spec) {
            return Ok(path);
        }
        if !spec.url().starts_with("https://") {
            return Err(LocalError::Cache(format!(
                "model {}: refusing a non-https URL",
                spec.id()
            )));
        }
        create_private_dir(&self.dir)?;
        let (part, file) = create_part_file(&self.dir, spec.id())?;
        let mut guard = PartGuard(Some(part));
        self.download(spec, transport, file).await?;
        let path = self.file_of(spec);
        let part = guard.0.as_ref().expect("the guard holds the part path");
        std::fs::rename(part, &path)
            .map_err(|e| LocalError::Cache(format!("model {}: rename failed: {e}", spec.id())))?;
        guard.0 = None;
        if self.path(spec).is_none() {
            return Err(LocalError::Cache(format!(
                "model {}: file changed after it was published",
                spec.id()
            )));
        }
        Ok(path)
    }

    async fn download(
        &self,
        spec: &LocalSpec,
        transport: &dyn Transport,
        mut file: File,
    ) -> Result<(), LocalError> {
        let id = spec.id();
        let mut url = spec.url().to_string();
        let mut redirects = 0;
        let mut response = loop {
            let response = transport
                .send(HttpRequest::get(url.as_str()))
                .await
                .map_err(|e| LocalError::Cache(format!("model {id}: download failed: {e}")))?;
            if !matches!(response.status, 301 | 302 | 303 | 307 | 308) {
                break response;
            }
            if redirects == MAX_REDIRECTS {
                return Err(LocalError::Cache(format!(
                    "model {id}: more than {MAX_REDIRECTS} redirects"
                )));
            }
            redirects += 1;
            url = redirect_target(&url, response.header("location"))
                .map_err(|why| LocalError::Cache(format!("model {id}: {why}")))?;
        };
        assert!(url.starts_with("https://"), "every followed URL is https");
        if response.status != 200 {
            return Err(LocalError::Cache(format!(
                "model {id}: server answered {}",
                response.status
            )));
        }
        let mut hasher = Sha256::new();
        let mut total: u64 = 0;
        while let Some(chunk) = response
            .body
            .chunk()
            .await
            .map_err(|e| LocalError::Cache(format!("model {id}: download failed: {e}")))?
        {
            total = total.saturating_add(chunk.len() as u64);
            if total > spec.bytes() {
                return Err(LocalError::Cache(format!(
                    "model {id}: download is over the declared {} bytes",
                    spec.bytes()
                )));
            }
            hasher.update(&chunk);
            file.write_all(&chunk)
                .map_err(|e| LocalError::Cache(format!("model {id}: write failed: {e}")))?;
        }
        if response.truncated || total != spec.bytes() {
            return Err(LocalError::Cache(format!(
                "model {id}: got {total} bytes, expected {}",
                spec.bytes()
            )));
        }
        file.sync_all()
            .map_err(|e| LocalError::Cache(format!("model {id}: sync failed: {e}")))?;
        let got = to_hex(&hasher.finish());
        if got != spec.sha256() {
            return Err(LocalError::Cache(format!(
                "model {id}: SHA-256 {got} does not match the catalog's {}",
                spec.sha256()
            )));
        }
        Ok(())
    }

    fn file_of(&self, spec: &LocalSpec) -> PathBuf {
        assert_eq!(spec.sha256().len(), 64, "a row's digest is checked hex");
        self.dir
            .join(format!("{}-{}.gguf", spec.id(), spec.sha256()))
    }
}

/// What marks a file as the one already hashed: size, mtime and, on
/// unix, device and inode. A changed file gets another identity and is
/// hashed again.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Identity {
    len: u64,
    modified: Option<SystemTime>,
    node: (u64, u64),
}

impl Identity {
    fn of(meta: &Metadata) -> Self {
        #[cfg(unix)]
        let node = {
            use std::os::unix::fs::MetadataExt;
            (meta.dev(), meta.ino())
        };
        #[cfg(not(unix))]
        let node = (0, 0);
        Self {
            len: meta.len(),
            modified: meta.modified().ok(),
            node,
        }
    }
}

/// Hashes an open file from its current position to the end.
/// Input: the file. Output: the lowercase hex SHA-256, or the read error.
fn hash_file(file: &mut File) -> std::io::Result<String> {
    let mut hasher = Sha256::new();
    let mut buf = vec![0u8; HASH_CHUNK];
    loop {
        let n = file.read(&mut buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    let hex = to_hex(&hasher.finish());
    assert_eq!(hex.len(), 64, "a SHA-256 is 64 hex digits");
    Ok(hex)
}

/// Resolves the `Location` of a redirect from `from`: an absolute https
/// URL as is, a path starting with one `/` on the same origin. Anything
/// else, plain http included, is refused so a download never leaves https.
/// Input: the current URL and the header. Output: the next URL or why not.
fn redirect_target(from: &str, location: Option<&str>) -> Result<String, String> {
    let Some(location) = location.map(str::trim).filter(|l| !l.is_empty()) else {
        return Err("redirect without a Location".into());
    };
    if location.starts_with("https://") {
        return Ok(location.to_string());
    }
    if location.starts_with('/') && !location.starts_with("//") {
        let rest = from
            .strip_prefix("https://")
            .expect("only https URLs are fetched");
        let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
        assert!(!host.is_empty(), "an https URL names a host");
        return Ok(format!("https://{host}{location}"));
    }
    Err("refusing a redirect that leaves https".into())
}

fn create_private_dir(dir: &Path) -> Result<(), LocalError> {
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        builder.mode(0o700);
    }
    builder
        .create(dir)
        .map_err(|e| LocalError::Cache(format!("cannot create {}: {e}", dir.display())))
}

struct PartGuard(Option<PathBuf>);

impl Drop for PartGuard {
    fn drop(&mut self) {
        if let Some(part) = self.0.take() {
            let _ = std::fs::remove_file(part);
        }
    }
}

fn create_part_file(dir: &Path, id: &str) -> Result<(PathBuf, File), LocalError> {
    static NEXT: AtomicU64 = AtomicU64::new(0);
    let mut options = OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    for _ in 0..PART_TRIES {
        let n = NEXT.fetch_add(1, Ordering::Relaxed);
        let part = dir.join(format!("{id}.gguf.{}-{n}.part", std::process::id()));
        match options.open(&part) {
            Ok(file) => return Ok((part, file)),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(e) => {
                return Err(LocalError::Cache(format!(
                    "cannot create {}: {e}",
                    part.display()
                )))
            }
        }
    }
    Err(LocalError::Cache(format!(
        "model {id}: no free part file name after {PART_TRIES} tries"
    )))
}