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:
@ -13,6 +13,7 @@ use crate::sandbox::Sandbox;
|
||||
use base64::Engine;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const WORK_DIR: &str = "/work";
|
||||
@ -119,6 +120,8 @@ pub struct RunOutcome {
|
||||
pub duration_ms: u128,
|
||||
pub time_to_first_tool_ms: Option<u128>,
|
||||
pub transcript: Vec<Message>,
|
||||
/// Gesetzt, wenn der Lauf von außen abgebrochen wurde. Dann ist das Ergebnis nicht gültig.
|
||||
pub cancelled: bool,
|
||||
}
|
||||
|
||||
/// Werkzeug-Schema für Ollama.
|
||||
@ -288,6 +291,17 @@ pub fn run_agent(
|
||||
ws: &dyn Workspace,
|
||||
prompt: &str,
|
||||
limits: &AgentLimits,
|
||||
) -> RunOutcome {
|
||||
run_agent_cancellable(model, ws, prompt, limits, &AtomicBool::new(false))
|
||||
}
|
||||
|
||||
/// Wie `run_agent`, bricht aber ab, sobald `cancel` gesetzt ist. Der Lauf gilt dann als `cancelled`.
|
||||
pub fn run_agent_cancellable(
|
||||
model: &dyn ModelClient,
|
||||
ws: &dyn Workspace,
|
||||
prompt: &str,
|
||||
limits: &AgentLimits,
|
||||
cancel: &AtomicBool,
|
||||
) -> RunOutcome {
|
||||
let started = Instant::now();
|
||||
let tools = tool_schemas();
|
||||
@ -302,6 +316,7 @@ pub fn run_agent(
|
||||
duration_ms: 0,
|
||||
time_to_first_tool_ms: None,
|
||||
transcript: vec![],
|
||||
cancelled: false,
|
||||
};
|
||||
|
||||
// Letzter Tool-Call und Anzahl gleicher Wiederholungen mit gleichem Ergebnis.
|
||||
@ -309,6 +324,10 @@ pub fn run_agent(
|
||||
let mut repeats: u32 = 0;
|
||||
|
||||
let class = loop {
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
out.cancelled = true;
|
||||
break ErrorClass::Ok;
|
||||
}
|
||||
if out.steps >= limits.max_steps {
|
||||
break ErrorClass::MaxSteps;
|
||||
}
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
mod agent;
|
||||
mod config;
|
||||
mod runner;
|
||||
mod store;
|
||||
mod sandbox;
|
||||
mod tasks;
|
||||
|
||||
|
||||
480
src-tauri/src/runner.rs
Normal file
480
src-tauri/src/runner.rs
Normal file
@ -0,0 +1,480 @@
|
||||
//! Runner: Batch aus Modellen, Aufgaben und Wiederholungen (F-05, SPEC Abschnitt 7).
|
||||
//!
|
||||
//! Die Modelle laufen nacheinander, weil ein Modell die GPU belegt. Jeder Lauf
|
||||
//! bekommt eine frische Sandbox, der Agent läuft, danach läuft `check.sh` im
|
||||
//! selben Container. Fertige Läufe stehen in der Datenbank und werden beim
|
||||
//! Fortsetzen übersprungen. Ein abgebrochener Lauf wird verworfen und nicht gespeichert.
|
||||
|
||||
use crate::agent::{
|
||||
run_agent_cancellable, AgentLimits, ErrorClass, Message, ModelClient, ModelError,
|
||||
OllamaClient, SandboxWorkspace,
|
||||
};
|
||||
use crate::sandbox::{container_name, remove_by_name, Limits, Sandbox};
|
||||
use crate::store::{RunRecord, Store};
|
||||
use crate::tasks::{Task, CHECK_FILE, START_DIR};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
pub const CHECK_DIR: &str = "/checks";
|
||||
pub const WARMUP_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
/// Ein einzelner Lauf im Plan.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Job {
|
||||
pub model: String,
|
||||
pub task: Task,
|
||||
pub repeat_idx: u32,
|
||||
}
|
||||
|
||||
/// Einstellungen für einen Batch.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunConfig {
|
||||
pub runtime: String,
|
||||
pub endpoint_url: String,
|
||||
pub data_dir: PathBuf,
|
||||
pub limits: Limits,
|
||||
}
|
||||
|
||||
/// Ereignisse für die Oberfläche.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Event {
|
||||
RunStarted { model: String, task: String, repeat: u32 },
|
||||
RunFinished { model: String, task: String, repeat: u32, class: ErrorClass, score: f64 },
|
||||
RunSkipped { model: String, task: String, repeat: u32 },
|
||||
ModelUnavailable { model: String, reason: String },
|
||||
Progress { done: usize, total: usize },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct BatchSummary {
|
||||
pub batch_id: i64,
|
||||
pub completed: usize,
|
||||
pub skipped: usize,
|
||||
pub cancelled: bool,
|
||||
}
|
||||
|
||||
/// Plan in fester Reihenfolge: Modell, dann Aufgabe, dann Wiederholung.
|
||||
pub fn plan(models: &[String], tasks: &[Task], repeats: u32) -> Vec<Job> {
|
||||
let mut jobs = Vec::new();
|
||||
for model in models {
|
||||
for task in tasks {
|
||||
for repeat_idx in 1..=repeats {
|
||||
jobs.push(Job {
|
||||
model: model.clone(),
|
||||
task: task.clone(),
|
||||
repeat_idx,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs
|
||||
}
|
||||
|
||||
/// Ergebnis der Prüfung durch `check.sh`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CheckResult {
|
||||
pub score: f64,
|
||||
pub passed: bool,
|
||||
}
|
||||
|
||||
/// Wertet `check.sh` aus. Letzte Zeile als JSON `{"score": …}` gewinnt, sonst zählt der Exit-Code.
|
||||
pub fn evaluate_check(exit: Option<i32>, stdout: &str) -> CheckResult {
|
||||
let last = stdout.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("");
|
||||
if let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(last.trim()) {
|
||||
if let Some(score) = obj.get("score").and_then(Value::as_f64) {
|
||||
let score = score.clamp(0.0, 1.0);
|
||||
return CheckResult { score, passed: score >= 1.0 };
|
||||
}
|
||||
}
|
||||
let passed = exit == Some(0);
|
||||
CheckResult { score: if passed { 1.0 } else { 0.0 }, passed }
|
||||
}
|
||||
|
||||
/// Fehlerklasse eines fertigen Laufs: zuerst die Agentenklasse, dann die Prüfung.
|
||||
pub fn final_class(agent: ErrorClass, check: &CheckResult) -> ErrorClass {
|
||||
if agent != ErrorClass::Ok {
|
||||
agent
|
||||
} else if !check.passed {
|
||||
ErrorClass::CheckFailed
|
||||
} else {
|
||||
ErrorClass::Ok
|
||||
}
|
||||
}
|
||||
|
||||
/// Startet einen Batch oder setzt einen bestehenden fort.
|
||||
/// `batch_id = None` legt einen neuen Batch an. Fertige Läufe werden übersprungen.
|
||||
pub fn run_batch(
|
||||
store: &mut Store,
|
||||
cfg: &RunConfig,
|
||||
batch_id: Option<i64>,
|
||||
note: &str,
|
||||
repeats: u32,
|
||||
jobs: &[Job],
|
||||
cancel: &AtomicBool,
|
||||
on_event: &dyn Fn(&Event),
|
||||
) -> Result<BatchSummary, String> {
|
||||
let config_json = json!({
|
||||
"runtime": cfg.runtime,
|
||||
"endpoint": cfg.endpoint_url,
|
||||
"limits": { "memory": cfg.limits.memory, "cpus": cfg.limits.cpus },
|
||||
"system_prompt": crate::agent::SYSTEM_PROMPT,
|
||||
"tool_output_chars": crate::agent::MAX_TOOL_OUTPUT_CHARS,
|
||||
"loop_repeats": crate::agent::LOOP_REPEATS,
|
||||
})
|
||||
.to_string();
|
||||
let batch_id = match batch_id {
|
||||
Some(id) => {
|
||||
if !store.batch_exists(id)? {
|
||||
return Err(format!("Batch {id} existiert nicht"));
|
||||
}
|
||||
id
|
||||
}
|
||||
None => store.create_batch(note, repeats, &config_json)?,
|
||||
};
|
||||
|
||||
let finished = store.finished_keys(batch_id)?;
|
||||
let total = jobs.len();
|
||||
let mut summary = BatchSummary { batch_id, completed: 0, skipped: 0, cancelled: false };
|
||||
let mut done = 0usize;
|
||||
|
||||
// Modelle in der Reihenfolge des Plans, jedes Modell nur einmal aufwärmen.
|
||||
let mut models: Vec<String> = Vec::new();
|
||||
for j in jobs {
|
||||
if !models.contains(&j.model) {
|
||||
models.push(j.model.clone());
|
||||
}
|
||||
}
|
||||
|
||||
'models: for model in &models {
|
||||
let client = OllamaClient::new(&cfg.endpoint_url, model)?;
|
||||
let warm = client.chat(
|
||||
&[Message::new("user", "ping")],
|
||||
&json!([]),
|
||||
WARMUP_TIMEOUT,
|
||||
);
|
||||
let unavailable = match warm {
|
||||
Ok(_) => None,
|
||||
Err(ModelError::Timeout) => Some("Aufwärmen hat das Zeitlimit überschritten".to_string()),
|
||||
Err(ModelError::Endpoint(e)) => Some(e),
|
||||
};
|
||||
if let Some(reason) = &unavailable {
|
||||
on_event(&Event::ModelUnavailable { model: model.clone(), reason: reason.clone() });
|
||||
}
|
||||
|
||||
for (i, job) in jobs.iter().enumerate().filter(|(_, j)| &j.model == model) {
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
summary.cancelled = true;
|
||||
break 'models;
|
||||
}
|
||||
let key = (job.model.clone(), job.task.meta.id.clone(), job.repeat_idx);
|
||||
if finished.contains(&key) {
|
||||
summary.skipped += 1;
|
||||
done += 1;
|
||||
on_event(&Event::RunSkipped {
|
||||
model: job.model.clone(),
|
||||
task: job.task.meta.id.clone(),
|
||||
repeat: job.repeat_idx,
|
||||
});
|
||||
on_event(&Event::Progress { done, total });
|
||||
continue;
|
||||
}
|
||||
|
||||
on_event(&Event::RunStarted {
|
||||
model: job.model.clone(),
|
||||
task: job.task.meta.id.clone(),
|
||||
repeat: job.repeat_idx,
|
||||
});
|
||||
|
||||
let fin = match &unavailable {
|
||||
// Modell nicht nutzbar: Lauf wird als endpoint_error gespeichert, ohne Container.
|
||||
Some(reason) => Finished {
|
||||
record: RunRecord {
|
||||
batch_id,
|
||||
model: job.model.clone(),
|
||||
task_id: job.task.meta.id.clone(),
|
||||
repeat_idx: job.repeat_idx,
|
||||
error_class: ErrorClass::EndpointError,
|
||||
score: 0.0,
|
||||
steps: 0,
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
duration_ms: 0,
|
||||
tps: None,
|
||||
ttft_tool_ms: None,
|
||||
artifact_path: None,
|
||||
summary: None,
|
||||
check_output: reason.clone(),
|
||||
},
|
||||
transcript: vec![],
|
||||
},
|
||||
None => match execute_job(cfg, batch_id, i, job, &client, cancel)? {
|
||||
JobResult::Cancelled => {
|
||||
summary.cancelled = true;
|
||||
break 'models;
|
||||
}
|
||||
JobResult::Finished(f) => f,
|
||||
},
|
||||
};
|
||||
|
||||
on_event(&Event::RunFinished {
|
||||
model: job.model.clone(),
|
||||
task: job.task.meta.id.clone(),
|
||||
repeat: job.repeat_idx,
|
||||
class: fin.record.error_class,
|
||||
score: fin.record.score,
|
||||
});
|
||||
store.insert_run(&fin.record, &fin.transcript)?;
|
||||
summary.completed += 1;
|
||||
done += 1;
|
||||
on_event(&Event::Progress { done, total });
|
||||
}
|
||||
}
|
||||
|
||||
if summary.cancelled {
|
||||
on_event(&Event::Progress { done, total });
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
struct Finished {
|
||||
record: RunRecord,
|
||||
transcript: Vec<Message>,
|
||||
}
|
||||
|
||||
enum JobResult {
|
||||
Finished(Finished),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
fn execute_job(
|
||||
cfg: &RunConfig,
|
||||
batch_id: i64,
|
||||
seq: usize,
|
||||
job: &Job,
|
||||
client: &OllamaClient,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<JobResult, String> {
|
||||
let meta = &job.task.meta;
|
||||
let name = container_name(&format!("{batch_id}-{seq}"));
|
||||
remove_by_name(&cfg.runtime, &name);
|
||||
|
||||
let start_dir = job.task.dir.join(START_DIR);
|
||||
let start_arg = if start_dir.is_dir() { Some(start_dir.as_path()) } else { None };
|
||||
let sb = Sandbox::start(&cfg.runtime, &name, &meta.image, &cfg.limits, start_arg)?;
|
||||
let ws = SandboxWorkspace { sandbox: &sb };
|
||||
|
||||
let limits = AgentLimits {
|
||||
max_steps: meta.max_steps,
|
||||
timeout: Duration::from_secs(meta.timeout_s),
|
||||
};
|
||||
let prompt = std::fs::read_to_string(job.task.dir.join("prompt.md"))
|
||||
.map_err(|e| format!("prompt.md nicht lesbar: {e}"))?;
|
||||
let outcome = run_agent_cancellable(client, &ws, &prompt, &limits, cancel);
|
||||
if outcome.cancelled {
|
||||
sb.remove()?;
|
||||
return Ok(JobResult::Cancelled);
|
||||
}
|
||||
|
||||
// check.sh läuft im selben Container, aber außerhalb von /work.
|
||||
let check_output = sb
|
||||
.exec(&format!("mkdir -p {CHECK_DIR}"), Duration::from_secs(30))
|
||||
.and_then(|_| sb.copy_in(&job.task.dir.join(CHECK_FILE), &format!("{CHECK_DIR}/check.sh")))
|
||||
.and_then(|_| {
|
||||
sb.exec(
|
||||
&format!("cd /work && sh {CHECK_DIR}/check.sh"),
|
||||
Duration::from_secs(meta.check_timeout_s),
|
||||
)
|
||||
});
|
||||
let (check, check_text) = match check_output {
|
||||
Ok(out) => {
|
||||
let text = format!(
|
||||
"exit {}{}\n{}{}",
|
||||
out.exit_code.map_or("?".into(), |c| c.to_string()),
|
||||
if out.timed_out { " (Zeitlimit)" } else { "" },
|
||||
out.stdout,
|
||||
out.stderr
|
||||
);
|
||||
let check = if out.timed_out {
|
||||
CheckResult { score: 0.0, passed: false }
|
||||
} else {
|
||||
evaluate_check(out.exit_code, &out.stdout)
|
||||
};
|
||||
(check, text)
|
||||
}
|
||||
Err(e) => (CheckResult { score: 0.0, passed: false }, format!("Prüfung nicht ausführbar: {e}")),
|
||||
};
|
||||
|
||||
let artifact = cfg
|
||||
.data_dir
|
||||
.join("runs")
|
||||
.join(batch_id.to_string())
|
||||
.join(format!("{}-{}-{}", job.model.replace([':', '/'], "_"), meta.id, job.repeat_idx));
|
||||
let artifact_path = match sb.export_work(&artifact.join("work")) {
|
||||
Ok(()) => Some(artifact.join("work").display().to_string()),
|
||||
Err(_) => None,
|
||||
};
|
||||
sb.remove()?;
|
||||
|
||||
let class = final_class(outcome.class, &check);
|
||||
let secs = outcome.duration_ms as f64 / 1000.0;
|
||||
let tps = if outcome.completion_tokens > 0 && secs > 0.0 {
|
||||
Some(outcome.completion_tokens as f64 / secs)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let record = RunRecord {
|
||||
batch_id,
|
||||
model: job.model.clone(),
|
||||
task_id: meta.id.clone(),
|
||||
repeat_idx: job.repeat_idx,
|
||||
error_class: class,
|
||||
score: check.score,
|
||||
steps: outcome.steps,
|
||||
prompt_tokens: outcome.prompt_tokens,
|
||||
completion_tokens: outcome.completion_tokens,
|
||||
duration_ms: outcome.duration_ms,
|
||||
tps,
|
||||
ttft_tool_ms: outcome.time_to_first_tool_ms,
|
||||
artifact_path,
|
||||
summary: outcome.summary.clone(),
|
||||
check_output: check_text,
|
||||
};
|
||||
Ok(JobResult::Finished(Finished {
|
||||
record,
|
||||
transcript: outcome.transcript,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::tasks::TaskToml;
|
||||
|
||||
fn task(id: &str) -> Task {
|
||||
Task {
|
||||
meta: TaskToml {
|
||||
id: id.into(),
|
||||
title: id.into(),
|
||||
group: "A".into(),
|
||||
weight: 1.0,
|
||||
image: "cb-python:latest".into(),
|
||||
max_steps: 5,
|
||||
timeout_s: 60,
|
||||
check_timeout_s: 30,
|
||||
},
|
||||
dir: PathBuf::from("/x"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_reihenfolge_modell_aufgabe_wiederholung() {
|
||||
let jobs = plan(
|
||||
&["m1".into(), "m2".into()],
|
||||
&[task("a-01"), task("b-04")],
|
||||
2,
|
||||
);
|
||||
assert_eq!(jobs.len(), 8);
|
||||
let keys: Vec<(String, String, u32)> = jobs
|
||||
.iter()
|
||||
.map(|j| (j.model.clone(), j.task.meta.id.clone(), j.repeat_idx))
|
||||
.collect();
|
||||
assert_eq!(keys[0], ("m1".into(), "a-01".into(), 1));
|
||||
assert_eq!(keys[1], ("m1".into(), "a-01".into(), 2));
|
||||
assert_eq!(keys[2], ("m1".into(), "b-04".into(), 1));
|
||||
assert_eq!(keys[4], ("m2".into(), "a-01".into(), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_json_score_gewinnt() {
|
||||
let r = evaluate_check(Some(0), "viel text\n{\"score\": 0.5, \"notes\": \"halb\"}\n");
|
||||
assert_eq!(r, CheckResult { score: 0.5, passed: false });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_ohne_json_zaehlt_exit_code() {
|
||||
assert_eq!(evaluate_check(Some(0), "ok"), CheckResult { score: 1.0, passed: true });
|
||||
assert_eq!(evaluate_check(Some(1), "fehler"), CheckResult { score: 0.0, passed: false });
|
||||
assert_eq!(evaluate_check(None, ""), CheckResult { score: 0.0, passed: false });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_score_wird_begrenzt() {
|
||||
let r = evaluate_check(Some(0), "{\"score\": 3.0}");
|
||||
assert_eq!(r.score, 1.0);
|
||||
assert!(r.passed);
|
||||
}
|
||||
|
||||
/// Kleiner Batch end-to-end: echtes Modell, echte Sandbox, Fortsetzen über die Datenbank.
|
||||
/// `CB_OLLAMA_URL=… CB_OLLAMA_MODEL=… CB_TEST_IMAGE=cb-python:latest cargo test batch_end_zu_end -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn batch_end_zu_end() {
|
||||
let url = std::env::var("CB_OLLAMA_URL").expect("CB_OLLAMA_URL setzen");
|
||||
let model = std::env::var("CB_OLLAMA_MODEL").expect("CB_OLLAMA_MODEL setzen");
|
||||
let image = std::env::var("CB_TEST_IMAGE").expect("CB_TEST_IMAGE setzen");
|
||||
|
||||
let base = std::env::temp_dir().join(format!("cb-batch-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let task_dir = base.join("tasks").join("A").join("a-test");
|
||||
std::fs::create_dir_all(task_dir.join("start")).unwrap();
|
||||
std::fs::write(
|
||||
task_dir.join("task.toml"),
|
||||
format!("id = \"a-test\"\ntitle = \"Datei schreiben\"\ngroup = \"A\"\nimage = \"{image}\"\nmax_steps = 6\ntimeout_s = 300\ncheck_timeout_s = 60\n"),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(task_dir.join("prompt.md"), "Erstelle die Datei out.txt mit dem Inhalt hallo (ohne Zeilenumbruch). Rufe danach done auf.").unwrap();
|
||||
std::fs::write(task_dir.join("check.sh"), "#!/bin/sh\n[ \"$(cat /work/out.txt)\" = \"hallo\" ]\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(task_dir.join("check.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
let (tasks, errs) = {
|
||||
let r = crate::tasks::load_all(&base.join("tasks"));
|
||||
(r.tasks, r.errors)
|
||||
};
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
let jobs = plan(&[model.clone()], &tasks, 2);
|
||||
let cfg = RunConfig {
|
||||
runtime: "podman".into(),
|
||||
endpoint_url: url,
|
||||
data_dir: base.join("data"),
|
||||
limits: Limits::default(),
|
||||
};
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
let cancel = AtomicBool::new(false);
|
||||
let events = std::cell::RefCell::new(Vec::new());
|
||||
let on = |e: &Event| events.borrow_mut().push(e.clone());
|
||||
|
||||
let first = run_batch(&mut store, &cfg, None, "e2e", 2, &jobs, &cancel, &on).unwrap();
|
||||
eprintln!("erster Lauf: {first:?}");
|
||||
assert_eq!(first.completed, 2);
|
||||
assert_eq!(first.skipped, 0);
|
||||
|
||||
// Fortsetzen mit demselben Batch: nichts läuft erneut.
|
||||
let second = run_batch(&mut store, &cfg, Some(first.batch_id), "", 2, &jobs, &cancel, &on).unwrap();
|
||||
eprintln!("zweiter Lauf: {second:?}");
|
||||
assert_eq!(second.completed, 0);
|
||||
assert_eq!(second.skipped, 2);
|
||||
assert_eq!(store.run_count(first.batch_id).unwrap(), 2);
|
||||
|
||||
for e in events.borrow().iter() {
|
||||
eprintln!("{}", serde_json::to_string(e).unwrap());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn klasse_agent_vor_pruefung() {
|
||||
let ok = CheckResult { score: 1.0, passed: true };
|
||||
let bad = CheckResult { score: 0.0, passed: false };
|
||||
assert_eq!(final_class(ErrorClass::MaxSteps, &ok), ErrorClass::MaxSteps);
|
||||
assert_eq!(final_class(ErrorClass::Ok, &bad), ErrorClass::CheckFailed);
|
||||
assert_eq!(final_class(ErrorClass::Ok, &ok), ErrorClass::Ok);
|
||||
}
|
||||
}
|
||||
@ -203,6 +203,20 @@ impl Sandbox {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Kopiert eine einzelne Datei in den Container (z. B. `check.sh`, nicht in `/work`).
|
||||
pub fn copy_in(&self, src: &Path, dst: &str) -> Result<(), String> {
|
||||
let dst_spec = format!("{}:{dst}", self.name);
|
||||
let out = Command::new(&self.runtime)
|
||||
.args(["cp", &src.display().to_string(), &dst_spec])
|
||||
.output()
|
||||
.map_err(|e| format!("podman cp fehlgeschlagen: {e}"))?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Entfernt den Container. Fehler werden zurückgegeben, nicht verschluckt.
|
||||
pub fn remove(mut self) -> Result<(), String> {
|
||||
self.remove_inner()
|
||||
@ -225,6 +239,11 @@ impl Sandbox {
|
||||
}
|
||||
}
|
||||
|
||||
/// Entfernt einen Container nach Name, falls ein früherer Lauf ihn hinterlassen hat.
|
||||
pub fn remove_by_name(runtime: &str, name: &str) {
|
||||
let _ = Command::new(runtime).args(["rm", "-f", name]).output();
|
||||
}
|
||||
|
||||
impl Drop for Sandbox {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.remove_inner();
|
||||
|
||||
257
src-tauri/src/store.rs
Normal file
257
src-tauri/src/store.rs
Normal 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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user