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:
130
Cargo.lock
generated
130
Cargo.lock
generated
@ -2,12 +2,29 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 4
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "async-trait"
|
||||||
|
version = "0.1.92"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bitflags"
|
name = "bitflags"
|
||||||
version = "2.13.2"
|
version = "2.13.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytes"
|
||||||
|
version = "1.12.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cc"
|
name = "cc"
|
||||||
version = "1.11.1"
|
version = "1.11.1"
|
||||||
@ -24,6 +41,16 @@ version = "1.0.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "errno"
|
||||||
|
version = "0.3.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fallible-iterator"
|
name = "fallible-iterator"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
@ -82,6 +109,12 @@ dependencies = [
|
|||||||
"hashbrown 0.17.1",
|
"hashbrown 0.17.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libc"
|
||||||
|
version = "0.2.191"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libsqlite3-sys"
|
name = "libsqlite3-sys"
|
||||||
version = "0.35.0"
|
version = "0.35.0"
|
||||||
@ -93,6 +126,17 @@ dependencies = [
|
|||||||
"vcpkg",
|
"vcpkg",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mio"
|
||||||
|
version = "1.2.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"wasi",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nexus"
|
name = "nexus"
|
||||||
version = "0.1.0-dev"
|
version = "0.1.0-dev"
|
||||||
@ -101,6 +145,18 @@ dependencies = [
|
|||||||
"nexus-store",
|
"nexus-store",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "nexus-adapter"
|
||||||
|
version = "0.1.0-dev"
|
||||||
|
dependencies = [
|
||||||
|
"async-trait",
|
||||||
|
"libc",
|
||||||
|
"serde",
|
||||||
|
"thiserror",
|
||||||
|
"tokio",
|
||||||
|
"toml",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nexus-core"
|
name = "nexus-core"
|
||||||
version = "0.1.0-dev"
|
version = "0.1.0-dev"
|
||||||
@ -118,6 +174,12 @@ dependencies = [
|
|||||||
"rusqlite",
|
"rusqlite",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pin-project-lite"
|
||||||
|
version = "0.2.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pkg-config"
|
name = "pkg-config"
|
||||||
version = "0.3.34"
|
version = "0.3.34"
|
||||||
@ -201,12 +263,32 @@ version = "2.0.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "signal-hook-registry"
|
||||||
|
version = "1.4.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||||
|
dependencies = [
|
||||||
|
"errno",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "smallvec"
|
name = "smallvec"
|
||||||
version = "1.16.5"
|
version = "1.16.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
|
checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "socket2"
|
||||||
|
version = "0.6.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "3.0.10"
|
version = "3.0.10"
|
||||||
@ -238,6 +320,33 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio"
|
||||||
|
version = "1.54.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"libc",
|
||||||
|
"mio",
|
||||||
|
"pin-project-lite",
|
||||||
|
"signal-hook-registry",
|
||||||
|
"socket2",
|
||||||
|
"tokio-macros",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio-macros"
|
||||||
|
version = "2.7.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml"
|
name = "toml"
|
||||||
version = "0.9.12+spec-1.1.0"
|
version = "0.9.12+spec-1.1.0"
|
||||||
@ -289,6 +398,27 @@ version = "0.2.15"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasi"
|
||||||
|
version = "0.11.1+wasi-snapshot-preview1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-link"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.61.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "0.7.15"
|
version = "0.7.15"
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
members = ["crates/nexus-core", "crates/nexus-store", "crates/nexus"]
|
members = ["crates/nexus-core", "crates/nexus-store", "crates/nexus-adapter", "crates/nexus"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0-dev"
|
version = "0.1.0-dev"
|
||||||
@ -11,6 +11,10 @@ repository = "ssh://git@git.wlkns.org:2222/wlkns-dev/nexus.git"
|
|||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
nexus-core = { path = "crates/nexus-core" }
|
nexus-core = { path = "crates/nexus-core" }
|
||||||
nexus-store = { path = "crates/nexus-store" }
|
nexus-store = { path = "crates/nexus-store" }
|
||||||
|
nexus-adapter = { path = "crates/nexus-adapter" }
|
||||||
|
async-trait = "0.1"
|
||||||
|
libc = "0.2"
|
||||||
|
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time", "net", "io-util", "sync", "fs"] }
|
||||||
rusqlite = { version = "0.37", features = ["bundled"] }
|
rusqlite = { version = "0.37", features = ["bundled"] }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
|
|||||||
@ -22,7 +22,7 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
|
|||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| #1001 | M0 Assessment srv04: Hardware, Engines, Modelle, Startmechanismen, Betriebszustand | Projektauftrag §14 | ✓ | Bericht `docs/m0-bestandsbericht.md` am 09.11.2026 von dir freigegeben (`srv042bericht.1`). Bekannte Lücken: User-Units von svc-scotty, API-Fähigkeiten der Engines (→ #1030). |
|
| #1001 | M0 Assessment srv04: Hardware, Engines, Modelle, Startmechanismen, Betriebszustand | Projektauftrag §14 | ✓ | Bericht `docs/m0-bestandsbericht.md` am 09.11.2026 von dir freigegeben (`srv042bericht.1`). Bekannte Lücken: User-Units von svc-scotty, API-Fähigkeiten der Engines (→ #1030). |
|
||||||
| #1002 | M1 Architektur und Spezifikation: Zielarchitektur, Adaptervertrag, Datenmodell, Scheduler-, Sicherheits-, Logging-Konzept, Teststrategie | Projektauftrag §14 | ✓ | `docs/m1-spezifikation.md` am 09.11.2026 von dir freigegeben (`spezifikation2freigabe.1`). Nur Planung: Protokolle von Strata und Maya sind nicht gemessen, der Build-Weg des Binarys (E8) ist offen. |
|
| #1002 | M1 Architektur und Spezifikation: Zielarchitektur, Adaptervertrag, Datenmodell, Scheduler-, Sicherheits-, Logging-Konzept, Teststrategie | Projektauftrag §14 | ✓ | `docs/m1-spezifikation.md` am 09.11.2026 von dir freigegeben (`spezifikation2freigabe.1`). Nur Planung: Protokolle von Strata und Maya sind nicht gemessen, der Build-Weg des Binarys (E8) ist offen. |
|
||||||
| #1003 | M2 Gateway-Kern: OpenAI-kompatible API, Model Registry, Engine-Adapter (Managed, External, Attached), API-Key-Authentifizierung, Lifecycle | Projektauftrag §3, §4, §7, §10 | ◐ | M2.1 (Grundgerüst, Konfiguration, Datenbank, Selbsttest) gebaut und mit Einheitentests geprüft (#1031). Adapter, API, Deployment fehlen. |
|
| #1003 | M2 Gateway-Kern: OpenAI-kompatible API, Model Registry, Engine-Adapter (Managed, External, Attached), API-Key-Authentifizierung, Lifecycle | Projektauftrag §3, §4, §7, §10 | ◐ | M2.1 (Grundgerüst, #1031) und M2.2 (Adaptervertrag, llama.cpp-Adapter, Attrappe, #1032) gebaut und mit Tests geprüft. API, Logging, Deployment fehlen. |
|
||||||
| #1004 | M3 Scheduler und Queue: Ressourcenplanung (VRAM, RAM, CPU), Parallelbetrieb, persistente Jobs, Prioritäten HIGH, NORMAL, LOW, VIP-Verdrängung, Aging | Projektauftrag §5, §6 | ✗ | Nichts gebaut. |
|
| #1004 | M3 Scheduler und Queue: Ressourcenplanung (VRAM, RAM, CPU), Parallelbetrieb, persistente Jobs, Prioritäten HIGH, NORMAL, LOW, VIP-Verdrängung, Aging | Projektauftrag §5, §6 | ✗ | Nichts gebaut. |
|
||||||
| #1005 | M4 ComfyUI: freigegebene Workflows, asynchrone Jobs, Workflow Registry, Bildendpunkte | Projektauftrag §8 | ✗ | Nichts gebaut. |
|
| #1005 | M4 ComfyUI: freigegebene Workflows, asynchrone Jobs, Workflow Registry, Bildendpunkte | Projektauftrag §8 | ✗ | Nichts gebaut. |
|
||||||
| #1006 | M5 Weboberfläche und Client: Dashboard, Administration, Playground, Benutzeranmeldung, installierbare PWA | Projektauftrag §9 | ✗ | Nichts gebaut. |
|
| #1006 | M5 Weboberfläche und Client: Dashboard, Administration, Playground, Benutzeranmeldung, installierbare PWA | Projektauftrag §9 | ✗ | Nichts gebaut. |
|
||||||
@ -37,7 +37,6 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
|
|||||||
## 4. Todo (nach Priorität, Stand 2026-11-09)
|
## 4. Todo (nach Priorität, Stand 2026-11-09)
|
||||||
|
|
||||||
**P1 – als Nächstes**
|
**P1 – als Nächstes**
|
||||||
- [#1032] **M2.2 Adapter und Attrappe.** Adaptervertrag, Attrappen-Engine, llama.cpp-Adapter mit Rezept (Managed). Tests: Einheitentests, Attrappen-Lauf. → #1003
|
|
||||||
- [#1033] **M2.3 API.** `GET /v1/models`, Chat-Completions mit SSE-Streaming, API-Keys, OpenAI-Fehlerformat. Tests: SDK-Tests gegen die Attrappe, `client2antwort.1` und `.3`. → #1003
|
- [#1033] **M2.3 API.** `GET /v1/models`, Chat-Completions mit SSE-Streaming, API-Keys, OpenAI-Fehlerformat. Tests: SDK-Tests gegen die Attrappe, `client2antwort.1` und `.3`. → #1003
|
||||||
- [#1034] **M2.4 Logging.** JSON-Logs, Correlation-IDs, Prüfung, dass keine Prompts und Keys im Log stehen. Tests: Log-Test, `client2antwort.3`. → #1007
|
- [#1034] **M2.4 Logging.** JSON-Logs, Correlation-IDs, Prüfung, dass keine Prompts und Keys im Log stehen. Tests: Log-Test, `client2antwort.3`. → #1007
|
||||||
- [#1035] **M2.5 Deployment auf srv04.** musl-Binary, systemd-Dienst `nexus.service` unter `svc-scotty`, echter llama.cpp-Lauf. Tests: `client2antwort.1–.3` auf srv04. → #1003
|
- [#1035] **M2.5 Deployment auf srv04.** musl-Binary, systemd-Dienst `nexus.service` unter `svc-scotty`, echter llama.cpp-Lauf. Tests: `client2antwort.1–.3` auf srv04. → #1003
|
||||||
@ -63,6 +62,8 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
|
|||||||
|
|
||||||
- [#1031] **M2.1 Grundgerüst** – erledigt am 09.11.2026. Workspace mit `nexus-core`, `nexus-store`, `nexus`; Konfiguration, SQLite-Schema mit Migration 1 (alle Tabellen aus der Spezifikation), `nexus selftest`. 18 Einheitentests grün, `clippy -D warnings` sauber, Selbsttest im echten Lauf bestanden (4 Prüfungen, Exit 0, falscher Pfad Exit 1). musl-Binary baut, statisch gelinkt, 2,8 MB. Nicht geprüft: Lauf des musl-Binarys auf srv04 (kommt mit #1035). Keine Klicktests, wie im Todo vorgesehen.
|
- [#1031] **M2.1 Grundgerüst** – erledigt am 09.11.2026. Workspace mit `nexus-core`, `nexus-store`, `nexus`; Konfiguration, SQLite-Schema mit Migration 1 (alle Tabellen aus der Spezifikation), `nexus selftest`. 18 Einheitentests grün, `clippy -D warnings` sauber, Selbsttest im echten Lauf bestanden (4 Prüfungen, Exit 0, falscher Pfad Exit 1). musl-Binary baut, statisch gelinkt, 2,8 MB. Nicht geprüft: Lauf des musl-Binarys auf srv04 (kommt mit #1035). Keine Klicktests, wie im Todo vorgesehen.
|
||||||
|
|
||||||
|
- [#1032] **M2.2 Adapter und Attrappe** – erledigt am 09.11.2026. Neues Crate `nexus-adapter`: Vertrag `Engine`, `LlamaCppEngine` (Managed, Rezept aus Konfiguration, Log-Erfassung, Bereitschaft über `/health`, Beenden, Messung), `MockEngine`. 48 Tests im Workspace grün (30 im Adapter, davon 9 Integrationstests mit echten Prozessen gegen eine Attrappe von `llama-server`), `clippy -D warnings` sauber, 5 Wiederholungen ohne Ausfall. Auf srv04 gemessen (Bonsai-1.7B, mit dem Start aus #1040): `/health` 503 dann 200, OpenAI-Chat antwortet, VRAM pro PID messbar, `SIGTERM` beendet sauber. Nicht geprüft: der Adapter-Code selbst auf srv04 (kommt mit #1035), große Modelle, Embeddings, `forward` (kommt mit #1033).
|
||||||
|
|
||||||
**Erledigt am 09.11.2026:** M1 freigegeben, Release `v0.0.1` gebaut, M0 freigegeben, Projekt mit `init.sh` angelegt (Git-Repo, ROADMAP, KLICKTESTS, README, AGENTS), Roadmap aus dem Projektauftrag befüllt.
|
**Erledigt am 09.11.2026:** M1 freigegeben, Release `v0.0.1` gebaut, M0 freigegeben, Projekt mit `init.sh` angelegt (Git-Repo, ROADMAP, KLICKTESTS, README, AGENTS), Roadmap aus dem Projektauftrag befüllt.
|
||||||
|
|
||||||
## 5. Offene Entscheidungen bei dir
|
## 5. Offene Entscheidungen bei dir
|
||||||
@ -95,5 +96,5 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
|
|||||||
- [#1023] Die Schnittstellen und Fähigkeiten der Engines Strata, Maya und Ollama sind in diesem Auftrag nicht beschrieben. Der Adaptervertrag kann erst nach M0 sinnvoll entworfen werden.
|
- [#1023] Die Schnittstellen und Fähigkeiten der Engines Strata, Maya und Ollama sind in diesem Auftrag nicht beschrieben. Der Adaptervertrag kann erst nach M0 sinnvoll entworfen werden.
|
||||||
- [#1024] Vorhandene Startmechanismen (Makefiles, Skripte, systemd) sind unbekannt. Managed-Betrieb könnte bestehende Abläufe stören.
|
- [#1024] Vorhandene Startmechanismen (Makefiles, Skripte, systemd) sind unbekannt. Managed-Betrieb könnte bestehende Abläufe stören.
|
||||||
- [#1029] Das Strata-Makefile startet den Server mit `--no-api-key --access lan` auf Port 8082. Läuft er so, ist er im LAN ohne Schlüssel erreichbar. Nur gelesen, nicht ausgeführt; zum Messzeitpunkt lauschte nichts.
|
- [#1029] Das Strata-Makefile startet den Server mit `--no-api-key --access lan` auf Port 8082. Läuft er so, ist er im LAN ohne Schlüssel erreichbar. Nur gelesen, nicht ausgeführt; zum Messzeitpunkt lauschte nichts.
|
||||||
- [#1030] Nicht geklärt: die systemd-User-Units von `svc-scotty`, ein Webdienst „Oberon Control“ auf `127.0.0.1:8750` (Prozess `/usr/bin/oberon-agent`, läuft als `svc-scotty` und `stephan`; Zweck nur aus dem Seitentitel bekannt) und die echten API-Fähigkeiten der Engines. Der Adaptervertrag in M1 ruht darauf.
|
- [#1030] Nicht geklärt: die systemd-User-Units von `svc-scotty`, ein Webdienst „Oberon Control“ auf `127.0.0.1:8750` (Prozess `/usr/bin/oberon-agent`, läuft als `svc-scotty` und `stephan`; Zweck nur aus dem Seitentitel bekannt) und die echten API-Fähigkeiten der Engines (für llama.cpp am 09.11.2026 teilweise gemessen: `/health`, `/v1/models`, Chat; offen für Embeddings und Tool Calling sowie für Maya, Strata, Ollama). Der Adaptervertrag in M1 ruht darauf.
|
||||||
- [#1025] Der Umfang ist groß (Scheduler mit Verdrängung, Aging, Queue, ComfyUI, PWA). Gefahr, in M2 und M3 zu viel auf einmal zu bauen; M1 soll Vereinfachungen vorschlagen.
|
- [#1025] Der Umfang ist groß (Scheduler mit Verdrängung, Aging, Queue, ComfyUI, PWA). Gefahr, in M2 und M3 zu viel auf einmal zu bauen; M1 soll Vereinfachungen vorschlagen.
|
||||||
|
|||||||
17
crates/nexus-adapter/Cargo.toml
Normal file
17
crates/nexus-adapter/Cargo.toml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
[package]
|
||||||
|
name = "nexus-adapter"
|
||||||
|
description = "Nexus: Engine-Adaptervertrag, Prozesssteuerung und Adapter"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
async-trait.workspace = true
|
||||||
|
libc.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
toml.workspace = true
|
||||||
|
tokio = { workspace = true, features = ["test-util"] }
|
||||||
24
crates/nexus-adapter/README.md
Normal file
24
crates/nexus-adapter/README.md
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
# nexus-adapter
|
||||||
|
|
||||||
|
Engine-Adaptervertrag, Prozesssteuerung und Adapter (Spezifikation, Abschnitt 4).
|
||||||
|
|
||||||
|
**Version:** wie der Workspace (`0.1.0-dev`).
|
||||||
|
|
||||||
|
## Schnittstelle
|
||||||
|
Trait `Engine` (async): `describe`, `discover`, `start`, `stop`, `health`, `endpoint`, `measure`. `stop` ist idempotent. `start` kehrt erst zurück, wenn die Instanz bereit ist oder der Start gescheitert ist. Fehlerarten (`AdapterError`): `InvalidProfile`, `Spawn`, `ExitedEarly` (mit Exit-Code und Log-Ende), `NotReady`, `NoFreePort`, `Stop`, `Io`.
|
||||||
|
|
||||||
|
`forward` (Anfragen durchreichen) kommt mit der API in M2.3; bis dahin liefert `endpoint` die Basis-URL.
|
||||||
|
|
||||||
|
## Adapter
|
||||||
|
- **`LlamaCppEngine`** (Managed): startet `llama-server` auf `127.0.0.1`, GPU-Auswahl über `CUDA_VISIBLE_DEVICES`, stdout und stderr gehen in `log_dir/instance-<id>.log`, Bereitschaft über `GET /health`, Beenden mit `SIGTERM` und nach der Gnadenfrist `SIGKILL`, Messung von VRAM (`nvidia-smi` pro PID) und RAM (`/proc/<pid>/status`). `discover` findet `.gguf`-Modelle, überspringt `mmproj*`, `*vocab*` und `mtp*`, fasst geteilte Dateien zusammen und liest die Quantisierung aus dem Dateinamen.
|
||||||
|
- **`MockEngine`**: Attrappe ohne Prozesse mit einstellbarer Ladezeit, Fehlern und Ressourcenbedarf, für Scheduler- und Vertragstests. Ein grüner Test gegen die Attrappe heißt „verhält sich wie gebaut“, nicht „Gesamtweg läuft“.
|
||||||
|
|
||||||
|
## Was gemessen ist (09.11.2026, srv04, `llama-server` Version b1-cd959ba, Modell Bonsai-1.7B)
|
||||||
|
- `GET /health`: zuerst 503, nach etwa 2 bis 3 s 200 mit `{"status":"ok"}`.
|
||||||
|
- `GET /v1/models` und `POST /v1/chat/completions` antworten im OpenAI-Format.
|
||||||
|
- Die GPU wurde durch `nvidia-smi --query-compute-apps` pro PID gemessen (638 MiB), RAM über `VmRSS` (rund 500 MB).
|
||||||
|
- `SIGTERM` beendet den Server sauber, der GPU-Speicher ist danach frei.
|
||||||
|
- **Nicht gemessen:** Verhalten großer Modelle (Ladezeit, RAM-Auslagerung), Embeddings, Tool Calling, der Adapter selbst auf srv04 (kommt mit M2.5).
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
`cargo test -p nexus-adapter`: Einheitentests (Kommandozeile, Parser, Port-Pool, Suche, Attrappe) und Integrationstests mit echten Prozessen gegen `tests/fake_llama_server.py` (Start, Bereitschaft, Log, Beenden, sturer Prozess, Absturz, Zeitüberschreitung, fehlendes Programm, zwei Instanzen). Die Integrationstests brauchen `python3`.
|
||||||
36
crates/nexus-adapter/src/engine.rs
Normal file
36
crates/nexus-adapter/src/engine.rs
Normal 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;
|
||||||
|
}
|
||||||
24
crates/nexus-adapter/src/lib.rs
Normal file
24
crates/nexus-adapter/src/lib.rs
Normal 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,
|
||||||
|
};
|
||||||
635
crates/nexus-adapter/src/llama.rs
Normal file
635
crates/nexus-adapter/src/llama.rs
Normal 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")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
228
crates/nexus-adapter/src/mock.rs
Normal file
228
crates/nexus-adapter/src/mock.rs
Normal 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(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
161
crates/nexus-adapter/src/process.rs
Normal file
161
crates/nexus-adapter/src/process.rs
Normal 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
120
crates/nexus-adapter/src/types.rs
Normal file
120
crates/nexus-adapter/src/types.rs
Normal 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>;
|
||||||
60
crates/nexus-adapter/tests/fake_llama_server.py
Executable file
60
crates/nexus-adapter/tests/fake_llama_server.py
Executable file
@ -0,0 +1,60 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Attrappe für llama-server, nur für Tests von nexus-adapter.
|
||||||
|
|
||||||
|
Versteht die Argumente, die der Adapter übergibt (-m, --host, --port, ...),
|
||||||
|
und verhält sich nach FAKE_LLAMA_MODE:
|
||||||
|
ok antwortet auf /health zuerst mit 503, nach FAKE_LLAMA_LOAD_SECONDS mit 200
|
||||||
|
crash schreibt einen Fehler nach stderr und endet mit Exit-Code 3
|
||||||
|
hang wird nie bereit (immer 503)
|
||||||
|
stubborn wie ok, ignoriert aber SIGTERM (zwingt den Adapter zum harten Beenden)
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
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_LLAMA_MODE", "ok")
|
||||||
|
print("fake-llama: pid", os.getpid(), flush=True)
|
||||||
|
print("fake-llama: args", " ".join(args), flush=True)
|
||||||
|
print("fake-llama: CUDA_VISIBLE_DEVICES=" + os.environ.get("CUDA_VISIBLE_DEVICES", "<unset>"), flush=True)
|
||||||
|
|
||||||
|
if mode == "crash":
|
||||||
|
print("fake-llama: error: failed to load model", file=sys.stderr, flush=True)
|
||||||
|
sys.exit(3)
|
||||||
|
|
||||||
|
if mode == "stubborn":
|
||||||
|
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||||
|
else:
|
||||||
|
signal.signal(signal.SIGTERM, lambda *_: os._exit(0))
|
||||||
|
|
||||||
|
started = time.time()
|
||||||
|
load_seconds = float(os.environ.get("FAKE_LLAMA_LOAD_SECONDS", "1"))
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, *_):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
if self.path == "/health":
|
||||||
|
ready = mode in ("ok", "stubborn") and time.time() - started >= load_seconds
|
||||||
|
code = 200 if ready else 503
|
||||||
|
body = b'{"status":"ok"}' if ready else b'{"error":{"message":"Loading model"}}'
|
||||||
|
else:
|
||||||
|
code, body = 404, b"{}"
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
ThreadingHTTPServer((opt("--host"), int(opt("--port"))), Handler).serve_forever()
|
||||||
227
crates/nexus-adapter/tests/llama_process.rs
Normal file
227
crates/nexus-adapter/tests/llama_process.rs
Normal file
@ -0,0 +1,227 @@
|
|||||||
|
//! 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 {
|
||||||
|
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"));
|
||||||
|
}
|
||||||
@ -50,6 +50,7 @@ trait Engine {
|
|||||||
async fn measure(&self, inst: &InstanceHandle) -> Usage; // VRAM und RAM
|
async fn measure(&self, inst: &InstanceHandle) -> Usage; // VRAM und RAM
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
- **Stand der Umsetzung (M2.2):** `forward` ist noch nicht im Trait; es kommt mit der API (M2.3). Bis dahin liefert `endpoint` die Basis-URL.
|
||||||
- **Betriebsmodi:** *Managed* (Gateway startet und stoppt über ein Rezept), *External* (nur `health` und `endpoint`), *Attached* (wie External, plus Laden und Entladen über die Engine-API, falls vorhanden, zum Beispiel Ollama).
|
- **Betriebsmodi:** *Managed* (Gateway startet und stoppt über ein Rezept), *External* (nur `health` und `endpoint`), *Attached* (wie External, plus Laden und Entladen über die Engine-API, falls vorhanden, zum Beispiel Ollama).
|
||||||
- **Rezept:** Befehl, Argumente, Arbeitsverzeichnis, Umgebungsvariablen (Verweise auf Geheimnisdateien, nie Werte), Port-Bereich, Bereitschaftsprüfung (URL und Zeitlimit), Stop-Signal. Vorhandene Makefiles und Skripte werden aufgerufen, nicht ersetzt (E2).
|
- **Rezept:** Befehl, Argumente, Arbeitsverzeichnis, Umgebungsvariablen (Verweise auf Geheimnisdateien, nie Werte), Port-Bereich, Bereitschaftsprüfung (URL und Zeitlimit), Stop-Signal. Vorhandene Makefiles und Skripte werden aufgerufen, nicht ersetzt (E2).
|
||||||
- **Protokoll:** Standard ist OpenAI-HTTP, `forward` reicht Anfrage und Antwort durch. Engines mit eigenem Protokoll (ComfyUI, ACE-Step später) übersetzen im Adapter.
|
- **Protokoll:** Standard ist OpenAI-HTTP, `forward` reicht Anfrage und Antwort durch. Engines mit eigenem Protokoll (ComfyUI, ACE-Step später) übersetzen im Adapter.
|
||||||
|
|||||||
Reference in New Issue
Block a user