Files
nexus/crates/nexus-store/src/lib.rs
wlkns-dev d95e60e64d feat(dashboard): Warnregeln, Speicher und Auswertung für Warnungen (DASH-R4, Arbeitspakete 1 bis 3, #1216)
- alarm.rs: sechs Regeln aus den Gründen des Gesamtzustands (dieselben Schwellen), Zustandsautomat mit Mindestdauer
  (drei Proben) und Hysterese (fünf Proben), Schonfrist nach dem Start
- Migration 17: Tabelle warnung (eine offene je Knoten, Regel, Komponente), Quittieren, Stummschalten, Aufbewahrung 90 Tage
- Auswertung einmal je Minute im Hintergrund, schreibt Warnungen und die Ereignisse warnung_ausgeloest und warnung_beendet
- Eingabe für den Gesamtzustand gemeinsam für Übersicht und Warnungen

Noch nicht gebaut: Routen, Oberfläche, Aktion Modell entladen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 11:48:49 +01:00

564 lines
20 KiB
Rust

//! SQLite-Speicher für Nexus: Datei öffnen, Migrationen anwenden, prüfen.
//!
//! Die Migrationen liegen in `migrations/` und sind nur vorwärts gerichtet.
//! Der Stand steht in `PRAGMA user_version`. Wer eine ältere Datenbank öffnet,
//! bekommt sie automatisch auf den neuesten Stand; eine Datenbank von einer
//! neueren Version wird abgelehnt.
use std::path::Path;
use nexus_core::{Error, Result};
use rusqlite::Connection;
mod auswertung;
mod historie;
mod keys;
mod logs;
mod logsearch;
mod reihen;
pub use chats::ChatSave;
pub use logsearch::{LogFilter, LogRecord};
mod chats;
mod ereignisse;
mod warnungen;
pub use ereignisse::{AUFBEWAHRUNG_TAGE, Ereignis, MAX_EREIGNISSE, NeuesEreignis};
pub use warnungen::{NeueWarnung, WARNUNG_AUFBEWAHRUNG_TAGE, Warnung, WarnungAntwort};
mod personas;
mod registry;
pub use personas::Persona;
mod startprofiles;
mod users;
mod voices;
pub use auswertung::{RequestSummary, SummaryGroup};
pub use historie::{
MAX_FENSTER_MS, MAX_PUNKTE, MAX_REIHEN, MIN_FENSTER_MS, Punkt, PurgeStand, RollupStand,
Verlauf, VerlaufReihe,
};
pub use keys::{ApiKeyRecord, RemoveKeyOutcome, Rights};
pub use logs::{AuditRow, RequestCounts, RequestLogEntry, RequestLogRow, RequestView};
pub use registry::{ModelDetails, ModelEntry, NewLlm, RemoveOutcome, StartPlan};
pub use reihen::{Aggregation, ReiheInfo, alle_reihen, reihe_info};
pub use users::{UserRecord, UserRole};
/// Alle Migrationen in Reihenfolge. Index 0 ergibt Schema-Version 1.
const MIGRATIONS: &[&str] = &[
include_str!("../migrations/0001_init.sql"),
include_str!("../migrations/0002_logging.sql"),
include_str!("../migrations/0003_metrikproben.sql"),
include_str!("../migrations/0004_scheduler.sql"),
include_str!("../migrations/0005_benutzer.sql"),
include_str!("../migrations/0006_auswertung.sql"),
include_str!("../migrations/0007_startprofile.sql"),
include_str!("../migrations/0008_stimmen.sql"),
include_str!("../migrations/0009_personas.sql"),
include_str!("../migrations/0010_denkstufe.sql"),
include_str!("../migrations/0011_vision.sql"),
include_str!("../migrations/0012_werkzeuge.sql"),
include_str!("../migrations/0013_embedding.sql"),
include_str!("../migrations/0014_chats.sql"),
include_str!("../migrations/0015_historie.sql"),
include_str!("../migrations/0016_ereignisse.sql"),
include_str!("../migrations/0017_warnungen.sql"),
];
/// Schema-Version, die dieses Crate erzeugt.
pub const LATEST_SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64;
/// Schreibt eine vollständige, in sich stimmige Kopie der Datenbank nach
/// `out` (`VACUUM INTO`). Die Datenbank wird nur lesend geöffnet und **nicht**
/// migriert, damit die Sicherung vor einem Update den alten Stand enthält.
/// Das geht auch, während das Gateway läuft. `out` darf noch nicht existieren.
pub fn backup_file(db_path: &std::path::Path, out: &std::path::Path) -> Result<()> {
if out.exists() {
return Err(Error::Db(format!("{} gibt es schon", out.display())));
}
if let Some(parent) = out.parent() {
std::fs::create_dir_all(parent).map_err(|source| Error::Io {
path: parent.to_path_buf(),
source,
})?;
}
let conn = rusqlite::Connection::open_with_flags(
db_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(db)?;
conn.execute("VACUUM INTO ?1", [out.display().to_string()])
.map_err(db)?;
Ok(())
}
pub(crate) fn db(e: rusqlite::Error) -> Error {
Error::Db(e.to_string())
}
/// Geöffnete Datenbank mit angewendeten Migrationen.
pub struct Store {
conn: Connection,
}
impl Store {
/// Öffnet (und erzeugt bei Bedarf) die Datenbankdatei und migriert sie.
/// Der Ordner der Datei muss existieren.
pub fn open(path: &Path) -> Result<Self> {
let conn = Connection::open(path).map_err(db)?;
conn.pragma_update(None, "journal_mode", "WAL")
.map_err(db)?;
Self::prepare(conn)
}
/// Öffnet die Datenbankdatei **nur lesend und ohne Migration** (für die Diagnose und Auswertungen, → #1175).
/// Weder Schema noch Daten ändern sich; eine ältere Datenbank bleibt für ihr altes Programm unverändert
/// nutzbar. Fehlende neuere Tabellen führen erst beim Lesen zu Fehlern, die der Aufrufer meldet.
pub fn open_readonly(path: &Path) -> Result<Self> {
let conn = Connection::open_with_flags(
path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(db)?;
conn.busy_timeout(std::time::Duration::from_secs(5))
.map_err(db)?;
Ok(Self { conn })
}
/// Öffnet eine Datenbank nur im Speicher (für Tests).
pub fn open_in_memory() -> Result<Self> {
Self::prepare(Connection::open_in_memory().map_err(db)?)
}
fn prepare(conn: Connection) -> Result<Self> {
conn.pragma_update(None, "foreign_keys", "ON").map_err(db)?;
conn.busy_timeout(std::time::Duration::from_secs(5))
.map_err(db)?;
let mut store = Self { conn };
store.migrate()?;
Ok(store)
}
pub(crate) fn transaction(&mut self) -> rusqlite::Result<rusqlite::Transaction<'_>> {
self.conn.transaction()
}
fn migrate(&mut self) -> Result<()> {
let current = self.schema_version()?;
if current > LATEST_SCHEMA_VERSION {
return Err(Error::Db(format!(
"Datenbank hat Schema-Version {current}, dieses Programm kennt nur {LATEST_SCHEMA_VERSION}"
)));
}
for (index, sql) in MIGRATIONS.iter().enumerate() {
let version = index as i64 + 1;
if version <= current {
continue;
}
let tx = self.conn.transaction().map_err(db)?;
tx.execute_batch(sql).map_err(db)?;
tx.pragma_update(None, "user_version", version)
.map_err(db)?;
tx.commit().map_err(db)?;
}
Ok(())
}
/// Aktuelle Schema-Version der geöffneten Datenbank.
pub fn schema_version(&self) -> Result<i64> {
self.conn
.pragma_query_value(None, "user_version", |row| row.get(0))
.map_err(db)
}
/// Führt SQLites Integritätsprüfung und die Fremdschlüsselprüfung aus.
pub fn integrity_check(&self) -> Result<()> {
let result: String = self
.conn
.pragma_query_value(None, "integrity_check", |row| row.get(0))
.map_err(db)?;
if result != "ok" {
return Err(Error::Db(format!("Integritätsprüfung: {result}")));
}
let mut stmt = self.conn.prepare("PRAGMA foreign_key_check").map_err(db)?;
let broken = stmt.query_map([], |_| Ok(())).map_err(db)?.count();
if broken > 0 {
return Err(Error::Db(format!("{broken} Fremdschlüssel verletzt")));
}
Ok(())
}
/// Zugriff auf die Verbindung für Abfragen anderer Module.
pub fn connection(&self) -> &Connection {
&self.conn
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
static ZAEHLER: AtomicU32 = AtomicU32::new(0);
/// Eigener Testordner ohne Zusatz-Abhängigkeit; wird am Ende entfernt.
struct Testordner(std::path::PathBuf);
impl Testordner {
fn neu() -> Self {
let n = ZAEHLER.fetch_add(1, Ordering::SeqCst);
let pfad =
std::env::temp_dir().join(format!("nexus-store-test-{}-{n}", std::process::id()));
std::fs::create_dir_all(&pfad).unwrap();
Self(pfad)
}
}
impl Drop for Testordner {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn nur_lesend_oeffnen_migriert_und_aendert_nichts() {
// #1175: Die Diagnose öffnet ein altes Schema (hier 7) ohne Migration; Schema und Daten bleiben bytegleich.
let ordner = Testordner::neu();
let pfad = ordner.0.join("alt.db");
{
let conn = Connection::open(&pfad).unwrap();
for sql in &MIGRATIONS[..7] {
conn.execute_batch(sql).unwrap();
}
conn.pragma_update(None, "user_version", 7).unwrap();
conn.execute(
"INSERT INTO audit (zeit, akteur, aktion) VALUES ('2026-11-01T00:00:00Z', 'cli', 'test')",
[],
)
.unwrap();
}
let vorher = std::fs::read(&pfad).unwrap();
{
let store = Store::open_readonly(&pfad).unwrap();
assert_eq!(store.schema_version().unwrap(), 7);
// Vorhandene Daten sind lesbar, spätere Tabellen fehlen und werden als Fehler gemeldet, nicht angelegt.
assert_eq!(store.recent_audit(10).unwrap().len(), 1);
assert!(
store
.connection()
.execute("CREATE TABLE x (a)", [])
.is_err()
);
assert!(store.connection().execute("DELETE FROM audit", []).is_err());
}
assert_eq!(std::fs::read(&pfad).unwrap(), vorher, "Datei unverändert");
// Ein Programm mit dem alten Schema kann sie weiter öffnen: Die Version ist unverändert 7.
let conn = Connection::open(&pfad).unwrap();
let v: i64 = conn
.pragma_query_value(None, "user_version", |r| r.get(0))
.unwrap();
assert_eq!(v, 7);
}
fn engine_einfuegen(store: &Store) -> i64 {
store
.connection()
.execute(
"INSERT INTO engine (name, art, modus) VALUES ('llama.cpp', 'llm', 'managed')",
[],
)
.unwrap();
store.connection().last_insert_rowid()
}
#[test]
fn schema_5_migriert_und_behaelt_alte_anfragen_ohne_erfundene_ladezahlen() {
let conn = Connection::open_in_memory().unwrap();
for sql in &MIGRATIONS[..5] {
conn.execute_batch(sql).unwrap();
}
conn.pragma_update(None, "user_version", 5).unwrap();
conn.execute("INSERT INTO anfrage_log (zeit, korrelation, status) VALUES ('2026-11-16T10:00:00Z', 'alt', 200)", []).unwrap();
let store = Store::prepare(conn).unwrap();
assert_eq!(store.schema_version().unwrap(), LATEST_SCHEMA_VERSION);
assert_eq!(store.recent_requests(10).unwrap().len(), 1);
assert!(!store.load_recording_since().unwrap().is_empty());
let count: i64 = store
.connection()
.query_row("SELECT COUNT(*) FROM lade_log", [], |r| r.get(0))
.unwrap();
assert_eq!(count, 0);
store.integrity_check().unwrap();
}
#[test]
fn schema_14_wird_mit_rohzeilen_auf_aktuelle_version_gehoben_und_ist_idempotent() {
let ordner = Testordner::neu();
let pfad = ordner.0.join("nexus.db");
{
let conn = Connection::open(&pfad).unwrap();
for sql in &MIGRATIONS[..14] {
conn.execute_batch(sql).unwrap();
}
conn.pragma_update(None, "user_version", 14).unwrap();
conn.execute(
"INSERT INTO metrik_probe (zeit, reihe, ziel, wert) VALUES ('2026-11-20T10:00:00Z', 'gpu_speicher_mb', 'gpu0', 4711.5)",
[],
)
.unwrap();
}
for durchlauf in 0..2 {
let store = Store::open(&pfad).unwrap();
assert_eq!(
store.schema_version().unwrap(),
LATEST_SCHEMA_VERSION,
"Durchlauf {durchlauf}"
);
let (node, wert): (String, f64) = store
.connection()
.query_row(
"SELECT node_id, wert FROM metrik_probe WHERE reihe = 'gpu_speicher_mb'",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert_eq!((node.as_str(), wert), ("local", 4711.5));
let anzahl: i64 = store
.connection()
.query_row("SELECT COUNT(*) FROM metrik_probe", [], |r| r.get(0))
.unwrap();
assert_eq!(anzahl, 1);
// Neue Tabelle und Index sind da; der alte Leser liefert die alte Zeile weiter.
store
.connection()
.query_row("SELECT COUNT(*) FROM metrik_rollup", [], |r| {
r.get::<_, i64>(0)
})
.unwrap();
let index: i64 = store
.connection()
.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE name = 'metrik_probe_knoten'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(index, 1);
assert_eq!(
store
.samples_since("gpu_speicher_mb", "2000-01-01T00:00:00Z")
.unwrap()
.len(),
1
);
store.integrity_check().unwrap();
}
}
#[test]
fn rollup_nach_migration_verdichtet_vorhandene_rohzeilen_des_lokalen_knotens() {
let conn = Connection::open_in_memory().unwrap();
for sql in &MIGRATIONS[..14] {
conn.execute_batch(sql).unwrap();
}
conn.pragma_update(None, "user_version", 14).unwrap();
for (z, w) in [
("2026-11-20T10:00:10Z", 10.0),
("2026-11-20T10:01:10Z", 20.0),
] {
conn.execute(
"INSERT INTO metrik_probe (zeit, reihe, ziel, wert) VALUES (?1, 'gpu_speicher_mb', 'gpu0', ?2)",
(z, w),
)
.unwrap();
}
let mut store = Store::prepare(conn).unwrap();
store.rollup("2026-11-20T10:30:00Z").unwrap();
let (node, n, summe): (String, i64, f64) = store
.connection()
.query_row(
"SELECT node_id, n, summe FROM metrik_rollup WHERE aufloesung_s = 300",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.unwrap();
assert_eq!((node.as_str(), n, summe), ("local", 2, 30.0));
}
#[test]
fn neue_datenbank_hat_neueste_version() {
let store = Store::open_in_memory().unwrap();
assert_eq!(store.schema_version().unwrap(), LATEST_SCHEMA_VERSION);
store.integrity_check().unwrap();
}
#[test]
fn erneutes_oeffnen_aendert_nichts_und_behaelt_daten() {
let ordner = Testordner::neu();
let pfad = ordner.0.join("nexus.db");
{
let store = Store::open(&pfad).unwrap();
engine_einfuegen(&store);
}
let store = Store::open(&pfad).unwrap();
assert_eq!(store.schema_version().unwrap(), LATEST_SCHEMA_VERSION);
let anzahl: i64 = store
.connection()
.query_row("SELECT COUNT(*) FROM engine", [], |r| r.get(0))
.unwrap();
assert_eq!(anzahl, 1);
}
#[test]
fn datenbank_der_version_1_wird_mit_ihren_daten_auf_2_gehoben() {
let ordner = Testordner::neu();
let pfad = ordner.0.join("nexus.db");
{
// Eine Datenbank, wie sie Version 0.1.0 bis 0.1.2 angelegt haben.
let conn = rusqlite::Connection::open(&pfad).unwrap();
conn.execute_batch(MIGRATIONS[0]).unwrap();
conn.pragma_update(None, "user_version", 1).unwrap();
conn.execute(
"INSERT INTO anfrage_log (zeit, korrelation, status) VALUES ('2026-11-09T10:00:00Z', 'req_alt', 200)",
[],
)
.unwrap();
}
let store = Store::open(&pfad).unwrap();
assert_eq!(store.schema_version().unwrap(), LATEST_SCHEMA_VERSION);
let alt = &store.recent_requests(10).unwrap()[0];
assert_eq!(alt.correlation, "req_alt");
assert_eq!(alt.tokens_out, None);
assert!(!alt.aborted);
}
#[test]
fn sicherung_ist_vollstaendig_und_migriert_die_quelle_nicht() {
let ordner = Testordner::neu();
let pfad = ordner.0.join("nexus.db");
{
let conn = rusqlite::Connection::open(&pfad).unwrap();
conn.execute_batch(MIGRATIONS[0]).unwrap();
conn.pragma_update(None, "user_version", 1).unwrap();
conn.execute(
"INSERT INTO anfrage_log (zeit, korrelation, status) VALUES ('2026-11-09T10:00:00Z', 'req_alt', 200)",
[],
)
.unwrap();
}
let ziel = ordner.0.join("sicherung/vorher.db");
backup_file(&pfad, &ziel).unwrap();
// Quelle unverändert auf Version 1.
let quelle = rusqlite::Connection::open(&pfad).unwrap();
let v: i64 = quelle
.pragma_query_value(None, "user_version", |r| r.get(0))
.unwrap();
assert_eq!(v, 1);
// Die Kopie hat Version 1 und die Daten.
let kopie = rusqlite::Connection::open(&ziel).unwrap();
let v: i64 = kopie
.pragma_query_value(None, "user_version", |r| r.get(0))
.unwrap();
assert_eq!(v, 1);
let n: i64 = kopie
.query_row("SELECT COUNT(*) FROM anfrage_log", [], |r| r.get(0))
.unwrap();
assert_eq!(n, 1);
// Zweimal dasselbe Ziel wird abgelehnt.
assert!(backup_file(&pfad, &ziel).is_err());
}
#[test]
fn neuere_datenbank_wird_abgelehnt() {
let ordner = Testordner::neu();
let pfad = ordner.0.join("nexus.db");
{
let store = Store::open(&pfad).unwrap();
store
.connection()
.pragma_update(None, "user_version", LATEST_SCHEMA_VERSION + 1)
.unwrap();
}
let err = Store::open(&pfad).err().expect("muss scheitern");
assert!(err.to_string().contains("Schema-Version"), "{err}");
}
#[test]
fn standard_worker_local_existiert() {
let store = Store::open_in_memory().unwrap();
let id: String = store
.connection()
.query_row("SELECT id FROM worker", [], |r| r.get(0))
.unwrap();
assert_eq!(id, "local");
}
#[test]
fn modell_artifact_profil_kette_funktioniert() {
let store = Store::open_in_memory().unwrap();
let c = store.connection();
let engine = engine_einfuegen(&store);
c.execute(
"INSERT INTO model (name, art, freigegeben) VALUES ('bonsai', 'llm', 1)",
[],
)
.unwrap();
let model = c.last_insert_rowid();
c.execute(
"INSERT INTO artifact (model_id, engine_id, pfad, quantisierung) VALUES (?1, ?2, '/srv/models/gguf/Bonsai-1.7B-Q1_0.gguf', 'Q1_0')",
(model, engine),
)
.unwrap();
let artifact = c.last_insert_rowid();
c.execute(
"INSERT INTO profile (artifact_id, gpus, vram_mb, ram_mb, kontext) VALUES (?1, '0', 1024, 2048, 4096)",
[artifact],
)
.unwrap();
store.integrity_check().unwrap();
}
#[test]
fn fremdschluessel_werden_erzwungen() {
let store = Store::open_in_memory().unwrap();
let err = store.connection().execute(
"INSERT INTO artifact (model_id, engine_id, pfad) VALUES (999, 999, 'x')",
[],
);
assert!(err.is_err());
}
#[test]
fn check_regeln_lehnen_ungueltige_werte_ab() {
let store = Store::open_in_memory().unwrap();
let c = store.connection();
assert!(
c.execute(
"INSERT INTO engine (name, art, modus) VALUES ('x', 'llm', 'unbekannt')",
[]
)
.is_err()
);
assert!(
c.execute("INSERT INTO model (name, art) VALUES ('m', 'audio')", [])
.is_err()
);
assert!(
c.execute(
"INSERT INTO api_key (name, hash, max_prioritaet) VALUES ('k', 'h', 'vip')",
[]
)
.is_err()
);
}
#[test]
fn api_key_hash_ist_eindeutig() {
let store = Store::open_in_memory().unwrap();
let c = store.connection();
c.execute("INSERT INTO api_key (name, hash) VALUES ('a', 'h1')", [])
.unwrap();
assert!(
c.execute("INSERT INTO api_key (name, hash) VALUES ('b', 'h1')", [])
.is_err()
);
}
}