//! SQLite-Speicher für Batches, Läufe und Schritte (F-06, SPEC Abschnitt 8). use crate::agent::{ErrorClass, Message}; use rusqlite::{params, Connection, OptionalExtension}; use serde::Serialize; use std::collections::HashSet; use std::path::Path; const SCHEMA: &str = " CREATE TABLE IF NOT EXISTS batch ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TEXT NOT NULL DEFAULT (datetime('now')), note TEXT NOT NULL DEFAULT '', repeats INTEGER NOT NULL, config_json TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS run ( id INTEGER PRIMARY KEY AUTOINCREMENT, batch_id INTEGER NOT NULL REFERENCES batch(id), model TEXT NOT NULL, task_id TEXT NOT NULL, repeat_idx INTEGER NOT NULL, status TEXT NOT NULL, error_class TEXT NOT NULL, score REAL NOT NULL, steps INTEGER NOT NULL, prompt_tokens INTEGER NOT NULL, completion_tokens INTEGER NOT NULL, duration_ms INTEGER NOT NULL, tps REAL, ttft_tool_ms INTEGER, started_at TEXT NOT NULL DEFAULT (datetime('now')), artifact_path TEXT, summary TEXT, check_output TEXT ); CREATE INDEX IF NOT EXISTS run_batch ON run(batch_id, model, task_id, repeat_idx); CREATE TABLE IF NOT EXISTS step ( id INTEGER PRIMARY KEY AUTOINCREMENT, run_id INTEGER NOT NULL REFERENCES run(id), idx INTEGER NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, tool_name TEXT, tool_args_json TEXT, tool_result TEXT, tokens INTEGER, duration_ms INTEGER ); "; /// Ein abgeschlossener Lauf, so wie er gespeichert wird. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct RunRecord { pub batch_id: i64, pub model: String, pub task_id: String, pub repeat_idx: u32, pub error_class: ErrorClass, pub score: f64, pub steps: u32, pub prompt_tokens: u32, pub completion_tokens: u32, pub duration_ms: u128, pub tps: Option, pub ttft_tool_ms: Option, pub artifact_path: Option, pub summary: Option, pub check_output: String, } pub struct Store { conn: Connection, } impl Store { pub fn open(path: &Path) -> Result { let conn = Connection::open(path).map_err(|e| format!("Datenbank nicht öffenbar: {e}"))?; Self::init(conn) } pub fn open_in_memory() -> Result { let conn = Connection::open_in_memory().map_err(|e| e.to_string())?; Self::init(conn) } fn init(conn: Connection) -> Result { conn.execute_batch("PRAGMA foreign_keys = ON;") .and_then(|_| conn.execute_batch(SCHEMA)) .map_err(|e| format!("Schema nicht anlegbar: {e}"))?; Ok(Store { conn }) } pub fn create_batch(&self, note: &str, repeats: u32, config_json: &str) -> Result { self.conn .execute( "INSERT INTO batch (note, repeats, config_json) VALUES (?1, ?2, ?3)", params![note, repeats, config_json], ) .map_err(|e| e.to_string())?; Ok(self.conn.last_insert_rowid()) } pub fn batch_exists(&self, batch_id: i64) -> Result { self.conn .query_row("SELECT 1 FROM batch WHERE id = ?1", params![batch_id], |_| Ok(())) .optional() .map(|r| r.is_some()) .map_err(|e| e.to_string()) } /// Schlüssel (Modell, Aufgabe, Wiederholung) aller bereits gespeicherten Läufe eines Batches. pub fn finished_keys(&self, batch_id: i64) -> Result, String> { let mut stmt = self .conn .prepare("SELECT model, task_id, repeat_idx FROM run WHERE batch_id = ?1") .map_err(|e| e.to_string())?; let rows = stmt .query_map(params![batch_id], |r| { Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, u32>(2)?)) }) .map_err(|e| e.to_string())?; rows.collect::, _>>().map_err(|e| e.to_string()) } /// Speichert einen Lauf mit seinen Schritten in einer Transaktion. pub fn insert_run(&mut self, rec: &RunRecord, transcript: &[Message]) -> Result { let tx = self.conn.transaction().map_err(|e| e.to_string())?; let class = serde_json::to_value(rec.error_class) .ok() .and_then(|v| v.as_str().map(String::from)) .unwrap_or_default(); tx.execute( "INSERT INTO run (batch_id, model, task_id, repeat_idx, status, error_class, score, steps, prompt_tokens, completion_tokens, duration_ms, tps, ttft_tool_ms, artifact_path, summary, check_output) VALUES (?1, ?2, ?3, ?4, 'done', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", params![ rec.batch_id, rec.model, rec.task_id, rec.repeat_idx, class, rec.score, rec.steps, rec.prompt_tokens, rec.completion_tokens, rec.duration_ms as i64, rec.tps, rec.ttft_tool_ms.map(|v| v as i64), rec.artifact_path, rec.summary, rec.check_output, ], ) .map_err(|e| e.to_string())?; let run_id = tx.last_insert_rowid(); for (idx, m) in transcript.iter().enumerate() { let (args, tool_name) = match m.tool_calls.first() { Some(c) => (Some(c.function.arguments.to_string()), Some(c.function.name.clone())), None => (None, m.tool_name.clone()), }; tx.execute( "INSERT INTO step (run_id, idx, role, content, tool_name, tool_args_json, tool_result) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", params![ run_id, idx as i64, m.role, m.content, tool_name, args, if m.role == "tool" { Some(m.content.clone()) } else { None }, ], ) .map_err(|e| e.to_string())?; } tx.commit().map_err(|e| e.to_string())?; Ok(run_id) } /// Alle gespeicherten Läufe eines Batches, sortiert nach Modell, Aufgabe und Wiederholung. pub fn runs_for_batch(&self, batch_id: i64) -> Result, String> { let mut stmt = self .conn .prepare( "SELECT batch_id, model, task_id, repeat_idx, error_class, score, steps, prompt_tokens, completion_tokens, duration_ms, tps, ttft_tool_ms, artifact_path, summary, check_output FROM run WHERE batch_id = ?1 ORDER BY model, task_id, repeat_idx", ) .map_err(|e| e.to_string())?; let rows = stmt .query_map(params![batch_id], |r| { let class: String = r.get(4)?; let error_class = serde_json::from_value(serde_json::Value::String(class)) .unwrap_or(ErrorClass::EndpointError); Ok(RunRecord { batch_id: r.get(0)?, model: r.get(1)?, task_id: r.get(2)?, repeat_idx: r.get(3)?, error_class, score: r.get(5)?, steps: r.get(6)?, prompt_tokens: r.get(7)?, completion_tokens: r.get(8)?, duration_ms: r.get::<_, i64>(9)? as u128, tps: r.get(10)?, ttft_tool_ms: r.get::<_, Option>(11)?.map(|v| v as u128), artifact_path: r.get(12)?, summary: r.get(13)?, check_output: r.get(14)?, }) }) .map_err(|e| e.to_string())?; rows.collect::, _>>().map_err(|e| e.to_string()) } pub fn run_count(&self, batch_id: i64) -> Result { self.conn .query_row("SELECT COUNT(*) FROM run WHERE batch_id = ?1", params![batch_id], |r| r.get(0)) .map_err(|e| e.to_string()) } pub fn step_count(&self, run_id: i64) -> Result { self.conn .query_row("SELECT COUNT(*) FROM step WHERE run_id = ?1", params![run_id], |r| r.get(0)) .map_err(|e| e.to_string()) } } #[cfg(test)] mod tests { use super::*; use crate::agent::{FunctionCall, ToolCall}; use serde_json::json; fn rec(batch: i64, model: &str, task: &str, rep: u32) -> RunRecord { RunRecord { batch_id: batch, model: model.into(), task_id: task.into(), repeat_idx: rep, error_class: ErrorClass::Ok, score: 1.0, steps: 2, prompt_tokens: 10, completion_tokens: 5, duration_ms: 1234, tps: Some(4.0), ttft_tool_ms: Some(300), artifact_path: None, summary: Some("fertig".into()), check_output: "ok".into(), } } #[test] fn batch_und_lauf_werden_gespeichert() { let mut s = Store::open_in_memory().unwrap(); let b = s.create_batch("test", 3, "{}").unwrap(); assert!(s.batch_exists(b).unwrap()); let transcript = vec![ Message::new("user", "Aufgabe"), Message { role: "assistant".into(), content: String::new(), tool_calls: vec![ToolCall { function: FunctionCall { name: "done".into(), arguments: json!({"summary": "x"}) }, }], tool_name: None, }, ]; let run_id = s.insert_run(&rec(b, "m1", "a-01", 1), &transcript).unwrap(); assert_eq!(s.run_count(b).unwrap(), 1); assert_eq!(s.step_count(run_id).unwrap(), 2); } #[test] fn fertige_schluessel_werden_gelesen() { let mut s = Store::open_in_memory().unwrap(); let b = s.create_batch("", 2, "{}").unwrap(); s.insert_run(&rec(b, "m1", "a-01", 1), &[]).unwrap(); let keys = s.finished_keys(b).unwrap(); assert!(keys.contains(&("m1".to_string(), "a-01".to_string(), 1))); assert!(!keys.contains(&("m1".to_string(), "a-01".to_string(), 2))); } #[test] fn laeufe_eines_batches_werden_zurueckgelesen() { let mut s = Store::open_in_memory().unwrap(); let b = s.create_batch("", 2, "{}").unwrap(); s.insert_run(&rec(b, "m1", "a-01", 2), &[]).unwrap(); s.insert_run(&rec(b, "m1", "a-01", 1), &[]).unwrap(); let runs = s.runs_for_batch(b).unwrap(); assert_eq!(runs.len(), 2); assert_eq!(runs[0].repeat_idx, 1); assert_eq!(runs[0].error_class, ErrorClass::Ok); assert_eq!(runs[0].ttft_tool_ms, Some(300)); assert!(s.runs_for_batch(99).unwrap().is_empty()); } #[test] fn unbekannter_batch_existiert_nicht() { let s = Store::open_in_memory().unwrap(); assert!(!s.batch_exists(99).unwrap()); } }