Files
nexus/crates/nexus-adapter/tests/llama_process.rs

229 lines
7.6 KiB
Rust

//! Integrationstests des llama.cpp-Adapters mit echten Prozessen.
//!
//! Statt `llama-server` läuft `tests/fake_llama_server.py`. Der Test prüft
//! Prozessstart, Bereitschaft über `/health`, Log-Erfassung, Beenden und
//! Fehlerfälle. Er prüft **nicht**, ob echte Modelle laden (das ist auf srv04
//! getrennt gemessen).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU16, AtomicU32, Ordering};
use std::time::Duration;
use nexus_adapter::{
AdapterError, Engine, Health, LlamaCppConfig, LlamaCppEngine, ProfileSpec, process_exists,
};
static PORT_BLOCK: AtomicU16 = AtomicU16::new(19300);
static DIR_COUNTER: AtomicU32 = AtomicU32::new(0);
struct Fixture {
dir: PathBuf,
config: LlamaCppConfig,
model: PathBuf,
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
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-it-{}-{n}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let model = dir.join("model-Q4_0.gguf");
std::fs::write(&model, b"gguf").unwrap();
let from = PORT_BLOCK.fetch_add(10, Ordering::SeqCst);
let config = LlamaCppConfig {
binary: Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake_llama_server.py"),
model_roots: vec![dir.clone()],
port_from: from,
port_to: from + 9,
ready_timeout_secs,
log_dir: dir.join("logs"),
env: BTreeMap::from([("FAKE_LLAMA_MODE".to_string(), mode.to_string())]),
nvidia_smi: dir.join("kein-nvidia-smi"),
..LlamaCppConfig::default()
};
Fixture { dir, config, model }
}
fn profile(f: &Fixture) -> ProfileSpec {
ProfileSpec {
start_parameters: Default::default(),
model_alias: "testmodell".to_string(),
model_path: f.model.clone(),
gpus: vec![0, 1],
context: Some(2048),
extra_args: vec![],
}
}
fn log_of(f: &Fixture, id: u64) -> String {
std::fs::read_to_string(f.dir.join(format!("logs/instance-{id}.log"))).unwrap_or_default()
}
fn pid_from_log(log: &str) -> u32 {
log.lines()
.find_map(|l| l.strip_prefix("fake-llama: 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 start_bereit_log_und_stopp() {
let f = fixture("ok", 20);
let engine = LlamaCppEngine::new(f.config.clone());
let inst = engine.start(&profile(&f)).await.expect("Start");
let pid = inst.pid.expect("PID");
assert_eq!(engine.health(&inst).await, Health::Ready);
assert_eq!(
engine.endpoint(&inst).base_url,
format!("http://127.0.0.1:{}", inst.port)
);
let log = log_of(&f, inst.id);
assert!(log.contains("--host 127.0.0.1"), "{log}");
assert!(log.contains("--alias testmodell"), "{log}");
assert!(log.contains("-c 2048"), "{log}");
assert!(log.contains("CUDA_VISIBLE_DEVICES=0,1"), "{log}");
let usage = engine.measure(&inst).await;
assert!(usage.ram_mb.is_some(), "RAM muss messbar sein");
assert_eq!(usage.vram_mb, None, "ohne nvidia-smi kein VRAM-Wert");
engine.stop(&inst, Duration::from_secs(5)).await.unwrap();
assert!(wait_until_gone(pid).await, "Prozess läuft noch");
assert_eq!(engine.health(&inst).await, Health::Gone);
engine.stop(&inst, Duration::from_secs(1)).await.unwrap();
}
#[tokio::test]
async fn von_aussen_beendeter_prozess_wird_als_gone_erkannt() {
let f = fixture("ok", 20);
let engine = LlamaCppEngine::new(f.config.clone());
let inst = engine.start(&profile(&f)).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);
// `health` holt den beendeten Prozess ab (sonst bliebe er als Zombie).
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);
assert!(wait_until_gone(pid).await);
}
#[tokio::test]
async fn absturz_beim_start_liefert_log_ende_und_exit_code() {
let f = fixture("crash", 20);
let engine = LlamaCppEngine::new(f.config.clone());
let err = engine.start(&profile(&f)).await.unwrap_err();
match err {
AdapterError::ExitedEarly { code, log_tail } => {
assert_eq!(code, Some(3));
assert!(log_tail.contains("failed to load model"), "{log_tail}");
}
other => panic!("falscher Fehler: {other}"),
}
}
#[tokio::test]
async fn nie_bereit_fuehrt_zu_zeitueberschreitung_und_beendet_den_prozess() {
let f = fixture("hang", 1);
let engine = LlamaCppEngine::new(f.config.clone());
let err = engine.start(&profile(&f)).await.unwrap_err();
assert!(
matches!(err, AdapterError::NotReady { seconds: 1, .. }),
"{err}"
);
let pid = pid_from_log(&log_of(&f, 1));
assert!(wait_until_gone(pid).await, "Prozess blieb zurück");
}
#[tokio::test]
async fn sturer_prozess_wird_nach_der_gnadenfrist_beendet() {
let f = fixture("stubborn", 20);
let engine = LlamaCppEngine::new(f.config.clone());
let inst = engine.start(&profile(&f)).await.unwrap();
let pid = inst.pid.unwrap();
let t0 = std::time::Instant::now();
engine
.stop(&inst, Duration::from_millis(400))
.await
.unwrap();
assert!(t0.elapsed() < Duration::from_secs(5));
assert!(
wait_until_gone(pid).await,
"SIGTERM wurde ignoriert, Prozess läuft noch"
);
}
#[tokio::test]
async fn fehlendes_programm_ist_spawn_fehler_und_gibt_den_port_frei() {
let mut f = fixture("ok", 5);
f.config.binary = f.dir.join("gibt-es-nicht");
f.config.port_to = f.config.port_from; // genau ein Port
let engine = LlamaCppEngine::new(f.config.clone());
for _ in 0..2 {
let err = engine.start(&profile(&f)).await.unwrap_err();
assert!(matches!(err, AdapterError::Spawn(_)), "{err}");
}
}
#[tokio::test]
async fn zwei_instanzen_bekommen_verschiedene_ports() {
let f = fixture("ok", 20);
let engine = LlamaCppEngine::new(f.config.clone());
let p = profile(&f);
let (a, b) = tokio::join!(engine.start(&p), engine.start(&p));
let (a, b) = (a.unwrap(), b.unwrap());
assert_ne!(a.port, b.port);
assert_ne!(a.id, b.id);
assert_eq!(engine.health(&a).await, Health::Ready);
assert_eq!(engine.health(&b).await, Health::Ready);
engine.stop(&a, Duration::from_secs(5)).await.unwrap();
engine.stop(&b, Duration::from_secs(5)).await.unwrap();
}
#[tokio::test]
async fn unbrauchbares_profil_wird_vor_dem_start_abgelehnt() {
let f = fixture("ok", 5);
let engine = LlamaCppEngine::new(f.config.clone());
let mut p = profile(&f);
p.model_path = f.dir.join("fehlt.gguf");
assert!(matches!(
engine.start(&p).await,
Err(AdapterError::InvalidProfile(_))
));
}
#[tokio::test]
async fn discover_findet_das_modell_im_ordner() {
let f = fixture("ok", 5);
let engine = LlamaCppEngine::new(f.config.clone());
let found = engine.discover().await.unwrap();
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].name, "model-Q4_0");
assert_eq!(found[0].quantization.as_deref(), Some("Q4_0"));
}