feat: Strata-Adapter (#1038), Release 0.1.6

Strata teilt Servercode und Protokoll mit Maya (docs/m2-strata-messung.md);
MayaEngine::strata startet server.py --engine strata, behält den Arbeitsordner
des Terminals, nur 127.0.0.1. Scheduler führt Strata als exklusiv. Neu: Abschnitt
[strata], nexus model add --engine strata --strata-config. Auf srv04 mit echtem
Strata geprüft (client2antwort.1-.3).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GmHhg3bfByVgQ9z7CGCSGc
This commit is contained in:
2026-11-16 06:51:21 +01:00
parent 437108c88b
commit 3e100918c2
18 changed files with 291 additions and 35 deletions

View File

@ -11,6 +11,14 @@
//! - Nach `POST /models/unload` oder einem Leerlauf-Entladen lädt der nächste
//! Chat das Modell selbst nach (etwa 66 s).
//!
//! **Strata** (`serve/server.py` des Strata-Terminals) teilt sich Servercode und
//! Protokoll mit Maya (gemessen am 16.11.2026, `docs/m2-strata-messung.md`) und
//! läuft deshalb über denselben Adapter: [`MayaEngine::strata`] setzt
//! `--engine strata`, behält den Arbeitsordner der Konfiguration (die Engine
//! wird über `$XDG_DATA_HOME/strata/components` gefunden, das bei einem anderen
//! Benutzer als `svc-scotty` in `[strata.env]` gesetzt werden muss) und nennt
//! sich `strata`.
//!
//! Das Modell ist bei Maya die Konfigurationsdatei (JSON). Der Adapter legt je
//! Instanz eine Kopie an, in der er Port, Log, GPUs und Arbeitsordner setzt,
//! damit weder die Originaldatei noch der Maya-Ordner verändert werden. Ein
@ -85,7 +93,15 @@ struct Managed {
port: u16,
}
/// Welcher Server hinter dem Adapter steckt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Flavor {
Maya,
Strata,
}
pub struct MayaEngine {
flavor: Flavor,
config: MayaConfig,
ports: PortPool,
next_id: AtomicU64,
@ -94,8 +110,18 @@ pub struct MayaEngine {
impl MayaEngine {
pub fn new(config: MayaConfig) -> Self {
Self::with_flavor(Flavor::Maya, config)
}
/// Derselbe Adapter für den Strata-Server (siehe Moduldokumentation).
pub fn strata(config: MayaConfig) -> Self {
Self::with_flavor(Flavor::Strata, config)
}
fn with_flavor(flavor: Flavor, config: MayaConfig) -> Self {
let ports = PortPool::new(config.port_from, config.port_to);
Self {
flavor,
config,
ports,
next_id: AtomicU64::new(1),
@ -103,6 +129,14 @@ impl MayaEngine {
}
}
/// Name der Engine im Gateway und in Dateinamen.
fn name(&self) -> &'static str {
match self.flavor {
Flavor::Maya => "maya",
Flavor::Strata => "strata",
}
}
fn validate(profile: &ProfileSpec) -> Result<()> {
if profile.gpus.is_empty() {
return Err(AdapterError::InvalidProfile(
@ -125,15 +159,18 @@ impl MayaEngine {
/// Kommandozeile für einen Start. Der Server lauscht nur auf `127.0.0.1`.
pub(crate) fn build_args(&self, config_path: &Path, port: u16) -> Vec<String> {
let mut args = vec![
self.config.script.display().to_string(),
let mut args = vec![self.config.script.display().to_string()];
if self.flavor == Flavor::Strata {
args.extend(["--engine".to_string(), "strata".to_string()]);
}
args.extend([
"--config".to_string(),
config_path.display().to_string(),
"--host".to_string(),
"127.0.0.1".to_string(),
"--port".to_string(),
port.to_string(),
];
]);
args.extend(self.config.extra_args.iter().cloned());
args
}
@ -152,7 +189,8 @@ impl MayaEngine {
};
let log_dir =
std::path::absolute(&self.config.log_dir).map_err(io(&self.config.log_dir))?;
let workdir = log_dir.join(format!("maya-{id}"));
let name = self.name();
let workdir = log_dir.join(format!("{name}-{id}"));
std::fs::create_dir_all(&workdir).map_err(io(&workdir))?;
let text = std::fs::read_to_string(&profile.model_path).map_err(io(&profile.model_path))?;
@ -162,15 +200,30 @@ impl MayaEngine {
profile.model_path.display()
))
})?;
let engine_log = log_dir.join(format!("instance-maya-{id}-engine.log"));
let copy = instance_config(template, port, &engine_log, &profile.gpus, profile.context)?;
let engine_log = log_dir.join(format!("instance-{name}-{id}-engine.log"));
let keep_cwd = self.flavor == Flavor::Strata;
let copy = instance_config_for(
template,
port,
&engine_log,
&profile.gpus,
profile.context,
keep_cwd,
)?;
// Strata braucht seinen Arbeitsordner (Terminal), Maya läuft im eigenen.
let process_dir = copy
.get("cwd")
.and_then(Value::as_str)
.map(PathBuf::from)
.filter(|p| keep_cwd && p.is_dir())
.unwrap_or_else(|| workdir.clone());
let config_path = workdir.join("config.json");
std::fs::write(
&config_path,
serde_json::to_vec_pretty(&copy).unwrap_or_default(),
)
.map_err(io(&config_path))?;
Ok((config_path, workdir))
Ok((config_path, process_dir))
}
async fn spawn_and_wait(
@ -184,7 +237,10 @@ impl MayaEngine {
source,
})?;
let (config_path, workdir) = self.write_instance_config(id, port, profile)?;
let log_path = self.config.log_dir.join(format!("instance-maya-{id}.log"));
let log_path = self
.config
.log_dir
.join(format!("instance-{}-{id}.log", self.name()));
let io_err = |source| AdapterError::Io {
path: log_path.clone(),
source,
@ -332,12 +388,26 @@ pub(crate) fn parse_health(text: &str) -> Option<HealthState> {
/// Setzt Port, Log, GPUs und Kontext in der Kopie der Maya-Konfiguration und
/// entfernt, was die Instanz stören würde (Arbeitsordner, API-Schlüssel).
#[cfg(test)]
pub(crate) fn instance_config(
template: Value,
port: u16,
engine_log: &Path,
gpus: &[u32],
context: Option<u32>,
) -> Result<Value> {
instance_config_for(template, port, engine_log, gpus, context, false)
}
/// Wie [`instance_config`]; `keep_cwd` behält den Arbeitsordner der Vorlage
/// (Strata).
pub(crate) fn instance_config_for(
template: Value,
port: u16,
engine_log: &Path,
gpus: &[u32],
context: Option<u32>,
keep_cwd: bool,
) -> Result<Value> {
let Value::Object(mut map) = template else {
return Err(AdapterError::InvalidProfile(
@ -349,7 +419,9 @@ pub(crate) fn instance_config(
"Maya-Konfiguration ohne \"exe\"".to_string(),
));
}
map.remove("cwd");
if !keep_cwd {
map.remove("cwd");
}
// Der Server lauscht nur lokal; ein Schlüssel aus der Vorlage käme beim
// Gateway nicht an und würde jede Anfrage mit 401 abweisen.
map.remove("api_key");
@ -411,7 +483,7 @@ pub(crate) fn parse_pgrp(stat: &str) -> Option<u32> {
impl Engine for MayaEngine {
fn describe(&self) -> EngineInfo {
EngineInfo {
name: "maya".to_string(),
name: self.name().to_string(),
mode: Mode::Managed,
// Gemessen: Chat und Streaming. Embeddings, Tool Calling und Bilder
// (Maya kann Bilder lesen) sind über das Gateway nicht geprüft.
@ -570,7 +642,7 @@ pub(crate) fn scan_configs(roots: &[PathBuf]) -> Vec<DiscoveredArtifact> {
.and_then(Value::as_str)
.map(str::to_string);
let pack = value.get("args").and_then(Value::as_array).and_then(|a| {
let i = a.iter().position(|x| x == "--glm-pack")?;
let i = a.iter().position(|x| x == "--glm-pack" || x == "--pack")?;
a.get(i + 1)?.as_str().map(PathBuf::from)
});
found.push(DiscoveredArtifact {
@ -610,6 +682,37 @@ fn dir_size(dir: &Path, depth: usize) -> u64 {
.sum()
}
#[cfg(test)]
mod strata_tests {
use super::*;
use serde_json::json;
#[test]
fn strata_startet_den_server_mit_engine_strata_und_behaelt_den_arbeitsordner() {
let engine = MayaEngine::strata(MayaConfig::default());
let args = engine.build_args(Path::new("/c.json"), 18500);
assert_eq!(args[1..3], ["--engine", "strata"]);
assert!(args.windows(2).any(|w| w == ["--host", "127.0.0.1"]));
assert_eq!(engine.describe().name, "strata");
let maya = MayaEngine::new(MayaConfig::default());
assert!(
!maya
.build_args(Path::new("/c.json"), 1)
.contains(&"--engine".to_string())
);
assert_eq!(maya.describe().name, "maya");
let template =
json!({"exe": "component:strata-engine", "cwd": "/t", "api_key": "x", "args": []});
let kept =
instance_config_for(template.clone(), 1, Path::new("/l"), &[0, 1], None, true).unwrap();
assert_eq!(kept["cwd"], "/t");
assert!(kept.get("api_key").is_none());
let dropped = instance_config(template, 1, Path::new("/l"), &[0], None).unwrap();
assert!(dropped.get("cwd").is_none());
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@ -29,8 +29,11 @@ pub use nexus_scheduler::Settings as SchedulerSettings;
use crate::metrics::{InstanceSample, Metrics, parse_gpus};
/// Engine, die ihre GPUs immer ganz belegt (Entscheidung #1052, Risiko #1047).
const EXCLUSIVE_ENGINE: &str = "maya";
/// Engines, die ihre GPUs immer ganz belegen (Entscheidung #1052, Risiko
/// #1047; Strata gemessen am 16.11.2026: beide GPUs mit je etwa 11,5 GB).
fn is_exclusive(engine: &str) -> bool {
matches!(engine, "maya" | "strata")
}
/// Wie oft eine Anfrage neu eingereiht wird, wenn ihre Instanz verschwindet.
const MAX_ATTEMPTS: u32 = 3;
@ -460,7 +463,7 @@ impl Shared {
}
fn need(&self, plan: &StartPlan) -> Need {
let exclusive = plan.engine_name == EXCLUSIVE_ENGINE;
let exclusive = is_exclusive(&plan.engine_name);
Need {
model: plan.model.clone(),
gpus: plan.gpus.clone(),

View File

@ -45,6 +45,8 @@ pub struct Config {
pub ollama: toml::Table,
/// Rohe Einstellungen des Maya-Adapters (Abschnitt `[maya]`).
pub maya: toml::Table,
/// Rohe Einstellungen des Strata-Adapters (Abschnitt `[strata]`).
pub strata: toml::Table,
}
/// Einstellungen des Schedulers (Entscheidungen #1051 bis #1056).
@ -101,6 +103,7 @@ impl Default for Config {
llama_cpp: toml::Table::new(),
ollama: toml::Table::new(),
maya: toml::Table::new(),
strata: toml::Table::new(),
}
}
}

View File

@ -13,6 +13,8 @@ pub const LLAMA_CPP: &str = "llama.cpp";
pub const OLLAMA: &str = "ollama";
/// Name der Engine-Zeile für Maya.
pub const MAYA: &str = "maya";
/// Name der Engine-Zeile für Strata.
pub const STRATA: &str = "strata";
/// Eingabe für `register_llm`: ein Sprachmodell mit einem Startprofil.
#[derive(Debug, Clone)]
@ -77,9 +79,13 @@ impl Store {
if new.gpus.is_empty() {
return Err(Error::Db("mindestens eine GPU angeben".to_string()));
}
if new.engine != LLAMA_CPP && new.engine != OLLAMA && new.engine != MAYA {
if new.engine != LLAMA_CPP
&& new.engine != OLLAMA
&& new.engine != MAYA
&& new.engine != STRATA
{
return Err(Error::Db(format!(
"unbekannte Engine \"{}\" (llama.cpp, ollama oder maya)",
"unbekannte Engine \"{}\" (llama.cpp, ollama, maya oder strata)",
new.engine
)));
}
@ -428,6 +434,19 @@ mod tests {
);
}
#[test]
fn strata_modell_hat_die_konfigurationsdatei_als_pfad_und_eigene_engine() {
let mut store = Store::open_in_memory().unwrap();
let mut n = neu("qwen");
n.engine = "strata".to_string();
n.path = PathBuf::from("/home/svc-scotty/.local/share/strata/install/strata-q2_0.json");
n.gpus = vec![0, 1];
store.register_llm(&n).unwrap();
let plan = store.start_plan("qwen").unwrap().unwrap();
assert_eq!(plan.engine_name, "strata");
assert_eq!(plan.gpus, vec![0, 1]);
}
#[test]
fn unbekannte_engine_wird_abgelehnt() {
let mut store = Store::open_in_memory().unwrap();

View File

@ -171,6 +171,7 @@ fn model_add(args: &[String]) -> Result<(), String> {
"path",
"tag",
"maya-config",
"strata-config",
"gpus",
"context",
"vram-mb",
@ -203,9 +204,17 @@ fn model_add(args: &[String]) -> Result<(), String> {
}
(path, None)
}
// Strata: dasselbe, die Konfigurationsdatei des Strata-Terminals.
"strata" => {
let path = PathBuf::from(flags.require("strata-config")?);
if !path.is_file() {
return Err(format!("{} ist keine Datei.", path.display()));
}
(path, None)
}
other => {
return Err(format!(
"Unbekannte Engine \"{other}\" (llama.cpp, ollama oder maya)."
"Unbekannte Engine \"{other}\" (llama.cpp, ollama, maya oder strata)."
));
}
};
@ -372,9 +381,14 @@ async fn model_discover(args: &[String]) -> Result<(), String> {
.discover()
.await
}
"strata" => {
MayaEngine::strata(crate::serve::strata_config(&config)?)
.discover()
.await
}
other => {
return Err(format!(
"Unbekannte Engine \"{other}\" (llama.cpp, ollama oder maya)."
"Unbekannte Engine \"{other}\" (llama.cpp, ollama, maya oder strata)."
));
}
}
@ -397,6 +411,8 @@ async fn model_discover(args: &[String]) -> Result<(), String> {
"--engine ollama --tag <modellname>"
} else if engine == "maya" {
"--engine maya --maya-config <pfad>"
} else if engine == "strata" {
"--engine strata --strata-config <pfad>"
} else {
"--path <pfad>"
}

View File

@ -286,6 +286,7 @@ fn log_dirs(config: &Config) -> Vec<PathBuf> {
crate::serve::llama_config(config).map(|c| c.log_dir),
crate::serve::ollama_config(config).map(|c| c.log_dir),
crate::serve::maya_config(config).map(|c| c.log_dir),
crate::serve::strata_config(config).map(|c| c.log_dir),
]
.into_iter()
.flatten()

View File

@ -25,8 +25,9 @@ Aufruf:
nexus model add --name N --path PFAD [--gpus 0,1] [--context N] [--vram-mb N] [--ram-mb N] [--idle-min N] [--quant Q] [--disabled]
nexus model add --name N --engine ollama --tag MODELLNAME [--gpus 0] [--disabled]
nexus model add --name N --engine maya --maya-config PFAD.json [--gpus 0,1] [--disabled]
nexus model add --name N --engine strata --strata-config PFAD.json [--gpus 0,1] [--disabled]
nexus model set --name N [--vram-mb N] [--idle-min MINUTEN (0 = nie) | --idle-default]
nexus model list | enable --name N | disable --name N | discover [--engine llama.cpp|ollama|maya]
nexus model list | enable --name N | disable --name N | discover [--engine llama.cpp|ollama|maya|strata]
nexus diag [--out DATEI.tar.gz] [--ohne-engine-logs] Diagnose-Archiv ohne Prompts und Keys
nexus backup [--out DATEI.db] Kopie der Datenbank (ohne sie zu migrieren; auch bei laufendem Gateway)
nexus help Diese Hilfe

View File

@ -78,6 +78,38 @@ pub fn runtime_options(config: &Config) -> RuntimeOptions {
}
}
/// Liest den Abschnitt `[strata]`. Ohne Angaben gelten die Pfade des
/// Strata-Terminals von `svc-scotty` und der Port-Bereich 18500 bis 18599.
pub fn strata_config(config: &Config) -> Result<MayaConfig, String> {
let mut table = config.strata.clone();
let base = "/home/svc-scotty/.local/share/strata";
for (key, value) in [
(
"python",
toml::Value::String(format!("{base}/terminal/current/python/bin/python3.12")),
),
(
"script",
toml::Value::String(format!("{base}/terminal/current/serve/server.py")),
),
(
"config_roots",
toml::Value::Array(vec![toml::Value::String(format!("{base}/install"))]),
),
("port_from", toml::Value::Integer(18500)),
("port_to", toml::Value::Integer(18599)),
(
"log_dir",
toml::Value::String(config.data_dir.join("logs").display().to_string()),
),
] {
table.entry(key).or_insert(value);
}
table
.try_into::<MayaConfig>()
.map_err(|e| format!("Konfiguration [strata]: {e}"))
}
pub async fn command(args: &[String]) -> ExitCode {
match run(args).await {
Ok(()) => ExitCode::SUCCESS,
@ -107,6 +139,10 @@ async fn run(args: &[String]) -> Result<(), String> {
"maya".to_string(),
Arc::new(MayaEngine::new(maya_config(&config)?)),
);
engines.insert(
"strata".to_string(),
Arc::new(MayaEngine::strata(strata_config(&config)?)),
);
let state = AppState::new(
store,
Runtime::with_options(engines, runtime_options(&config)),
@ -211,6 +247,7 @@ fn spawn_background_jobs(
llama_config(config)?.log_dir,
ollama_config(config)?.log_dir,
maya_config(config)?.log_dir,
strata_config(config)?.log_dir,
];
dirs.sort();
dirs.dedup();