feat: Ollama-Adapter (Managed und Attached), Engine-Wahl in der Registry (M2.6a, gegen Attrappe)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
130
crates/nexus-adapter/tests/fake_ollama.py
Executable file
130
crates/nexus-adapter/tests/fake_ollama.py
Executable file
@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attrappe für `ollama serve`, nur für Tests von nexus-adapter und tests/sdk.
|
||||
|
||||
Aufruf wie das Original: `fake_ollama.py serve`. Liest OLLAMA_HOST (host:port).
|
||||
Verhalten nach FAKE_OLLAMA_MODE:
|
||||
ok läuft normal
|
||||
crash schreibt einen Fehler nach stderr und endet mit Exit-Code 4
|
||||
hang startet den Server nie (hört nie auf Anfragen)
|
||||
Bekannte Modelle: FAKE_OLLAMA_MODELS (Komma-getrennt, Standard "qwen3:0.6b,llama3").
|
||||
Ladezeit: FAKE_OLLAMA_LOAD_SECONDS (Standard 0.3).
|
||||
|
||||
Schnittstellen: GET /api/version, GET /api/ps, POST /api/generate (laden und
|
||||
entladen über keep_alive), POST /v1/chat/completions (OpenAI-Format, mit und
|
||||
ohne SSE). Die Antwort nennt das Modell, das tatsächlich in der Anfrage stand.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
if len(sys.argv) < 2 or sys.argv[1] != "serve":
|
||||
print("Aufruf: fake_ollama.py serve", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
mode = os.environ.get("FAKE_OLLAMA_MODE", "ok")
|
||||
host, _, port = os.environ.get("OLLAMA_HOST", "127.0.0.1:11434").rpartition(":")
|
||||
known = {m.strip() for m in os.environ.get("FAKE_OLLAMA_MODELS", "qwen3:0.6b,llama3").split(",")}
|
||||
load_seconds = float(os.environ.get("FAKE_OLLAMA_LOAD_SECONDS", "0.3"))
|
||||
|
||||
print("fake-ollama: pid", os.getpid(), flush=True)
|
||||
for name in ("OLLAMA_HOST", "OLLAMA_MODELS", "OLLAMA_KEEP_ALIVE", "OLLAMA_NOPRUNE", "CUDA_VISIBLE_DEVICES"):
|
||||
print(f"fake-ollama: {name}={os.environ.get(name, '<unset>')}", flush=True)
|
||||
|
||||
if mode == "crash":
|
||||
print("fake-ollama: error: could not bind", file=sys.stderr, flush=True)
|
||||
sys.exit(4)
|
||||
if mode == "hang":
|
||||
signal.signal(signal.SIGTERM, signal.SIG_DFL)
|
||||
while True:
|
||||
time.sleep(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, lambda *_: os._exit(0))
|
||||
loaded = {}
|
||||
lock = threading.Lock()
|
||||
ANSWER = ["Antwort", " von", " "]
|
||||
|
||||
|
||||
def normalize(tag):
|
||||
return tag if ":" in tag else tag + ":latest"
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def _json(self, code, payload):
|
||||
body = json.dumps(payload).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _body(self):
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
return json.loads(self.rfile.read(length) or b"{}")
|
||||
|
||||
def _is_known(self, model):
|
||||
return model in known or normalize(model) in {normalize(k) for k in known}
|
||||
|
||||
def _load(self, model):
|
||||
time.sleep(load_seconds)
|
||||
with lock:
|
||||
loaded[normalize(model)] = time.time()
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/api/version":
|
||||
self._json(200, {"version": "0.0.0-fake"})
|
||||
elif self.path == "/api/ps":
|
||||
with lock:
|
||||
models = [{"name": m, "model": m, "size": 600_000_000, "size_vram": 500_000_000} for m in loaded]
|
||||
self._json(200, {"models": models})
|
||||
else:
|
||||
self._json(404, {"error": "not found"})
|
||||
|
||||
def do_POST(self):
|
||||
request = self._body()
|
||||
model = request.get("model", "")
|
||||
if self.path == "/api/generate":
|
||||
if not self._is_known(model):
|
||||
self._json(404, {"error": f"model '{model}' not found"})
|
||||
elif request.get("keep_alive") == 0:
|
||||
with lock:
|
||||
loaded.pop(normalize(model), None)
|
||||
self._json(200, {"model": model, "response": "", "done": True, "done_reason": "unload"})
|
||||
else:
|
||||
self._load(model)
|
||||
self._json(200, {"model": model, "response": "", "done": True, "done_reason": "load"})
|
||||
elif self.path == "/v1/chat/completions":
|
||||
if not self._is_known(model):
|
||||
self._json(404, {"error": {"message": f"model '{model}' not found", "type": "api_error"}})
|
||||
return
|
||||
if normalize(model) not in loaded:
|
||||
self._load(model)
|
||||
parts = ANSWER + [model]
|
||||
if request.get("stream"):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.end_headers()
|
||||
for part in parts:
|
||||
chunk = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": 1, "model": model,
|
||||
"choices": [{"index": 0, "delta": {"content": part}, "finish_reason": None}]}
|
||||
self.wfile.write(("data: " + json.dumps(chunk) + "\n\n").encode())
|
||||
self.wfile.flush()
|
||||
time.sleep(0.03)
|
||||
self.wfile.write(b"data: [DONE]\n\n")
|
||||
self.wfile.flush()
|
||||
else:
|
||||
self._json(200, {"id": "chatcmpl-fake", "object": "chat.completion", "created": 1, "model": model,
|
||||
"choices": [{"index": 0, "finish_reason": "stop",
|
||||
"message": {"role": "assistant", "content": "".join(parts)}}],
|
||||
"usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7}})
|
||||
else:
|
||||
self._json(404, {"error": "not found"})
|
||||
|
||||
|
||||
ThreadingHTTPServer((host, int(port)), Handler).serve_forever()
|
||||
349
crates/nexus-adapter/tests/ollama_process.rs
Normal file
349
crates/nexus-adapter/tests/ollama_process.rs
Normal file
@ -0,0 +1,349 @@
|
||||
//! Integrationstests des Ollama-Adapters mit echten Prozessen.
|
||||
//!
|
||||
//! Statt `ollama` läuft `tests/fake_ollama.py`. Geprüft werden Serverstart,
|
||||
//! Laden und Entladen, geteilter Server, Fehlerfälle und der Modus Attached.
|
||||
//! Nicht geprüft wird, ob das echte Ollama sich genauso verhält (das ist auf
|
||||
//! srv04 getrennt gemessen).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicU16, AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use nexus_adapter::{
|
||||
AdapterError, Engine, Health, OllamaConfig, OllamaEngine, OllamaMode, ProfileSpec,
|
||||
process_exists,
|
||||
};
|
||||
|
||||
static PORT_BLOCK: AtomicU16 = AtomicU16::new(19700);
|
||||
static DIR_COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
struct Fixture {
|
||||
dir: PathBuf,
|
||||
config: OllamaConfig,
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
fn fake_binary() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake_ollama.py")
|
||||
}
|
||||
|
||||
fn fixture(mode: &str, ready_timeout_secs: u64) -> Fixture {
|
||||
let n = DIR_COUNTER.fetch_add(1, Ordering::SeqCst);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"nexus-adapter-ollama-it-{}-{n}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let from = PORT_BLOCK.fetch_add(10, Ordering::SeqCst);
|
||||
let config = OllamaConfig {
|
||||
binary: fake_binary(),
|
||||
models_dir: dir.join("modelle"),
|
||||
gpus: vec![0, 1],
|
||||
port_from: from,
|
||||
port_to: from + 9,
|
||||
ready_timeout_secs,
|
||||
log_dir: dir.join("logs"),
|
||||
env: BTreeMap::from([("FAKE_OLLAMA_MODE".to_string(), mode.to_string())]),
|
||||
..OllamaConfig::default()
|
||||
};
|
||||
Fixture { dir, config }
|
||||
}
|
||||
|
||||
fn profile(alias: &str, tag: &str) -> ProfileSpec {
|
||||
ProfileSpec {
|
||||
model_alias: alias.to_string(),
|
||||
model_path: PathBuf::from(tag),
|
||||
gpus: vec![0],
|
||||
context: None,
|
||||
extra_args: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn server_log(f: &Fixture) -> String {
|
||||
std::fs::read_to_string(f.dir.join("logs/instance-ollama.log")).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn pid_from_log(log: &str) -> u32 {
|
||||
log.lines()
|
||||
.find_map(|l| l.strip_prefix("fake-ollama: pid "))
|
||||
.and_then(|p| p.trim().parse().ok())
|
||||
.expect("PID im Log")
|
||||
}
|
||||
|
||||
async fn wait_until_gone(pid: u32) -> bool {
|
||||
for _ in 0..50 {
|
||||
if !process_exists(pid) {
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_start_endpoint_messung_und_stopp() {
|
||||
let f = fixture("ok", 20);
|
||||
let engine = OllamaEngine::new(f.config.clone());
|
||||
let inst = engine
|
||||
.start(&profile("klein", "qwen3:0.6b"))
|
||||
.await
|
||||
.expect("Start");
|
||||
let pid = inst.pid.expect("PID des Servers");
|
||||
|
||||
assert_eq!(engine.health(&inst).await, Health::Ready);
|
||||
let endpoint = engine.endpoint(&inst);
|
||||
assert_eq!(endpoint.base_url, format!("http://127.0.0.1:{}", inst.port));
|
||||
assert_eq!(endpoint.upstream_model.as_deref(), Some("qwen3:0.6b"));
|
||||
|
||||
let log = server_log(&f);
|
||||
assert!(
|
||||
log.contains(&format!("OLLAMA_HOST=127.0.0.1:{}", inst.port)),
|
||||
"{log}"
|
||||
);
|
||||
assert!(
|
||||
log.contains("OLLAMA_KEEP_ALIVE=-1") && log.contains("OLLAMA_NOPRUNE=1"),
|
||||
"{log}"
|
||||
);
|
||||
assert!(log.contains("CUDA_VISIBLE_DEVICES=0,1"), "{log}");
|
||||
assert!(log.contains("OLLAMA_MODELS="), "{log}");
|
||||
|
||||
let usage = engine.measure(&inst).await;
|
||||
assert_eq!(usage.vram_mb, Some(500_000_000 / (1024 * 1024)));
|
||||
assert_eq!(usage.ram_mb, Some(100_000_000 / (1024 * 1024)));
|
||||
|
||||
engine.stop(&inst, Duration::from_secs(5)).await.unwrap();
|
||||
assert!(
|
||||
wait_until_gone(pid).await,
|
||||
"Der Server lief nach dem letzten Modell weiter"
|
||||
);
|
||||
assert_eq!(engine.health(&inst).await, Health::Gone);
|
||||
engine.stop(&inst, Duration::from_secs(1)).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zwei_modelle_teilen_sich_einen_server_der_mit_dem_letzten_endet() {
|
||||
let f = fixture("ok", 20);
|
||||
let engine = OllamaEngine::new(f.config.clone());
|
||||
let a = engine.start(&profile("a", "qwen3:0.6b")).await.unwrap();
|
||||
let b = engine.start(&profile("b", "llama3")).await.unwrap();
|
||||
assert_eq!((a.port, a.pid), (b.port, b.pid), "ein Server für beide");
|
||||
assert_ne!(a.id, b.id);
|
||||
let pid = a.pid.unwrap();
|
||||
|
||||
engine.stop(&a, Duration::from_secs(5)).await.unwrap();
|
||||
assert!(
|
||||
process_exists(pid),
|
||||
"Der Server muss für das zweite Modell weiterlaufen"
|
||||
);
|
||||
assert_eq!(engine.health(&a).await, Health::Gone);
|
||||
assert_eq!(engine.health(&b).await, Health::Ready);
|
||||
|
||||
engine.stop(&b, Duration::from_secs(5)).await.unwrap();
|
||||
assert!(wait_until_gone(pid).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unbekanntes_modell_gibt_invalid_profile_und_hinterlaesst_keinen_server() {
|
||||
let f = fixture("ok", 20);
|
||||
let engine = OllamaEngine::new(f.config.clone());
|
||||
let err = engine
|
||||
.start(&profile("x", "gibt-es-nicht:1b"))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, AdapterError::InvalidProfile(m) if m.contains("gibt-es-nicht:1b")),
|
||||
"{err}"
|
||||
);
|
||||
let pid = pid_from_log(&server_log(&f));
|
||||
assert!(
|
||||
wait_until_gone(pid).await,
|
||||
"Der Server blieb ohne Modell zurück"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn profil_mit_nicht_erlaubter_gpu_wird_abgelehnt_ohne_serverstart() {
|
||||
let f = fixture("ok", 20);
|
||||
let engine = OllamaEngine::new(f.config.clone());
|
||||
let mut p = profile("x", "qwen3:0.6b");
|
||||
p.gpus = vec![7];
|
||||
assert!(matches!(
|
||||
engine.start(&p).await,
|
||||
Err(AdapterError::InvalidProfile(_))
|
||||
));
|
||||
assert!(
|
||||
server_log(&f).is_empty(),
|
||||
"Es darf kein Server gestartet worden sein"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn absturz_beim_start_liefert_log_ende_und_exit_code() {
|
||||
let f = fixture("crash", 20);
|
||||
let engine = OllamaEngine::new(f.config.clone());
|
||||
match engine.start(&profile("x", "qwen3:0.6b")).await.unwrap_err() {
|
||||
AdapterError::ExitedEarly { code, log_tail } => {
|
||||
assert_eq!(code, Some(4));
|
||||
assert!(log_tail.contains("could not bind"), "{log_tail}");
|
||||
}
|
||||
other => panic!("falscher Fehler: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_der_nie_bereit_wird_fuehrt_zur_zeitueberschreitung_und_wird_beendet() {
|
||||
let f = fixture("hang", 1);
|
||||
let engine = OllamaEngine::new(f.config.clone());
|
||||
let err = engine.start(&profile("x", "qwen3:0.6b")).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, AdapterError::NotReady { seconds: 1, .. }),
|
||||
"{err}"
|
||||
);
|
||||
let pid = pid_from_log(&server_log(&f));
|
||||
assert!(wait_until_gone(pid).await, "Prozess blieb zurück");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn von_aussen_beendeter_server_wird_als_gone_erkannt_und_neu_gestartet() {
|
||||
let f = fixture("ok", 20);
|
||||
let engine = OllamaEngine::new(f.config.clone());
|
||||
let inst = engine.start(&profile("a", "qwen3:0.6b")).await.unwrap();
|
||||
let pid = inst.pid.unwrap();
|
||||
// SAFETY: beendet gezielt den Prozess, den dieser Test selbst gestartet hat.
|
||||
assert_eq!(unsafe { libc::kill(pid as i32, libc::SIGKILL) }, 0);
|
||||
|
||||
let mut health = engine.health(&inst).await;
|
||||
for _ in 0..50 {
|
||||
if health == Health::Gone {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
health = engine.health(&inst).await;
|
||||
}
|
||||
assert_eq!(health, Health::Gone);
|
||||
|
||||
let neu = engine
|
||||
.start(&profile("a", "qwen3:0.6b"))
|
||||
.await
|
||||
.expect("Neustart");
|
||||
assert_ne!(neu.pid, inst.pid);
|
||||
assert_eq!(engine.health(&neu).await, Health::Ready);
|
||||
engine.stop(&neu, Duration::from_secs(5)).await.unwrap();
|
||||
}
|
||||
|
||||
/// Startet die Attrappe als eigenständigen Server (nicht vom Adapter verwaltet).
|
||||
fn external_server(port: u16) -> Child {
|
||||
let child = Command::new(fake_binary())
|
||||
.arg("serve")
|
||||
.env("OLLAMA_HOST", format!("127.0.0.1:{port}"))
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("Attrappe starten");
|
||||
for _ in 0..50 {
|
||||
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
child
|
||||
}
|
||||
|
||||
fn attached(port: u16) -> OllamaEngine {
|
||||
OllamaEngine::new(OllamaConfig {
|
||||
mode: OllamaMode::Attached,
|
||||
base_url: format!("http://127.0.0.1:{port}/"),
|
||||
ready_timeout_secs: 10,
|
||||
..OllamaConfig::default()
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attached_laedt_und_entlaedt_ohne_den_server_zu_beenden() {
|
||||
let port = PORT_BLOCK.fetch_add(10, Ordering::SeqCst);
|
||||
let mut server = external_server(port);
|
||||
let engine = attached(port);
|
||||
|
||||
let inst = engine
|
||||
.start(&profile("a", "qwen3:0.6b"))
|
||||
.await
|
||||
.expect("Start");
|
||||
assert_eq!(inst.pid, None);
|
||||
assert_eq!(engine.health(&inst).await, Health::Ready);
|
||||
assert_eq!(
|
||||
engine.endpoint(&inst).base_url,
|
||||
format!("http://127.0.0.1:{port}")
|
||||
);
|
||||
|
||||
engine.stop(&inst, Duration::from_secs(5)).await.unwrap();
|
||||
assert_eq!(engine.health(&inst).await, Health::Gone);
|
||||
assert!(
|
||||
server.try_wait().unwrap().is_none(),
|
||||
"Der externe Server muss weiterlaufen"
|
||||
);
|
||||
|
||||
// Ein neuer Start lädt das Modell wieder.
|
||||
let neu = engine.start(&profile("a", "qwen3:0.6b")).await.unwrap();
|
||||
assert_eq!(engine.health(&neu).await, Health::Ready);
|
||||
|
||||
let _ = server.kill();
|
||||
let _ = server.wait();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attached_erkennt_ein_vom_server_entladenes_modell() {
|
||||
let port = PORT_BLOCK.fetch_add(10, Ordering::SeqCst);
|
||||
let mut server = external_server(port);
|
||||
let engine = attached(port);
|
||||
let inst = engine.start(&profile("a", "qwen3:0.6b")).await.unwrap();
|
||||
|
||||
// Der Server entlädt das Modell von sich aus (eigener Leerlauf-Timeout).
|
||||
let http = reqwest::Client::new();
|
||||
http.post(format!("http://127.0.0.1:{port}/api/generate"))
|
||||
.header("content-type", "application/json")
|
||||
.body(r#"{"model":"qwen3:0.6b","keep_alive":0}"#)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(engine.health(&inst).await, Health::Gone);
|
||||
|
||||
let _ = server.kill();
|
||||
let _ = server.wait();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attached_ohne_erreichbaren_server_ist_not_ready() {
|
||||
// Ein freier Port, auf dem niemand lauscht.
|
||||
let port = {
|
||||
let l = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
l.local_addr().unwrap().port()
|
||||
};
|
||||
let err = attached(port)
|
||||
.start(&profile("a", "qwen3:0.6b"))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, AdapterError::NotReady { .. }), "{err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discover_liest_die_manifeste_des_modellordners() {
|
||||
let f = fixture("ok", 5);
|
||||
let manifest = f
|
||||
.config
|
||||
.models_dir
|
||||
.join("manifests/registry.ollama.ai/library/qwen3/0.6b");
|
||||
std::fs::create_dir_all(manifest.parent().unwrap()).unwrap();
|
||||
std::fs::write(&manifest, r#"{"config":{"size":1},"layers":[{"size":9}]}"#).unwrap();
|
||||
let engine = OllamaEngine::new(f.config.clone());
|
||||
let found = engine.discover().await.unwrap();
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].name, "qwen3:0.6b");
|
||||
assert_eq!(found[0].size_bytes, 10);
|
||||
}
|
||||
Reference in New Issue
Block a user