feat: Engine-Adaptervertrag, llama.cpp-Adapter und Attrappe (M2.2)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 17:05:03 +01:00
parent 3e6148419b
commit ada5745c53
14 changed files with 1672 additions and 4 deletions

View File

@ -0,0 +1,36 @@
use std::time::Duration;
use async_trait::async_trait;
use crate::types::EngineInfo;
use crate::types::{
DiscoveredArtifact, Endpoint, Health, InstanceHandle, ProfileSpec, Result, Usage,
};
/// Vertrag zwischen Gateway und Engine (Spezifikation, Abschnitt 4).
///
/// Alle Methoden sind wiederholbar aufrufbar. `stop` ist idempotent: Eine
/// bereits beendete oder unbekannte Instanz ist kein Fehler.
#[async_trait]
pub trait Engine: Send + Sync {
/// Art, Modus und Fähigkeiten der Engine.
fn describe(&self) -> EngineInfo;
/// Sucht Modelle und Quantisierungen. Verändert nichts.
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>>;
/// Startet eine Instanz und kehrt erst zurück, wenn sie bereit ist oder
/// der Start gescheitert ist.
async fn start(&self, profile: &ProfileSpec) -> Result<InstanceHandle>;
/// Beendet die Instanz: zuerst höflich, nach `grace` mit Gewalt.
async fn stop(&self, instance: &InstanceHandle, grace: Duration) -> Result<()>;
async fn health(&self, instance: &InstanceHandle) -> Health;
/// Adresse, unter der die Instanz erreichbar ist.
fn endpoint(&self, instance: &InstanceHandle) -> Endpoint;
/// Misst den echten Ressourcenverbrauch.
async fn measure(&self, instance: &InstanceHandle) -> Usage;
}

View File

@ -0,0 +1,24 @@
//! Engine-Adaptervertrag, Prozesssteuerung und Adapter für Nexus.
//!
//! Der Vertrag steht in [`Engine`]. Adapter:
//! - [`LlamaCppEngine`]: startet `llama-server` als verwalteten Prozess (Managed).
//! - [`MockEngine`]: Attrappe ohne Prozesse für Scheduler- und Vertragstests.
//!
//! Stand M2.2: Die Weiterleitung von Anfragen (`forward`) kommt mit der API
//! (M2.3). Bis dahin liefert [`Engine::endpoint`] die Basis-URL, an die der
//! Aufrufer selbst sendet.
mod engine;
mod llama;
mod mock;
mod process;
mod types;
pub use engine::Engine;
pub use llama::{LlamaCppConfig, LlamaCppEngine};
pub use mock::{MockConfig, MockEngine};
pub use process::process_exists;
pub use types::{
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, Health, InstanceHandle, Mode,
ProfileSpec, Protocol, Result, Usage,
};

View File

