feat: Maya-Adapter (Managed, gegen Attrappe), Engine-Wahl maya in Registry und CLI (M2.6b)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
118
crates/nexus-adapter/tests/fake_maya.py
Executable file
118
crates/nexus-adapter/tests/fake_maya.py
Executable file
@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attrappe für `maya.py`, nur für Tests von nexus-adapter.
|
||||
|
||||
Versteht `--config <json> --host H --port P` wie Maya und verhält sich nach
|
||||
FAKE_MAYA_MODE (wie das echte Maya öffnet sie den Port erst, wenn das Modell
|
||||
"geladen" ist):
|
||||
ok öffnet den Port nach FAKE_MAYA_LOAD_SECONDS; /health liefert status ok
|
||||
crash schreibt einen Fehler nach stderr, Exit-Code 3
|
||||
hang öffnet den Port nie
|
||||
stubborn wie ok, ignoriert aber SIGTERM
|
||||
orphan wie ok; startet einen Kindprozess ("Engine") und lässt ihn bei
|
||||
SIGTERM zurück, wie es Ollamas Runner taten
|
||||
busy Port offen, aber /health meldet status reloading
|
||||
Außerdem /v1/models und /v1/chat/completions (mit und ohne SSE, mit
|
||||
reasoning_content und Keep-alive-Zeile wie Maya).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
args = sys.argv[1:]
|
||||
|
||||
|
||||
def opt(name):
|
||||
return args[args.index(name) + 1] if name in args else None
|
||||
|
||||
|
||||
mode = os.environ.get("FAKE_MAYA_MODE", "ok")
|
||||
config = json.load(open(opt("--config")))
|
||||
print("fake-maya: pid", os.getpid(), flush=True)
|
||||
print("fake-maya: cwd", os.getcwd(), flush=True)
|
||||
print("fake-maya: args", " ".join(args), flush=True)
|
||||
print("fake-maya: config-port", config.get("port"), flush=True)
|
||||
print("fake-maya: config-gpu", json.dumps(config.get("gpu")), flush=True)
|
||||
print("fake-maya: config-api-key", "api_key" in config, flush=True)
|
||||
print("fake-maya: config-max-context", config.get("args"), flush=True)
|
||||
|
||||
if mode == "crash":
|
||||
print("fake-maya: error: engine did not start", file=sys.stderr, flush=True)
|
||||
sys.exit(3)
|
||||
|
||||
if mode == "orphan":
|
||||
child = subprocess.Popen(["sleep", "300"])
|
||||
print("fake-maya: engine pid", child.pid, flush=True)
|
||||
|
||||
if mode == "stubborn":
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
else:
|
||||
signal.signal(signal.SIGTERM, lambda *_: os._exit(0))
|
||||
|
||||
load_seconds = float(os.environ.get("FAKE_MAYA_LOAD_SECONDS", "1"))
|
||||
if mode == "hang":
|
||||
time.sleep(3600)
|
||||
time.sleep(load_seconds) # der echte Server lauscht erst nach dem Laden
|
||||
|
||||
ANSWER = ["Hallo", " vom", " Maya-", "Modell."]
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def _send_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 do_GET(self):
|
||||
if self.path == "/health":
|
||||
status = "reloading" if mode == "busy" else "ok"
|
||||
self._send_json(200, {"status": status, "model": "fake-maya", "unloaded": False})
|
||||
elif self.path == "/v1/models":
|
||||
self._send_json(200, {"object": "list", "data": [{"id": "fake-maya", "object": "model"}]})
|
||||
else:
|
||||
self._send_json(404, {})
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
request = json.loads(self.rfile.read(length) or b"{}")
|
||||
if self.path != "/v1/chat/completions":
|
||||
self._send_json(404, {})
|
||||
return
|
||||
model = request.get("model", "fake-maya")
|
||||
if request.get("stream"):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.end_headers()
|
||||
self.wfile.write(b": keep-alive\n\n")
|
||||
for i, part in enumerate(ANSWER):
|
||||
delta = {"reasoning_content": "denke"} if i == 0 else {"content": part}
|
||||
chunk = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": 1, "model": model,
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
|
||||
self.wfile.write(("data: " + json.dumps(chunk) + "\n\n").encode())
|
||||
self.wfile.flush()
|
||||
time.sleep(0.05)
|
||||
last = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": 1, "model": model,
|
||||
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7}}
|
||||
self.wfile.write(("data: " + json.dumps(last) + "\n\ndata: [DONE]\n\n").encode())
|
||||
self.wfile.flush()
|
||||
else:
|
||||
self._send_json(200, {
|
||||
"id": "chatcmpl-fake", "object": "chat.completion", "created": 1, "model": model,
|
||||
"choices": [{"index": 0, "finish_reason": "stop",
|
||||
"message": {"role": "assistant", "content": "".join(ANSWER),
|
||||
"reasoning_content": "denke"}}],
|
||||
"usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},
|
||||
})
|
||||
|
||||
|
||||
ThreadingHTTPServer((opt("--host"), int(opt("--port"))), Handler).serve_forever()
|
||||
266
crates/nexus-adapter/tests/maya_process.rs
Normal file
266
crates/nexus-adapter/tests/maya_process.rs
Normal file
@ -0,0 +1,266 @@
|
||||
//! 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);
|
||||
}
|
||||
Reference in New Issue
Block a user