feat: Runner und SQLite-Speicher

runner.rs: Plan in Reihenfolge Modell/Aufgabe/Wiederholung, Aufwärmen je
Modell, frische Sandbox pro Lauf, check.sh im selben Container, Abbruch
und Fortsetzen über die Datenbank. store.rs: Schema nach SPEC 8, Lauf und
Schritte in einer Transaktion. Agent-Loop bekommt Abbruchflag.
Ende-zu-Ende gegen srv04 mit qwen3:0.6b grün; Fortsetzen überspringt
fertige Läufe. 38 Unit-Tests grün.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-06 19:35:02 +01:00
parent e69f3be35b
commit c8290aeb94
8 changed files with 872 additions and 4 deletions

257
src-tauri/src/store.rs Normal file
View File

@ -0,0 +1,257 @@
//! 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<f64>,
pub ttft_tool_ms: Option<u128>,
pub artifact_path: Option<String>,
pub summary: Option<String>,
pub check_output: String,
}
pub struct Store {
conn: Connection,
}
impl Store {
pub fn open(path: &Path) -> Result<Store, String> {
let conn = Connection::open(path).map_err(|e| format!("Datenbank nicht öffenbar: {e}"))?;
Self::init(conn)
}
pub fn open_in_memory() -> Result<Store, String> {
let conn = Connection::open_in_memory().map_err(|e| e.to_string())?;
Self::init(conn)
}
fn init(conn: Connection) -> Result<Store, String> {
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<i64, String> {
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<bool, String> {
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<HashSet<(String, String, u32)>, 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::<Result<HashSet<_>, _>>().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<i64, String> {
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)
}
pub fn run_count(&self, batch_id: i64) -> Result<i64, String> {
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<i64, String> {
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 unbekannter_batch_existiert_nicht() {
let s = Store::open_in_memory().unwrap();
assert!(!s.batch_exists(99).unwrap());
}
}