@ -0,0 +1,635 @@
//! Adapter für `llama-server` (llama.cpp) im Modus Managed.
//!
//! Gemessen auf srv04 (09.11.2026, Bonsai-1.7B): `llama-server` antwortet auf
//! `GET /health` zuerst mit 503, solange das Modell lädt, danach mit 200 und
//! `{"status":"ok"}`; er spricht OpenAI-HTTP (`/v1/models`,
//! `/v1/chat/completions`); `SIGTERM` beendet ihn sauber und gibt den
//! GPU-Speicher frei. Der VRAM-Verbrauch ist über `nvidia-smi` pro PID messbar.
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use serde::Deserialize;
use tokio::process::{Child, Command};
use crate::engine::Engine;
use crate::process::{PortPool, http_status, log_tail, sigterm};
use crate::types::{
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, EngineInfo, Health, InstanceHandle,
Mode, ProfileSpec, Protocol, Result, Usage,
};
/// Konfiguration des llama.cpp-Adapters. Enthält keine Geheimnisse.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LlamaCppConfig {
/// Pfad zu `llama-server`.
pub binary: PathBuf,
/// Ordner, in denen `discover` nach `.gguf`-Dateien sucht.
pub model_roots: Vec<PathBuf>,
/// Port-Bereich für die Instanzen (nur `127.0.0.1`).
pub port_from: u16,
pub port_to: u16,
/// Wie lange das Laden eines Modells höchstens dauern darf.
pub ready_timeout_secs: u64,
/// Ordner für stdout und stderr der Instanzen.
pub log_dir: PathBuf,
/// Anzahl der Schichten auf der GPU (`-ngl`).
pub gpu_layers: i32,
/// Zusätzliche Argumente für jeden Start.
pub extra_args: Vec<String>,
/// Zusätzliche Umgebungsvariablen (keine Geheimnisse).
pub env: BTreeMap<String, String>,
/// Programm zur VRAM-Messung.
pub nvidia_smi: PathBuf,
}
impl Default for LlamaCppConfig {
fn default() -> Self {
Self {
binary: PathBuf::from("/srv/apps/llama.cpp/build/bin/llama-server"),
model_roots: vec![PathBuf::from("/srv/models/gguf")],
port_from: 18080,
port_to: 18180,
ready_timeout_secs: 120,
log_dir: PathBuf::from("data/logs"),
gpu_layers: 99,
extra_args: Vec::new(),
env: BTreeMap::new(),
nvidia_smi: PathBuf::from("nvidia-smi"),
}
}
}
/// Kommandozeile und Umgebung für einen Start.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CommandLine {
pub args: Vec<String>,
pub env: Vec<(String, String)>,
}
struct Managed {
child: Child,
port: u16,
}
pub struct LlamaCppEngine {
config: LlamaCppConfig,
ports: PortPool,
next_id: AtomicU64,
children: tokio::sync::Mutex<HashMap<u64, Managed>>,
}
impl LlamaCppEngine {
pub fn new(config: LlamaCppConfig) -> Self {
let ports = PortPool::new(config.port_from, config.port_to);
Self {
config,
ports,
next_id: AtomicU64::new(1),
children: tokio::sync::Mutex::new(HashMap::new()),
}
}
/// Baut Argumente und Umgebung für ein Profil. Der Server lauscht nur auf
/// `127.0.0.1`; die GPU-Auswahl läuft über `CUDA_VISIBLE_DEVICES`.
pub(crate) fn build_command(&self, profile: &ProfileSpec, port: u16) -> CommandLine {
let mut args = vec![
"-m".to_string(),
profile.model_path.display().to_string(),
"--host".to_string(),
"127.0.0.1".to_string(),
"--port".to_string(),
port.to_string(),
"-ngl".to_string(),
self.config.gpu_layers.to_string(),
"--alias".to_string(),
profile.model_alias.clone(),
];
if let Some(context) = profile.context {
args.push("-c".to_string());
args.push(context.to_string());
}
args.extend(self.config.extra_args.iter().cloned());
args.extend(profile.extra_args.iter().cloned());
let mut env: Vec<(String, String)> = self
.config
.env
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let gpus: Vec<String> = profile.gpus.iter().map(u32::to_string).collect();
env.push(("CUDA_VISIBLE_DEVICES".to_string(), gpus.join(",")));
CommandLine { args, env }
}
fn validate(profile: &ProfileSpec) -> Result<()> {
if profile.gpus.is_empty() {
return Err(AdapterError::InvalidProfile(
"keine GPU angegeben".to_string(),
));
}
if profile.model_alias.trim().is_empty() {
return Err(AdapterError::InvalidProfile(
"model_alias ist leer".to_string(),
));
}
if !profile.model_path.is_file() {
return Err(AdapterError::InvalidProfile(format!(
"Modelldatei {} existiert nicht",
profile.model_path.display()
)));
}
Ok(())
}
async fn spawn_and_wait(
&self,
id: u64,
port: u16,
profile: &ProfileSpec,
) -> Result<InstanceHandle> {
std::fs::create_dir_all(&self.config.log_dir).map_err(|source| AdapterError::Io {
path: self.config.log_dir.clone(),
source,
})?;
let log_path = self.config.log_dir.join(format!("instance-{id}.log"));
let io_err = |source| AdapterError::Io {
path: log_path.clone(),
source,
};
let log = std::fs::File::create(&log_path).map_err(io_err)?;
let log_err = log.try_clone().map_err(io_err)?;
let command_line = self.build_command(profile, port);
let mut child = Command::new(&self.config.binary)
.args(&command_line.args)
.envs(command_line.env.iter().map(|(k, v)| (k, v)))
.stdin(std::process::Stdio::null())
.stdout(log)
.stderr(log_err)
.kill_on_drop(true)
.spawn()
.map_err(|e| AdapterError::Spawn(format!("{}: {e}", self.config.binary.display())))?;
let timeout = Duration::from_secs(self.config.ready_timeout_secs);
let started = Instant::now();
loop {
if let Ok(Some(status)) = child.try_wait() {
return Err(AdapterError::ExitedEarly {
code: status.code(),
log_tail: log_tail(&log_path, 20),
});
}
if http_status(port, "/health", Duration::from_secs(1)).await == Some(200) {
break;
}
if started.elapsed() >= timeout {
let _ = child.start_kill();
let _ = child.wait().await;
return Err(AdapterError::NotReady {
seconds: self.config.ready_timeout_secs,
log_tail: log_tail(&log_path, 20),
});
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
let pid = child.id();
self.children
.lock()
.await
.insert(id, Managed { child, port });
Ok(InstanceHandle { id, pid, port })
}
async fn vram_mb(&self, pid: u32) -> Option<u64> {
let output = tokio::time::timeout(
Duration::from_secs(5),
Command::new(&self.config.nvidia_smi)
.args([
"--query-compute-apps=pid,used_memory",
"--format=csv,noheader,nounits",
])
.output(),
)
.await
.ok()?
.ok()?;
if !output.status.success() {
return None;
}
parse_vram_mb(&String::from_utf8_lossy(&output.stdout), pid)
}
}
#[async_trait]
impl Engine for LlamaCppEngine {
fn describe(&self) -> EngineInfo {
EngineInfo {
name: "llama.cpp".to_string(),
mode: Mode::Managed,
// Gemessen: Chat und Streaming laufen. Embeddings und Tool Calling
// hängen vom Modell und von den Startargumenten ab und sind noch
// nicht geprüft.
capabilities: Capabilities {
chat: true,
completions: true,
embeddings: false,
streaming: true,
tool_calling: false,
images: false,
},
}
}
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>> {
let roots = self.config.model_roots.clone();
tokio::task::spawn_blocking(move || scan_models(&roots))
.await
.map_err(|e| AdapterError::Spawn(format!("Suche abgebrochen: {e}")))
}
async fn start(&self, profile: &ProfileSpec) -> Result<InstanceHandle> {
Self::validate(profile)?;
let port = self.ports.acquire()?;
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
match self.spawn_and_wait(id, port, profile).await {
Ok(handle) => Ok(handle),
Err(e) => {
self.ports.release(port);
Err(e)
}
}
}
async fn stop(&self, instance: &InstanceHandle, grace: Duration) -> Result<()> {
let managed = self.children.lock().await.remove(&instance.id);
let Some(mut managed) = managed else {
return Ok(());
};
if let Some(pid) = managed.child.id() {
sigterm(pid);
}
let exited = tokio::time::timeout(grace, managed.child.wait()).await;
if exited.is_err() {
managed
.child
.kill()
.await
.map_err(|e| AdapterError::Stop(e.to_string()))?;
}
self.ports.release(managed.port);
Ok(())
}
async fn health(&self, instance: &InstanceHandle) -> Health {
let port = {
let mut children = self.children.lock().await;
let Some(managed) = children.get_mut(&instance.id) else {
return Health::Gone;
};
match managed.child.try_wait() {
Ok(Some(_)) => {
let port = managed.port;
children.remove(&instance.id);
self.ports.release(port);
return Health::Gone;
}
Ok(None) => managed.port,
Err(e) => return Health::Unhealthy(e.to_string()),
}
};
match http_status(port, "/health", Duration::from_secs(2)).await {
Some(200) => Health::Ready,
Some(503) => Health::Starting,
Some(code) => Health::Unhealthy(format!("HTTP {code}")),
None => Health::Unhealthy("keine Antwort".to_string()),
}
}
fn endpoint(&self, instance: &InstanceHandle) -> Endpoint {
Endpoint {
base_url: format!("http://127.0.0.1:{}", instance.port),
protocol: Protocol::OpenAi,
}
}
async fn measure(&self, instance: &InstanceHandle) -> Usage {
let Some(pid) = instance.pid else {
return Usage::default();
};
Usage {
vram_mb: self.vram_mb(pid).await,
ram_mb: std::fs::read_to_string(format!("/proc/{pid}/status"))
.ok()
.and_then(|text| parse_rss_mb(&text)),
}
}
}
/// Liest aus der Ausgabe von `nvidia-smi --query-compute-apps=pid,used_memory
/// --format=csv,noheader,nounits` den VRAM (MiB) eines Prozesses; mehrere
/// Zeilen (mehrere GPUs) werden addiert.
pub(crate) fn parse_vram_mb(output: &str, pid: u32) -> Option<u64> {
let mut total = None;
for line in output.lines() {
let mut fields = line.split(',').map(str::trim);
let (Some(p), Some(mb)) = (fields.next(), fields.next()) else {
continue;
};
if p.parse::<u32>().ok() == Some(pid)
&& let Ok(mb) = mb.parse::<u64>()
{
*total.get_or_insert(0) += mb;
}
}
total
}
/// Liest `VmRSS` (kB) aus `/proc/<pid>/status` und rechnet in MiB um.
pub(crate) fn parse_rss_mb(status: &str) -> Option<u64> {
let line = status.lines().find(|l| l.starts_with("VmRSS:"))?;
let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
Some(kb / 1024)
}
const MAX_SCAN_DEPTH: usize = 6;
/// Teile eines geteilten Modells: erster Teil, Summe der Größen, gefundene
/// Teile, erwartete Teile.
type ShardGroup = (Option<PathBuf>, u64, u32, u32);
/// Sucht `.gguf`-Modelle. Übersprungen werden Vision-Projektoren (`mmproj*`),
/// Vokabeldateien (`*vocab*`) und Entwurfsmodelle (`mtp*`), weil sie keine
/// eigenständigen Modelle sind. Geteilte Modelle (`-00001-of-00002`) zählen
/// als ein Modell mit der Summe der Größen; fehlt der erste Teil, wird das
/// Modell ausgelassen.
pub(crate) fn scan_models(roots: &[PathBuf]) -> Vec<DiscoveredArtifact> {
let mut files = Vec::new();
for root in roots {
collect_gguf(root, 0, &mut files);
}
let mut singles = Vec::new();
let mut shards: BTreeMap<(PathBuf, String), ShardGroup> = BTreeMap::new();
for (path, size) in files {
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
let lower = stem.to_lowercase();
if lower.starts_with("mmproj") || lower.contains("vocab") || lower.starts_with("mtp") {
continue;
}
match split_shard(stem) {
Some((base, index, total)) => {
let key = (
path.parent().unwrap_or(Path::new("")).to_path_buf(),
base.to_string(),
);
let entry = shards.entry(key).or_insert((None, 0, 0, total));
entry.1 += size;
entry.2 += 1;
if index == 1 {
entry.0 = Some(path.clone());
}
}
None => singles.push(DiscoveredArtifact {
name: stem.to_string(),
quantization: parse_quantization(stem),
path,
size_bytes: size,
}),
}
}
let mut found = singles;
for ((_, base), (first, size, parts, expected)) in shards {
if let (Some(path), true) = (first, parts == expected) {
found.push(DiscoveredArtifact {
quantization: parse_quantization(&base),
name: base,
path,
size_bytes: size,
});
}
}
found.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.path.cmp(&b.path)));
found
}
fn collect_gguf(dir: &Path, depth: usize, out: &mut Vec<(PathBuf, u64)>) {
if depth > MAX_SCAN_DEPTH {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = entry.metadata() else { continue };
let hidden = entry.file_name().to_string_lossy().starts_with('.');
if meta.is_dir() && !hidden {
collect_gguf(&path, depth + 1, out);
} else if meta.is_file() && path.extension().is_some_and(|e| e == "gguf") {
out.push((path, meta.len()));
}
}
}
/// Zerlegt `Name-00001-of-00002` in (`Name`, 1, 2).
fn split_shard(stem: &str) -> Option<(&str, u32, u32)> {
let (left, total) = stem.rsplit_once("-of-")?;
let total: u32 = total.parse().ok()?;
let (base, index) = left.rsplit_once('-')?;
let index: u32 = index.parse().ok()?;
Some((base, index, total))
}
/// Erkennt die Quantisierung im Dateinamen (zum Beispiel `Q4_K_XL`, `IQ1_S`,
/// `BF16`). Liefert `None`, wenn der Name keine erkennbare Angabe enthält.
pub(crate) fn parse_quantization(name: &str) -> Option<String> {
name.split(['-', '.']).find_map(|token| {
let upper = token.to_uppercase();
let digit_after = |prefix: &str| {
upper
.strip_prefix(prefix)
.and_then(|rest| rest.chars().next())
.is_some_and(|c| c.is_ascii_digit())
};
let known = matches!(upper.as_str(), "BF16" | "F16" | "F32");
(known || digit_after("IQ") || digit_after("Q")).then_some(upper)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn profile() -> ProfileSpec {
ProfileSpec {
model_alias: "bonsai".to_string(),
model_path: PathBuf::from("/srv/models/gguf/Bonsai-1.7B-Q1_0.gguf"),
gpus: vec![0, 1],
context: Some(2048),
extra_args: vec!["--no-webui".to_string()],
}
}
#[test]
fn kommandozeile_bindet_nur_an_localhost_und_waehlt_gpus() {
let engine = LlamaCppEngine::new(LlamaCppConfig::default());
let cmd = engine.build_command(&profile(), 18090);
assert_eq!(
cmd.args,
[
"-m",
"/srv/models/gguf/Bonsai-1.7B-Q1_0.gguf",
"--host",
"127.0.0.1",
"--port",
"18090",
"-ngl",
"99",
"--alias",
"bonsai",
"-c",
"2048",
"--no-webui"
]
);
assert!(
cmd.env
.contains(&("CUDA_VISIBLE_DEVICES".to_string(), "0,1".to_string()))
);
}
#[test]
fn kontext_ist_optional_und_konfigurierte_argumente_kommen_zuerst() {
let config = LlamaCppConfig {
extra_args: vec!["--flash-attn".to_string()],
env: BTreeMap::from([("LD_LIBRARY_PATH".to_string(), "/x".to_string())]),
..LlamaCppConfig::default()
};
let engine = LlamaCppEngine::new(config);
let mut p = profile();
p.context = None;
let cmd = engine.build_command(&p, 1);
assert!(!cmd.args.contains(&"-c".to_string()));
let flash = cmd.args.iter().position(|a| a == "--flash-attn").unwrap();
let profil = cmd.args.iter().position(|a| a == "--no-webui").unwrap();
assert!(flash < profil);
assert!(
cmd.env
.contains(&("LD_LIBRARY_PATH".to_string(), "/x".to_string()))
);
}
#[test]
fn konfiguration_aus_toml_mit_standardwerten_und_ablehnung_unbekannter_felder() {
let config: LlamaCppConfig = toml::from_str("ready_timeout_secs = 300").unwrap();
assert_eq!(config.ready_timeout_secs, 300);
assert_eq!(config.port_from, 18080);
assert!(toml::from_str::<LlamaCppConfig>("portt = 1").is_err());
}
#[test]
fn quantisierung_wird_aus_dem_namen_gelesen() {
let fall = |n: &str| parse_quantization(n);
assert_eq!(
fall("Qwen3.6-35B-A3B-UD-Q4_K_XL").as_deref(),
Some("Q4_K_XL")
);
assert_eq!(
fall("GLM-5.3-Flash-Maya-XS-IQ1_S").as_deref(),
Some("IQ1_S")
);
assert_eq!(fall("Bonsai-1.7B-Q1_0").as_deref(), Some("Q1_0"));
assert_eq!(
fall("Qwen3.8-Flash-Next-GSQ-RCO-Q2_0").as_deref(),
Some("Q2_0")
);
assert_eq!(fall("model-BF16").as_deref(), Some("BF16"));
assert_eq!(fall("Bonsai-1.7B"), None);
assert_eq!(fall("Qwen3.8-Flash"), None);
}
#[test]
fn geteilte_dateien_werden_zerlegt() {
assert_eq!(
split_shard("Name-Q2_0-00001-of-00002"),
Some(("Name-Q2_0", 1, 2))
);
assert_eq!(split_shard("Name-Q2_0"), None);
assert_eq!(split_shard("A-of-B"), None);
}
#[test]
fn vram_wird_pro_pid_gelesen_und_ueber_gpus_addiert() {
let out = "123772, 638\n999, 10\n123772, 100\n";
assert_eq!(parse_vram_mb(out, 123772), Some(738));
assert_eq!(parse_vram_mb(out, 5), None);
assert_eq!(parse_vram_mb("", 1), None);
assert_eq!(parse_vram_mb("Unsinn", 1), None);
}
#[test]
fn rss_wird_in_mib_umgerechnet() {
let status = "Name:\tllama-server\nVmRSS:\t 511668 kB\nThreads:\t4\n";
assert_eq!(parse_rss_mb(status), Some(499));
assert_eq!(parse_rss_mb("Name: x"), None);
}
#[test]
fn suche_findet_modelle_und_ueberspringt_hilfsdateien() {
let root = std::env::temp_dir().join(format!("nexus-adapter-scan-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let schreibe = |rel: &str, bytes: usize| {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, vec![0u8; bytes]).unwrap();
};
schreibe("a/Qwen-Q4_K_XL.gguf", 10);
schreibe("a/mmproj-F16.gguf", 3);
schreibe("a/ggml-vocab-llama.gguf", 1);
schreibe("mtp/mtp-q2_0.gguf", 2);
schreibe("b/Big-IQ1_S-00001-of-00002.gguf", 5);
schreibe("b/Big-IQ1_S-00002-of-00002.gguf", 7);
schreibe("c/Unvollstaendig-Q2_0-00002-of-00002.gguf", 4);
schreibe("a/notizen.txt", 9);
schreibe(".versteckt/Geheim-Q4_0.gguf", 8);
let found = scan_models(std::slice::from_ref(&root));
let namen: Vec<_> = found.iter().map(|a| a.name.as_str()).collect();
assert_eq!(namen, ["Big-IQ1_S", "Qwen-Q4_K_XL"], "{found:?}");
assert_eq!(found[0].size_bytes, 12);
assert!(found[0].path.ends_with("Big-IQ1_S-00001-of-00002.gguf"));
assert_eq!(found[0].quantization.as_deref(), Some("IQ1_S"));
assert_eq!(found[1].size_bytes, 10);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn suche_in_fehlendem_ordner_liefert_leere_liste() {
assert!(scan_models(&[PathBuf::from("/nicht/vorhanden")]).is_empty());
}
#[test]
fn profilpruefung_lehnt_unbrauchbare_profile_ab() {
let mut p = profile();
assert!(matches!(
LlamaCppEngine::validate(&p),
Err(AdapterError::InvalidProfile(m)) if m.contains("existiert nicht")
));
p.gpus.clear();
assert!(matches!(
LlamaCppEngine::validate(&p),
Err(AdapterError::InvalidProfile(m)) if m.contains("GPU")
));
}
}

View File

@ -0,0 +1,228 @@
//! Attrappen-Engine: erfüllt den Vertrag ohne Prozesse. Für Scheduler- und
//! Vertragstests ohne GPU. Ein grüner Test gegen diese Attrappe heißt „verhält
//! sich wie gebaut“, nicht „Gesamtweg läuft“.
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::Duration;
use async_trait::async_trait;
use crate::engine::Engine;
use crate::types::{
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, EngineInfo, Health, InstanceHandle,
Mode, ProfileSpec, Protocol, Result, Usage,
};
/// Einstellbares Verhalten der Attrappe.
#[derive(Debug, Clone)]
pub struct MockConfig {
pub start_delay: Duration,
/// Wenn gesetzt, scheitert jeder Start mit dieser Meldung.
pub fail_start: Option<String>,
pub vram_mb: u64,
pub ram_mb: u64,
pub artifacts: Vec<DiscoveredArtifact>,
}
impl Default for MockConfig {
fn default() -> Self {
Self {
start_delay: Duration::ZERO,
fail_start: None,
vram_mb: 1024,
ram_mb: 512,
artifacts: Vec::new(),
}
}
}
pub struct MockEngine {
config: MockConfig,
next_id: AtomicU64,
starts: AtomicUsize,
alive: Mutex<HashMap<u64, bool>>,
}
impl MockEngine {
pub fn new(config: MockConfig) -> Self {
Self {
config,
next_id: AtomicU64::new(1),
starts: AtomicUsize::new(0),
alive: Mutex::new(HashMap::new()),
}
}
/// Wie oft `start` aufgerufen wurde (auch gescheiterte Starts).
pub fn start_count(&self) -> usize {
self.starts.load(Ordering::SeqCst)
}
/// Anzahl der Instanzen, die gerade laufen.
pub fn running(&self) -> usize {
self.alive.lock().unwrap().values().filter(|a| **a).count()
}
/// Simuliert den Absturz einer Instanz.
pub fn crash(&self, instance: &InstanceHandle) {
if let Some(alive) = self.alive.lock().unwrap().get_mut(&instance.id) {
*alive = false;
}
}
}
#[async_trait]
impl Engine for MockEngine {
fn describe(&self) -> EngineInfo {
EngineInfo {
name: "mock".to_string(),
mode: Mode::Managed,
capabilities: Capabilities {
chat: true,
completions: true,
embeddings: true,
streaming: true,
tool_calling: false,
images: false,
},
}
}
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>> {
Ok(self.config.artifacts.clone())
}
async fn start(&self, profile: &ProfileSpec) -> Result<InstanceHandle> {
self.starts.fetch_add(1, Ordering::SeqCst);
if profile.gpus.is_empty() {
return Err(AdapterError::InvalidProfile(
"keine GPU angegeben".to_string(),
));
}
tokio::time::sleep(self.config.start_delay).await;
if let Some(message) = &self.config.fail_start {
return Err(AdapterError::Spawn(message.clone()));
}
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
self.alive.lock().unwrap().insert(id, true);
Ok(InstanceHandle {
id,
pid: None,
port: 40000 + id as u16,
})
}
async fn stop(&self, instance: &InstanceHandle, _grace: Duration) -> Result<()> {
self.alive.lock().unwrap().remove(&instance.id);
Ok(())
}
async fn health(&self, instance: &InstanceHandle) -> Health {
match self.alive.lock().unwrap().get(&instance.id) {
Some(true) => Health::Ready,
_ => Health::Gone,
}
}
fn endpoint(&self, instance: &InstanceHandle) -> Endpoint {
Endpoint {
base_url: format!("http://127.0.0.1:{}", instance.port),
protocol: Protocol::OpenAi,
}
}
async fn measure(&self, instance: &InstanceHandle) -> Usage {
match self.alive.lock().unwrap().get(&instance.id) {
Some(true) => Usage {
vram_mb: Some(self.config.vram_mb),
ram_mb: Some(self.config.ram_mb),
},
_ => Usage::default(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn profile() -> ProfileSpec {
ProfileSpec {
model_alias: "m".to_string(),
model_path: PathBuf::from("/x.gguf"),
gpus: vec![0],
context: None,
extra_args: vec![],
}
}
#[tokio::test(start_paused = true)]
async fn start_wartet_die_ladezeit_ab_und_instanz_ist_bereit() {
let engine = MockEngine::new(MockConfig {
start_delay: Duration::from_secs(5),
..MockConfig::default()
});
let t0 = tokio::time::Instant::now();
let inst = engine.start(&profile()).await.unwrap();
assert!(t0.elapsed() >= Duration::from_secs(5));
assert_eq!(engine.health(&inst).await, Health::Ready);
assert_eq!(engine.running(), 1);
}
#[tokio::test]
async fn stop_ist_idempotent_und_danach_gone() {
let engine = MockEngine::new(MockConfig::default());
let inst = engine.start(&profile()).await.unwrap();
engine.stop(&inst, Duration::from_secs(1)).await.unwrap();
engine.stop(&inst, Duration::from_secs(1)).await.unwrap();
assert_eq!(engine.health(&inst).await, Health::Gone);
assert_eq!(engine.measure(&inst).await, Usage::default());
}
#[tokio::test]
async fn absturz_wird_als_gone_gemeldet() {
let engine = MockEngine::new(MockConfig::default());
let inst = engine.start(&profile()).await.unwrap();
engine.crash(&inst);
assert_eq!(engine.health(&inst).await, Health::Gone);
}
#[tokio::test]
async fn gescheiterter_start_wird_gezaehlt_und_liefert_fehler() {
let engine = MockEngine::new(MockConfig {
fail_start: Some("kein VRAM".to_string()),
..MockConfig::default()
});
let err = engine.start(&profile()).await.unwrap_err();
assert!(matches!(err, AdapterError::Spawn(_)));
assert_eq!(engine.start_count(), 1);
assert_eq!(engine.running(), 0);
}
#[tokio::test]
async fn messung_liefert_eingestellte_werte() {
let engine = MockEngine::new(MockConfig {
vram_mb: 4000,
ram_mb: 800,
..MockConfig::default()
});
let inst = engine.start(&profile()).await.unwrap();
let usage = engine.measure(&inst).await;
assert_eq!(usage.vram_mb, Some(4000));
assert_eq!(usage.ram_mb, Some(800));
}
#[tokio::test]
async fn profil_ohne_gpu_wird_abgelehnt() {
let engine = MockEngine::new(MockConfig::default());
let mut p = profile();
p.gpus.clear();
assert!(matches!(
engine.start(&p).await,
Err(AdapterError::InvalidProfile(_))
));
}
}

View File

@ -0,0 +1,161 @@
//! Hilfen für verwaltete Prozesse: HTTP-Status, Signale, Log-Ende, Ports.
use std::collections::HashSet;
use std::path::Path;
use std::sync::Mutex;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use crate::types::{AdapterError, Result};
/// Fragt `GET <pfad>` auf `127.0.0.1:<port>` ab und liefert den
/// HTTP-Statuscode, oder `None` bei Verbindungsfehler und Zeitüberschreitung.
pub(crate) async fn http_status(port: u16, path: &str, timeout: Duration) -> Option<u16> {
let request = format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n");
let work = async {
let mut stream = TcpStream::connect(("127.0.0.1", port)).await.ok()?;
stream.write_all(request.as_bytes()).await.ok()?;
let mut buf = [0u8; 64];
let n = stream.read(&mut buf).await.ok()?;
parse_status_line(std::str::from_utf8(&buf[..n]).ok()?)
};
tokio::time::timeout(timeout, work).await.ok().flatten()
}
fn parse_status_line(text: &str) -> Option<u16> {
let line = text.lines().next()?;
let mut parts = line.split_whitespace();
let version = parts.next()?;
if !version.starts_with("HTTP/") {
return None;
}
parts.next()?.parse().ok()
}
/// Schickt ein Signal an einen Prozess. Liefert `false`, wenn es den Prozess
/// nicht (mehr) gibt.
pub(crate) fn send_signal(pid: u32, signal: i32) -> bool {
// SAFETY: `kill` hat keine Speichersicherheits-Voraussetzungen; ein
// ungültiger PID ergibt nur einen Fehlercode.
unsafe { libc::kill(pid as i32, signal) == 0 }
}
/// Prüft, ob ein Prozess mit diesem PID existiert.
pub fn process_exists(pid: u32) -> bool {
send_signal(pid, 0)
}
pub(crate) fn sigterm(pid: u32) -> bool {
send_signal(pid, libc::SIGTERM)
}
/// Letzte Zeilen einer Logdatei (höchstens `max_lines` Zeilen und 4 KB).
pub(crate) fn log_tail(path: &Path, max_lines: usize) -> String {
let Ok(bytes) = std::fs::read(path) else {
return "(Log nicht lesbar)".to_string();
};
let start = bytes.len().saturating_sub(4096);
let text = String::from_utf8_lossy(&bytes[start..]);
let lines: Vec<&str> = text.lines().collect();
let from = lines.len().saturating_sub(max_lines);
lines[from..].join("\n")
}
/// Verwaltet die Ports eines Bereichs: ein Port gilt als belegt, wenn wir ihn
/// vergeben haben oder auf `127.0.0.1` schon jemand lauscht.
pub(crate) struct PortPool {
from: u16,
to: u16,
taken: Mutex<HashSet<u16>>,
}
impl PortPool {
pub(crate) fn new(from: u16, to: u16) -> Self {
Self {
from,
to,
taken: Mutex::new(HashSet::new()),
}
}
pub(crate) fn acquire(&self) -> Result<u16> {
let mut taken = self.taken.lock().expect("PortPool vergiftet");
for port in self.from..=self.to {
if taken.contains(&port) {
continue;
}
if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
taken.insert(port);
return Ok(port);
}
}
Err(AdapterError::NoFreePort {
from: self.from,
to: self.to,
})
}
pub(crate) fn release(&self, port: u16) {
self.taken.lock().expect("PortPool vergiftet").remove(&port);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn statuszeile_wird_gelesen() {
assert_eq!(parse_status_line("HTTP/1.1 200 OK\r\n"), Some(200));
assert_eq!(
parse_status_line("HTTP/1.0 503 Service Unavailable"),
Some(503)
);
assert_eq!(parse_status_line("Unsinn"), None);
assert_eq!(parse_status_line(""), None);
}
#[test]
fn log_ende_kuerzt_auf_letzte_zeilen() {
let dir =
std::env::temp_dir().join(format!("nexus-adapter-logtail-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("x.log");
std::fs::write(&file, "a\nb\nc\nd\ne\n").unwrap();
assert_eq!(log_tail(&file, 2), "d\ne");
assert_eq!(log_tail(&dir.join("fehlt.log"), 2), "(Log nicht lesbar)");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn portpool_vergibt_jeden_port_nur_einmal_und_gibt_frei() {
// Ein Bereich mit einem einzigen Port.
let probe = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = probe.local_addr().unwrap().port();
drop(probe);
let pool = PortPool::new(port, port);
assert_eq!(pool.acquire().unwrap(), port);
assert!(matches!(
pool.acquire(),
Err(AdapterError::NoFreePort { .. })
));
pool.release(port);
assert_eq!(pool.acquire().unwrap(), port);
}
#[test]
fn portpool_ueberspringt_belegte_ports() {
let belegt = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = belegt.local_addr().unwrap().port();
let pool = PortPool::new(port, port);
assert!(pool.acquire().is_err());
}
#[test]
fn eigener_prozess_existiert_unmoeglicher_pid_nicht() {
assert!(process_exists(std::process::id()));
assert!(!process_exists(4_000_000));
}
}

View File

@ -0,0 +1,120 @@
use std::path::PathBuf;
/// Betriebsmodus einer Engine (Spezifikation, Abschnitt 4).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
/// Das Gateway startet und stoppt die Engine-Prozesse selbst.
Managed,
/// Das Gateway nutzt eine bereits laufende Engine, ohne sie zu steuern.
External,
/// Wie External, plus Laden und Entladen über die API der Engine.
Attached,
}
/// Sprache, die eine Engine spricht.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
/// OpenAI-kompatibles HTTP.
OpenAi,
}
/// Was eine Engine grundsätzlich kann. Die tatsächliche Unterstützung hängt
/// zusätzlich vom Modell ab.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Capabilities {
pub chat: bool,
pub completions: bool,
pub embeddings: bool,
pub streaming: bool,
pub tool_calling: bool,
pub images: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EngineInfo {
pub name: String,
pub mode: Mode,
pub capabilities: Capabilities,
}
/// Ein auf der Platte gefundenes Modell (Vorschlag für die Registry; ein
/// Administrator gibt es frei).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredArtifact {
/// Name ohne Endung und ohne Aufteilungs-Suffix (`-00001-of-00002`).
pub name: String,
/// Pfad der Datei (bei geteilten Modellen die erste Datei).
pub path: PathBuf,
pub quantization: Option<String>,
/// Gesamtgröße aller Teile.
pub size_bytes: u64,
}
/// Startkonfiguration für eine Modellinstanz (Auszug aus dem Profil).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileSpec {
/// Name, unter dem die Engine das Modell anbietet.
pub model_alias: String,
pub model_path: PathBuf,
/// GPU-Indizes; mindestens eine.
pub gpus: Vec<u32>,
pub context: Option<u32>,
pub extra_args: Vec<String>,
}
/// Verweis auf eine laufende Instanz.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstanceHandle {
pub id: u64,
pub pid: Option<u32>,
pub port: u16,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Health {
/// Prozess läuft, Modell wird noch geladen.
Starting,
Ready,
Unhealthy(String),
/// Prozess existiert nicht mehr.
Gone,
}
/// Gemessener Ressourcenverbrauch einer Instanz (`None` = nicht messbar).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Usage {
pub vram_mb: Option<u64>,
pub ram_mb: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Endpoint {
pub base_url: String,
pub protocol: Protocol,
}
/// Fehler der Adapter. Die Fehlerarten kennt der Scheduler (Spezifikation,
/// Abschnitt 4).
#[derive(Debug, thiserror::Error)]
pub enum AdapterError {
#[error("ungültiges Profil: {0}")]
InvalidProfile(String),
#[error("Prozess konnte nicht gestartet werden: {0}")]
Spawn(String),
#[error("Prozess endete beim Start (Exit-Code {code:?}); Log-Ende:\n{log_tail}")]
ExitedEarly { code: Option<i32>, log_tail: String },
#[error("nicht bereit nach {seconds} s; Log-Ende:\n{log_tail}")]
NotReady { seconds: u64, log_tail: String },
#[error("kein freier Port im Bereich {from}..={to}")]
NoFreePort { from: u16, to: u16 },
#[error("Stoppen fehlgeschlagen: {0}")]
Stop(String),
#[error("Dateizugriff auf {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
}
pub type Result<T> = std::result::Result<T, AdapterError>;