//! Integrationstests des Maya-Adapters mit echten Prozessen. //! //! Statt `maya.py` läuft `tests/fake_maya.py`. Der Test prüft Prozessstart, //! Konfigurationskopie, Bereitschaft über `/health`, Beenden samt //! Prozessgruppe und Fehlerfälle. Er prüft **nicht**, ob das echte Maya lädt //! (das ist auf srv04 getrennt gemessen, `docs/m2-maya-messung.md`). 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, MayaConfig, MayaEngine, ProfileSpec, process_exists, }; static PORT_BLOCK: AtomicU16 = AtomicU16::new(19700); static DIR_COUNTER: AtomicU32 = AtomicU32::new(0); struct Fixture { dir: PathBuf, config: MayaConfig, maya_config: 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-maya-it-{}-{n}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let maya_config = dir.join("maya-test.json"); std::fs::write( &maya_config, r#"{"exe":"/nicht/da/maya","args":["--glm-pack","/pack","--max-context","32768"], "cwd":"/nicht/da","api_key":"geheim","port":8083,"gpu":[0,1], "model_name":"fake-maya","installer":{"quant":"IQ1_S"}}"#, ) .unwrap(); let from = PORT_BLOCK.fetch_add(10, Ordering::SeqCst); let config = MayaConfig { python: PathBuf::from("python3"), script: Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake_maya.py"), config_roots: vec![dir.clone()], port_from: from, port_to: from + 9, ready_timeout_secs, log_dir: dir.join("logs"), env: BTreeMap::from([("FAKE_MAYA_MODE".to_string(), mode.to_string())]), nvidia_smi: dir.join("kein-nvidia-smi"), ..MayaConfig::default() }; Fixture { dir, config, maya_config, } } fn profile(f: &Fixture) -> ProfileSpec { ProfileSpec { model_alias: "glm".to_string(), model_path: f.maya_config.clone(), gpus: vec![1], context: Some(8192), extra_args: vec![], } } fn log_of(f: &Fixture, id: u64) -> String { std::fs::read_to_string(f.dir.join(format!("logs/instance-maya-{id}.log"))).unwrap_or_default() } fn number_after(log: &str, prefix: &str) -> u32 { log.lines() .find_map(|l| l.strip_prefix(prefix)) .and_then(|p| p.trim().parse().ok()) .unwrap_or_else(|| panic!("{prefix} nicht im Log:\n{log}")) } async fn wait_until_gone(pid: u32) -> bool { for _ in 0..80 { if !process_exists(pid) { return true; } tokio::time::sleep(Duration::from_millis(100)).await; } false } #[tokio::test] async fn start_bereit_konfigurationskopie_und_stopp() { let f = fixture("ok", 20); let engine = MayaEngine::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(&format!("--port {}", inst.port)), "{log}"); assert!( log.contains(&format!("config-port {}", inst.port)), "Port in der Kopie: {log}" ); assert!(log.contains("config-gpu [1]"), "{log}"); assert!(log.contains("config-api-key False"), "{log}"); assert!( log.contains("'--max-context', '8192'"), "Kontext in der Kopie: {log}" ); assert!(log.contains("maya-1"), "Arbeitsordner je Instanz: {log}"); // Die Vorlage bleibt unverändert. let original = std::fs::read_to_string(&f.maya_config).unwrap(); assert!(original.contains("geheim") && original.contains("8083")); 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 kindprozess_der_den_server_ueberlebt_wird_mit_beendet() { let f = fixture("orphan", 20); let engine = MayaEngine::new(f.config.clone()); let inst = engine.start(&profile(&f)).await.unwrap(); let engine_pid = number_after(&log_of(&f, inst.id), "fake-maya: engine pid "); assert!(process_exists(engine_pid)); engine.stop(&inst, Duration::from_secs(5)).await.unwrap(); assert!( wait_until_gone(engine_pid).await, "die Engine blieb zurück (Prozessgruppe nicht beendet)" ); } #[tokio::test] async fn dauerhaft_beschaeftigter_server_gilt_nicht_als_bereit() { // Wie beim echten Maya (Neuladen, Update): Port offen, aber nicht bereit. let f = fixture("busy", 2); let engine = MayaEngine::new(f.config.clone()); let err = engine.start(&profile(&f)).await.unwrap_err(); assert!(matches!(err, AdapterError::NotReady { .. }), "{err}"); } #[tokio::test] async fn von_aussen_beendeter_prozess_wird_als_gone_erkannt() { let f = fixture("ok", 20); let engine = MayaEngine::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); 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 = MayaEngine::new(f.config.clone()); match engine.start(&profile(&f)).await.unwrap_err() { AdapterError::ExitedEarly { code, log_tail } => { assert_eq!(code, Some(3)); assert!(log_tail.contains("engine did not start"), "{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 = MayaEngine::new(f.config.clone()); let err = engine.start(&profile(&f)).await.unwrap_err(); assert!( matches!(err, AdapterError::NotReady { seconds: 1, .. }), "{err}" ); let pid = number_after(&log_of(&f, 1), "fake-maya: pid "); 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 = MayaEngine::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 ignoriert, 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.python = f.dir.join("gibt-es-nicht"); f.config.port_to = f.config.port_from; // genau ein Port let engine = MayaEngine::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 unbrauchbares_profil_wird_vor_dem_start_abgelehnt() { let f = fixture("ok", 5); let engine = MayaEngine::new(f.config.clone()); let mut p = profile(&f); p.model_path = f.dir.join("fehlt.json"); assert!(matches!( engine.start(&p).await, Err(AdapterError::InvalidProfile(_)) )); let mut p = profile(&f); std::fs::write(&p.model_path, "kein json").unwrap(); assert!(matches!( engine.start(&p).await, Err(AdapterError::InvalidProfile(_)) )); p.gpus.clear(); assert!(matches!( engine.start(&p).await, Err(AdapterError::InvalidProfile(_)) )); } #[tokio::test] async fn discover_findet_die_konfiguration() { let f = fixture("ok", 5); std::fs::write(f.dir.join("anderes.json"), r#"{"x":1}"#).unwrap(); let engine = MayaEngine::new(f.config.clone()); let found = engine.discover().await.unwrap(); assert_eq!(found.len(), 1, "{found:?}"); assert_eq!(found[0].name, "fake-maya"); assert_eq!(found[0].quantization.as_deref(), Some("IQ1_S")); assert_eq!(found[0].path, f.maya_config); } #[tokio::test] async fn discover_zaehlt_den_modellordner_ueber_dem_pack() { let f = fixture("ok", 5); let modell = f.dir.join("modell"); std::fs::create_dir_all(modell.join("pack")).unwrap(); std::fs::write(modell.join("pack/dense.bin"), vec![0u8; 100]).unwrap(); std::fs::write(modell.join("experten-00001-of-00002.gguf"), vec![0u8; 1000]).unwrap(); std::fs::write( f.dir.join("maya-test.json"), format!( r#"{{"exe":"/x","args":["--glm-pack","{}"],"model_name":"fake-maya"}}"#, modell.join("pack").display() ), ) .unwrap(); let found = MayaEngine::new(f.config.clone()).discover().await.unwrap(); assert_eq!(found[0].size_bytes, 1100); }