capri-models: add manage module
This commit is contained in:
1 file changed
+475
@@ -0,0 +1,475 @@
|
||||
//! Local model lifecycle on the owned Ollama (Capri `providers/native-model.mjs`,
|
||||
//! `embedding-model.mjs`, `pull-model.mjs`, `model-residency.mjs`).
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use capri_core::Settings;
|
||||
use capri_llm::{LlmError, ModelEntry, Ollama, RouterSection, RunningModel};
|
||||
use regex::Regex;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::catalog::{EMBEDDING_ALIAS, EMBEDDING_BASE};
|
||||
|
||||
/// Capri generation parameters baked into the native alias and sent with every local request.
|
||||
pub fn generation_params(settings: &Settings) -> Value {
|
||||
// f32 → 3 decimals so 0.85 is stored as 0.85, not 0.8500000238418579.
|
||||
let mut params = json!({"temperature": (settings.temperature as f64 * 1000.0).round() / 1000.0, "repeat_last_n": settings.repeat_last_n});
|
||||
if settings.acceleration == "cpu" {
|
||||
params["num_gpu"] = json!(0);
|
||||
}
|
||||
if let Some(threads) = settings.cpu_threads {
|
||||
let available = std::thread::available_parallelism().map_or(1, |n| n.get() as u32);
|
||||
params["num_thread"] = json!(threads.min(available));
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// `<ns>/<base>` path segments and tag of a model name (`library` namespace by default).
|
||||
fn name_parts(name: &str) -> Result<(Vec<&str>, &str)> {
|
||||
let valid = Regex::new(r"^[a-z0-9][a-z0-9._-]*(?:/[a-z0-9][a-z0-9._-]*)?(?::[a-zA-Z0-9._-]+)?$").expect("valid regex");
|
||||
if !valid.is_match(name) {
|
||||
bail!("Invalid local model name");
|
||||
}
|
||||
let (base, tag) = name.split_once(':').unwrap_or((name, "latest"));
|
||||
let segments = if base.contains('/') { base.split('/').collect() } else { vec!["library", base] };
|
||||
Ok((segments, tag))
|
||||
}
|
||||
|
||||
fn read_small(path: &Path) -> Result<Vec<u8>> {
|
||||
capri_core::fsutil::read_regular(path, 1 << 20)?.with_context(|| format!("{} is missing", path.display()))
|
||||
}
|
||||
|
||||
fn blob_path(store: &Path, digest: &str) -> Result<PathBuf> {
|
||||
let hex = digest.strip_prefix("sha256:").filter(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()));
|
||||
Ok(store.join("blobs").join(format!("sha256-{}", hex.context("Invalid upstream model manifest")?)))
|
||||
}
|
||||
|
||||
/// Reads a model manifest from Ollama's store: the legacy registry path first, then the
|
||||
/// 0.40 `manifests-v2` layout, resolving a manifest list to its `llamacpp`/`gguf` entry.
|
||||
pub fn read_manifest(store: &Path, name: &str) -> Result<Value> {
|
||||
let (segments, tag) = name_parts(name)?;
|
||||
let legacy = segments.iter().fold(store.join("manifests/registry.ollama.ai"), |p, s| p.join(s)).join(tag);
|
||||
let v2 = segments.iter().fold(store.join("manifests-v2/ollama.com"), |p, s| p.join(s)).join(tag);
|
||||
let path = if legacy.is_file() { legacy } else { v2 };
|
||||
let manifest: Value = serde_json::from_slice(&read_small(&path)?)?;
|
||||
if manifest["mediaType"] != "application/vnd.ollama.manifest.list.v2+json" {
|
||||
return Ok(manifest);
|
||||
}
|
||||
let entry = manifest["manifests"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|m| m["runner"] == "llamacpp" && m["format"] == "gguf")
|
||||
.context("No GGUF build in the model manifest list")?;
|
||||
Ok(serde_json::from_slice(&read_small(&blob_path(store, entry["digest"].as_str().unwrap_or(""))?)?)?)
|
||||
}
|
||||
|
||||
/// Alias definition reusing the upstream GGUF weights and projector with Capri's parameters.
|
||||
pub fn native_definition(manifest: &Value, store: &Path, params: &Value) -> Result<Value> {
|
||||
let layers = manifest["layers"].as_array().filter(|l| l.len() <= 32).context("Invalid upstream model manifest")?;
|
||||
let digest_ok = Regex::new("^sha256:[a-f0-9]{64}$").expect("valid regex");
|
||||
if layers.iter().any(|l| !l["digest"].as_str().is_some_and(|d| digest_ok.is_match(d))) {
|
||||
bail!("Invalid upstream model manifest");
|
||||
}
|
||||
let of = |kind: &str| layers.iter().filter(|l| l["mediaType"] == kind).collect::<Vec<_>>();
|
||||
let (weights, projectors) = (of("application/vnd.ollama.image.model"), of("application/vnd.ollama.image.projector"));
|
||||
if weights.len() != 1 || projectors.len() > 1 {
|
||||
bail!("Expected one language GGUF and at most one vision projector");
|
||||
}
|
||||
let mut files = json!({"model.gguf": weights[0]["digest"]});
|
||||
if let Some(p) = projectors.first() {
|
||||
files["mmproj.gguf"] = p["digest"].clone();
|
||||
}
|
||||
let blob = |layer: &&Value| -> Result<String> { Ok(String::from_utf8(read_small(&blob_path(store, layer["digest"].as_str().unwrap_or(""))?)?)?) };
|
||||
let mut parameters = match of("application/vnd.ollama.image.params").first() {
|
||||
Some(layer) => serde_json::from_str(&blob(layer)?)?,
|
||||
None => json!({}),
|
||||
};
|
||||
for (k, v) in params.as_object().into_iter().flatten() {
|
||||
parameters[k] = v.clone();
|
||||
}
|
||||
let mut definition = json!({"files": files, "parameters": parameters});
|
||||
if let Some(license) = of("application/vnd.ollama.image.license").first() {
|
||||
definition["license"] = json!(blob(license)?);
|
||||
}
|
||||
Ok(definition)
|
||||
}
|
||||
|
||||
/// Creates or refreshes `settings.model` (e.g. `capri-qwen3.5:4b`) from `settings.upstream_model`
|
||||
/// with the GGUF's own chat template. `store` is the Ollama model directory Capri owns.
|
||||
pub async fn ensure_native_alias(client: &Ollama, settings: &Settings, store: &Path) -> Result<()> {
|
||||
let (alias, upstream) = (&settings.model, &settings.upstream_model);
|
||||
if upstream.is_empty() || upstream == alias {
|
||||
return Ok(());
|
||||
}
|
||||
let manifest = read_manifest(store, upstream).map_err(|_| anyhow!("Download {upstream} in Settings → Language model first."))?;
|
||||
let params = generation_params(settings);
|
||||
let definition = native_definition(&manifest, store, ¶ms)?;
|
||||
let mut existing = client.show_info(alias).await?;
|
||||
let same = existing.as_ref().is_some_and(|e| e["template_source"] == "gguf_chat_template")
|
||||
&& read_manifest(store, alias).and_then(|m| native_definition(&m, store, ¶ms)).is_ok_and(|own| own == definition);
|
||||
if !same {
|
||||
let mut body = definition.clone();
|
||||
body["model"] = json!(alias);
|
||||
client.create(body).await?;
|
||||
existing = client.show_info(alias).await?;
|
||||
}
|
||||
let existing = existing.unwrap_or_default();
|
||||
let caps: Vec<&str> = existing["capabilities"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
if existing["template_source"] != "gguf_chat_template" || !caps.contains(&"tools") || !caps.contains(&"thinking") {
|
||||
bail!("The local Qwen alias must use its native chat template with thinking and tools.");
|
||||
}
|
||||
if definition["files"].get("mmproj.gguf").is_some() && !caps.contains(&"vision") {
|
||||
bail!("Native Qwen lost its upstream vision projector");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `x` and `x:latest` are the same model.
|
||||
pub fn tagged(name: &str) -> String {
|
||||
if name.rsplit('/').next().is_some_and(|last| last.contains(':')) { name.to_string() } else { format!("{name}:latest") }
|
||||
}
|
||||
|
||||
pub fn installed(inventory: &[ModelEntry], name: &str) -> bool {
|
||||
let want = tagged(name);
|
||||
inventory.iter().any(|m| tagged(&m.name) == want || tagged(&m.model) == want)
|
||||
}
|
||||
|
||||
/// Creates a CPU-only alias `alias` from `base` when missing (`num_gpu 0`, never downloads).
|
||||
async fn ensure_cpu_alias(client: &Ollama, alias: &str, base: &str, missing: impl Fn() -> String) -> Result<()> {
|
||||
if installed(&client.tags().await?, alias) {
|
||||
return Ok(());
|
||||
}
|
||||
if !installed(&client.tags().await?, base) {
|
||||
bail!(missing());
|
||||
}
|
||||
client.create(json!({"model": alias, "from": base, "parameters": {"num_gpu": 0}})).await.map_err(|_| anyhow!(missing()))?;
|
||||
if !installed(&client.tags().await?, alias) {
|
||||
bail!(missing());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Memory embedding alias `capri-embed:latest` from a downloaded `bge-m3:latest`.
|
||||
pub async fn ensure_embedding_alias(client: &Ollama, model: &str) -> Result<()> {
|
||||
let missing = || format!("Memory model {model} is missing. Download it in Settings → Language model.");
|
||||
if model != EMBEDDING_ALIAS {
|
||||
return if installed(&client.tags().await?, model) { Ok(()) } else { Err(anyhow!(missing())) };
|
||||
}
|
||||
ensure_cpu_alias(client, EMBEDDING_ALIAS, EMBEDDING_BASE, missing).await
|
||||
}
|
||||
|
||||
/// Router alias (`capri-router:latest` from `all-minilm:l6-v2`, CPU only).
|
||||
pub async fn ensure_router_alias(client: &Ollama, router: &RouterSection) -> Result<()> {
|
||||
ensure_cpu_alias(client, &router.model, &router.base_model, || format!("Request router model {} is missing.", router.base_model)).await
|
||||
}
|
||||
|
||||
const NETWORK_CODES: &[&str] = &["ECONNRESET", "ETIMEDOUT", "EAI_AGAIN", "ENOTFOUND", "UND_ERR_SOCKET", "UND_ERR_CONNECT_TIMEOUT", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH"];
|
||||
|
||||
/// Transient pull failures worth retrying (regex kept verbatim from Capri, Windows socket errors included).
|
||||
pub fn is_transient(error: &LlmError) -> bool {
|
||||
let transient = Regex::new(r"(?i)(?:lookup\s+\S+[^\n]*(?:i/o timeout|no such host)|connection reset|unexpected EOF|TLS handshake timeout|temporary failure in name resolution|(?:dial|read|write) tcp[^\n]*(?:connectex|wsarecv|wsasend|i/o timeout|connection timed out|network is unreachable)|tls handshake eof)").expect("valid regex");
|
||||
match error {
|
||||
LlmError::Network { code } => NETWORK_CODES.contains(code),
|
||||
LlmError::Http { status, .. } => matches!(status, 408 | 429 | 500 | 502 | 503 | 504),
|
||||
LlmError::Reported(message) => transient.is_match(message),
|
||||
LlmError::StreamIncomplete => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces URLs by origin + path (signed CDN queries never reach logs or the UI), ≤ 1800 chars.
|
||||
pub fn sanitize_pull_message(message: &str) -> String {
|
||||
let url = Regex::new(r#"https?://[^\s"'<>]+"#).expect("valid regex");
|
||||
let out = url.replace_all(message, |c: ®ex::Captures<'_>| match url::Url::parse(&c[0]) {
|
||||
Ok(u) => format!("{}{}{}", u.origin().ascii_serialization(), u.path(), if u.query().is_some() { "?[redacted]" } else { "" }),
|
||||
Err(_) => "[download URL]".into(),
|
||||
});
|
||||
out.chars().take(1800).collect()
|
||||
}
|
||||
|
||||
/// Registry pull with progress `(status, completed, total)` and up to 3 retries with
|
||||
/// exponential backoff (`backoff`, 2·backoff, 4·backoff). Ollama keeps verified layers between attempts.
|
||||
// TODO: no registry TLS recovery and no Ollama restart on connection loss yet; the owner retries,
|
||||
// and partial layers are kept.
|
||||
pub async fn pull_with_retry(client: &Ollama, model: &str, mut progress: impl FnMut(&str, u64, u64), backoff: Duration) -> Result<()> {
|
||||
let mut attempt = 0u32;
|
||||
loop {
|
||||
let error = match client.pull(model, &mut progress).await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
let message = sanitize_pull_message(&error.to_string());
|
||||
if !is_transient(&error) {
|
||||
bail!(message);
|
||||
}
|
||||
if attempt == 3 {
|
||||
if let LlmError::Network { code } = error {
|
||||
bail!("The local model download connection failed ({code}). Downloaded layers are retained. Retry the download if it continues.");
|
||||
}
|
||||
bail!(message);
|
||||
}
|
||||
let wait = backoff * 2u32.pow(attempt);
|
||||
progress(&format!("Model download connection interrupted: {message}. Retrying {}/4 in {}s; Ollama retains verified layers and partial downloads.", attempt + 2, wait.as_secs()), 0, 0);
|
||||
tokio::time::sleep(wait).await;
|
||||
attempt += 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn pull_model(client: &Ollama, model: &str, progress: impl FnMut(&str, u64, u64)) -> Result<()> {
|
||||
pull_with_retry(client, model, progress, Duration::from_secs(2)).await
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Residency {
|
||||
Unknown,
|
||||
Unloaded,
|
||||
Cpu,
|
||||
Gpu,
|
||||
Partial,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ResidencyInfo {
|
||||
pub status: Residency,
|
||||
pub total_bytes: u64,
|
||||
pub gpu_bytes: u64,
|
||||
pub context_tokens: u64,
|
||||
}
|
||||
|
||||
/// Where a model runs, from `/api/ps`: placement CPU / GPU / partial offload.
|
||||
pub fn residency_of(running: &[RunningModel], model: &str) -> ResidencyInfo {
|
||||
let want = tagged(model);
|
||||
let unknown = ResidencyInfo { status: Residency::Unknown, total_bytes: 0, gpu_bytes: 0, context_tokens: 0 };
|
||||
let matches: Vec<_> = running.iter().filter(|m| tagged(&m.name) == want || tagged(&m.model) == want).collect();
|
||||
match matches.as_slice() {
|
||||
[] if running.len() <= 32 => ResidencyInfo { status: Residency::Unloaded, ..unknown },
|
||||
[m] if m.size > 0 && m.size_vram <= m.size => ResidencyInfo {
|
||||
status: if m.size_vram == 0 { Residency::Cpu } else if m.size_vram == m.size { Residency::Gpu } else { Residency::Partial },
|
||||
total_bytes: m.size,
|
||||
gpu_bytes: m.size_vram,
|
||||
context_tokens: m.context_length,
|
||||
},
|
||||
_ => unknown,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn residency(client: &Ollama, model: &str) -> ResidencyInfo {
|
||||
match client.ps().await {
|
||||
Ok(running) => residency_of(&running, model),
|
||||
Err(_) => ResidencyInfo { status: Residency::Unknown, total_bytes: 0, gpu_bytes: 0, context_tokens: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
/// Body shared by every local chat-model request so Ollama never reloads the runner.
|
||||
pub fn runner_options(settings: &Settings) -> Value {
|
||||
let mut options = json!({"num_ctx": settings.context_tokens});
|
||||
if settings.acceleration == "cpu" {
|
||||
options["num_gpu"] = json!(0);
|
||||
}
|
||||
if let Some(threads) = settings.cpu_threads {
|
||||
options["num_thread"] = json!(threads);
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
/// Makes the chat model resident with the conversation's runner options, without replacing a
|
||||
/// live KV cache. Returns `true` when it was cold.
|
||||
pub async fn prepare_language_model(client: &Ollama, settings: &Settings, think_capable: bool) -> Result<bool, LlmError> {
|
||||
let ready = |running: &[RunningModel]| {
|
||||
running.iter().any(|m| {
|
||||
tagged(&m.name) == tagged(&settings.model) && m.context_length == settings.context_tokens as u64 && (settings.acceleration != "cpu" || m.size_vram == 0)
|
||||
})
|
||||
};
|
||||
if client.ps().await.is_ok_and(|r| ready(&r)) {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut options = runner_options(settings);
|
||||
options["num_predict"] = json!(1);
|
||||
let mut body = json!({
|
||||
"model": settings.model, "messages": [{"role": "user", "content": "Hello."}], "stream": false,
|
||||
"truncate": false, "shift": false, "keep_alive": settings.keep_alive, "options": options,
|
||||
});
|
||||
if think_capable {
|
||||
body["think"] = json!(false);
|
||||
}
|
||||
client.raw_chat(&body, Duration::from_secs(180)).await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// API mode startup: unloads exactly the configured chat model if resident.
|
||||
pub async fn release_language_model(client: &Ollama, model: &str) -> Result<()> {
|
||||
let running = client.ps().await.unwrap_or_default();
|
||||
if running.iter().any(|m| m.name == model) {
|
||||
client.unload(model).await.map_err(|_| anyhow!("The idle local language model could not be unloaded."))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes a local model; refuses the active or a resident model (models are only removed on request).
|
||||
pub async fn delete_model(client: &Ollama, settings: &Settings, name: &str) -> Result<()> {
|
||||
if [&settings.model, &settings.upstream_model].iter().any(|m| tagged(m) == tagged(name)) {
|
||||
bail!("Switch to another model before removing the active model.");
|
||||
}
|
||||
if client.ps().await.unwrap_or_default().iter().any(|m| tagged(&m.name) == tagged(name)) {
|
||||
bail!("Unload this model before removing it.");
|
||||
}
|
||||
client.delete(name).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wiremock::matchers::{body_partial_json, method, path};
|
||||
use wiremock::{Mock, MockServer, Request, ResponseTemplate};
|
||||
|
||||
const D1: &str = "sha256:a9d0a3e1d8c91732a3812becd31f8d4a8ff57414903f226306069f0437e2ac50";
|
||||
const D2: &str = "sha256:e56a899b1540860385465756dd308c84417410b94dbc1c380adffd20a921ca60";
|
||||
const DP: &str = "sha256:9371364b27a52acac9d87f88bd93c9db1174d8d6ec57f6888925cdc1788871ff";
|
||||
const DL: &str = "sha256:50cbab8a892c5f2993b8c7351a99182507472def3b1374558308605d99b86b32";
|
||||
const DM: &str = "sha256:d8b0f5e9760cd1682034f292d7ef72ec46f432149be0df7574bf2d6e92e38c04";
|
||||
|
||||
fn write(path: PathBuf, text: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn manifest() -> Value {
|
||||
json!({"layers": [
|
||||
{"mediaType": "application/vnd.ollama.image.projector", "digest": D2},
|
||||
{"mediaType": "application/vnd.ollama.image.model", "digest": D1},
|
||||
{"mediaType": "application/vnd.ollama.image.license", "digest": DL},
|
||||
{"mediaType": "application/vnd.ollama.image.params", "digest": DP},
|
||||
{"mediaType": "application/vnd.ollama.manifest.list.v2+json", "digest": DM},
|
||||
]})
|
||||
}
|
||||
|
||||
/// Ollama 0.40 store: upstream only as a v2 manifest list, the GGUF manifest in a blob.
|
||||
fn store() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let blob = |d: &str| dir.path().join("blobs").join(d.replace(':', "-"));
|
||||
write(blob(DP), r#"{"top_k":20,"temperature":1}"#);
|
||||
write(blob(DL), "Apache-2.0");
|
||||
write(blob(DM), &manifest().to_string());
|
||||
write(dir.path().join("manifests-v2/ollama.com/library/qwen3.5/4b"), &json!({"mediaType": "application/vnd.ollama.manifest.list.v2+json", "manifests": [
|
||||
{"digest": "sha256:7f3251fa6878a78a606bcb3c074283306e5ad2ea411a7774a9dd98a4bc7f2d13", "runner": "mlx", "format": "safetensors"},
|
||||
{"digest": DM, "runner": "llamacpp", "format": "gguf"}]}).to_string());
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_definition_from_v2_store() {
|
||||
let dir = store();
|
||||
let m = read_manifest(dir.path(), "qwen3.5:4b").unwrap();
|
||||
let def = native_definition(&m, dir.path(), &generation_params(&Settings::default())).unwrap();
|
||||
assert_eq!(def["files"], json!({"model.gguf": D1, "mmproj.gguf": D2}));
|
||||
assert_eq!(def["parameters"], json!({"top_k": 20, "temperature": 0.85, "repeat_last_n": 512}));
|
||||
assert_eq!(def["license"], "Apache-2.0");
|
||||
let mut two = manifest();
|
||||
two["layers"][1]["mediaType"] = json!("application/vnd.ollama.image.projector");
|
||||
assert!(native_definition(&two, dir.path(), &json!({})).is_err());
|
||||
let mut bad = manifest();
|
||||
bad["layers"][0]["digest"] = json!("sha256:XYZ");
|
||||
assert_eq!(native_definition(&bad, dir.path(), &json!({})).unwrap_err().to_string(), "Invalid upstream model manifest");
|
||||
assert!(name_parts("../etc").is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn creates_alias_and_checks_capabilities() {
|
||||
let dir = store();
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST")).and(path("/api/create")).respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"success"}"#)).mount(&server).await;
|
||||
Mock::given(method("POST")).and(path("/api/show")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"template_source": "gguf_chat_template", "capabilities": ["completion", "tools", "thinking", "vision"]}))).mount(&server).await;
|
||||
let client = Ollama::new(server.uri());
|
||||
ensure_native_alias(&client, &Settings::default(), dir.path()).await.unwrap();
|
||||
let create = server.received_requests().await.unwrap().into_iter().find(|r| r.url.path() == "/api/create").unwrap();
|
||||
let body: Value = serde_json::from_slice(&create.body).unwrap();
|
||||
assert_eq!((body["model"].as_str(), body["stream"].as_bool()), (Some("capri-qwen3.5:4b"), Some(false)));
|
||||
assert_eq!(body["files"]["mmproj.gguf"], D2);
|
||||
|
||||
let settings = Settings { upstream_model: "qwen3.5:9b".into(), ..Default::default() };
|
||||
assert_eq!(ensure_native_alias(&client, &settings, dir.path()).await.unwrap_err().to_string(), "Download qwen3.5:9b in Settings → Language model first.");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn embedding_alias_only_from_cached_base() {
|
||||
let server = MockServer::start().await;
|
||||
let created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let flag = created.clone();
|
||||
Mock::given(method("GET")).and(path("/api/tags")).respond_with(move |_: &Request| {
|
||||
let mut models = vec![json!({"name": "bge-m3:latest"})];
|
||||
if flag.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
models.push(json!({"name": "capri-embed:latest"}));
|
||||
}
|
||||
ResponseTemplate::new(200).set_body_json(json!({"models": models}))
|
||||
}).mount(&server).await;
|
||||
let flag = created.clone();
|
||||
Mock::given(method("POST")).and(path("/api/create")).and(body_partial_json(json!({"from": "bge-m3:latest", "parameters": {"num_gpu": 0}})))
|
||||
.respond_with(move |_: &Request| { flag.store(true, std::sync::atomic::Ordering::SeqCst); ResponseTemplate::new(200).set_body_string("{}") }).mount(&server).await;
|
||||
let client = Ollama::new(server.uri());
|
||||
ensure_embedding_alias(&client, EMBEDDING_ALIAS).await.unwrap();
|
||||
assert!(created.load(std::sync::atomic::Ordering::SeqCst));
|
||||
assert!(ensure_embedding_alias(&client, "custom-embed").await.unwrap_err().to_string().starts_with("Memory model custom-embed is missing."));
|
||||
assert!(ensure_router_alias(&client, &RouterSection::default()).await.is_err(), "never downloads");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pull_retries_transient_failures_only() {
|
||||
let server = MockServer::start().await;
|
||||
let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let n = calls.clone();
|
||||
Mock::given(method("POST")).and(path("/api/pull")).respond_with(move |r: &Request| {
|
||||
let model: Value = serde_json::from_slice(&r.body).unwrap();
|
||||
if model["model"] == "missing" {
|
||||
return ResponseTemplate::new(200).set_body_string("{\"error\":\"pull model manifest: file does not exist\"}\n");
|
||||
}
|
||||
if n.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {
|
||||
ResponseTemplate::new(200).set_body_string("{\"error\":\"read tcp 1.2.3.4: connection reset by peer https://cdn.example/x?sig=SECRET\"}\n")
|
||||
} else {
|
||||
ResponseTemplate::new(200).set_body_string("{\"status\":\"pulling a\",\"total\":10,\"completed\":5}\n{\"status\":\"success\"}\n")
|
||||
}
|
||||
}).mount(&server).await;
|
||||
let client = Ollama::new(server.uri());
|
||||
let mut lines = vec![];
|
||||
pull_with_retry(&client, "qwen3.5:4b", |s, c, t| lines.push((s.to_string(), c, t)), Duration::from_millis(1)).await.unwrap();
|
||||
assert!(lines[0].0.starts_with("Model download connection interrupted: Model reported an error: read tcp"));
|
||||
assert!(lines[0].0.contains("https://cdn.example/x?[redacted]") && !lines[0].0.contains("SECRET"));
|
||||
assert_eq!(lines[1], ("pulling a".into(), 5, 10));
|
||||
let err = pull_with_retry(&client, "missing", |_, _, _| {}, Duration::from_millis(1)).await.unwrap_err();
|
||||
assert!(err.to_string().contains("file does not exist"));
|
||||
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2, "permanent errors are not retried");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn residency_rules() {
|
||||
let row = |name: &str, size, vram| RunningModel { name: name.into(), size, size_vram: vram, context_length: 32768, ..Default::default() };
|
||||
assert_eq!(residency_of(&[row("capri-qwen3.5:4b", 10, 10)], "capri-qwen3.5:4b").status, Residency::Gpu);
|
||||
assert_eq!(residency_of(&[row("capri-qwen3.5:4b", 10, 4)], "capri-qwen3.5:4b").status, Residency::Partial);
|
||||
assert_eq!(residency_of(&[row("capri-embed:latest", 10, 0)], "capri-embed").status, Residency::Cpu);
|
||||
assert_eq!(residency_of(&[row("other:latest", 10, 0)], "capri-embed").status, Residency::Unloaded);
|
||||
assert_eq!(residency_of(&[row("m:latest", 10, 11)], "m").status, Residency::Unknown);
|
||||
assert!(installed(&[ModelEntry { name: "bge-m3:latest".into(), ..Default::default() }], "bge-m3"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn readiness_and_release() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET")).and(path("/api/ps")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"models": [{"name": "capri-qwen3.5:4b", "size": 10, "size_vram": 10, "context_length": 32768}]}))).mount(&server).await;
|
||||
Mock::given(method("POST")).and(path("/api/chat")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"done": true}))).mount(&server).await;
|
||||
Mock::given(method("POST")).and(path("/api/generate")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"done": true}))).mount(&server).await;
|
||||
let client = Ollama::new(server.uri());
|
||||
assert!(!prepare_language_model(&client, &Settings::default(), true).await.unwrap(), "resident with the same context");
|
||||
let cpu = Settings { acceleration: "cpu".into(), ..Default::default() };
|
||||
assert!(prepare_language_model(&client, &cpu, true).await.unwrap(), "GPU-resident model is reloaded for CPU mode");
|
||||
let warm: Value = serde_json::from_slice(&server.received_requests().await.unwrap().into_iter().find(|r| r.url.path() == "/api/chat").unwrap().body).unwrap();
|
||||
assert_eq!(warm["options"], json!({"num_ctx": 32768, "num_gpu": 0, "num_predict": 1}));
|
||||
assert_eq!((warm["think"].as_bool(), warm["shift"].as_bool()), (Some(false), Some(false)));
|
||||
release_language_model(&client, "capri-qwen3.5:4b").await.unwrap();
|
||||
release_language_model(&client, "capri-embed:latest").await.unwrap();
|
||||
let unloads = server.received_requests().await.unwrap().into_iter().filter(|r| r.url.path() == "/api/generate").count();
|
||||
assert_eq!(unloads, 1, "only the exact chat model is released");
|
||||
assert!(delete_model(&client, &Settings::default(), "capri-qwen3.5:4b").await.is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user