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:
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user