From b8ab4eadc1db48a5ca4a5b847c063e981e19d76a Mon Sep 17 00:00:00 2001 From: Ryan Brooks Date: Wed, 25 Nov 2026 10:59:16 -0800 Subject: [PATCH] Cleanups --- README.md | 6 +- core/PROTOCOL.md | 30 +++-- core/README.md | 8 +- core/src/cli/args.rs | 21 ++- core/src/cli/flags.rs | 4 +- core/src/cli/mod.rs | 1 - core/src/commands/offline.rs | 33 +++-- core/src/commands/runs.rs | 1 - core/src/eac/phases/credentials.rs | 21 ++- core/src/eac/phases/discover.rs | 2 +- core/src/eac/phases/execute.rs | 19 ++- core/src/eac/phases/judge.rs | 56 +++----- core/src/eac/phases/seed.rs | 23 ++-- core/src/eac/run/cases.rs | 23 ++-- core/src/eac/run/dir.rs | 40 +----- core/src/eac/run/mod.rs | 6 +- core/src/eac/run/results.rs | 33 +++-- core/src/eac/run/seeds.rs | 4 +- core/src/eac/run/summary.rs | 23 +--- core/src/report/format.rs | 29 +--- core/src/report/tables.rs | 7 +- core/src/schema/document.rs | 19 ++- core/src/schema/protocol.schema.json | 105 +++++++-------- core/src/schema/types.rs | 63 +++------ core/src/schema/worker_methods.rs | 55 ++++---- core/src/worker/pool.rs | 111 ++++----------- core/src/worker/process.rs | 67 ++++++---- core/tests/cli.rs | 64 +++++++-- core/tests/fixtures/project/eac/worker.py | 16 ++- .../tests/fixtures/project/evals/chat_eval.py | 47 ++++--- docs/app/cases-and-runners/page.mdx | 8 +- docs/app/concepts/page.mdx | 2 +- docs/app/introduction/page.mdx | 6 +- docs/app/judges/page.mdx | 16 ++- docs/app/online-evals/page.mdx | 4 +- docs/app/protocol/page.mdx | 2 +- docs/app/run-directory/page.mdx | 2 - docs/app/seeds/page.mdx | 10 +- docs/components/landing.tsx | 6 +- .../evals/triage/judges/found_cause_judge.py | 4 +- .../evals/triage/judges/found_issue_judge.py | 6 +- .../evals/triage/judges/triage_llm_judge.py | 2 +- .../evals/triage/runners/offline.py | 4 +- .../evals/triage/runners/online.py | 2 +- .../evals/triage/seed.py | 4 +- schemas/results.schema.json | 56 ++++---- scripts/upload_evals.py | 7 +- sdks/python/README.md | 74 +++++----- sdks/python/eac/__init__.py | 3 +- sdks/python/eac/judge/judge.py | 13 +- sdks/python/eac/models.py | 10 +- sdks/python/eac/protocol.py | 80 +++++------ sdks/python/eac/runner/offline_runner.py | 10 +- sdks/python/eac/runner/online_runner.py | 2 +- sdks/python/eac/seed/__init__.py | 4 +- sdks/python/eac/seed/seed.py | 85 +++--------- sdks/python/eac/worker.py | 126 +++++------------- 57 files changed, 624 insertions(+), 861 deletions(-) diff --git a/README.md b/README.md index 65d841d..49906c9 100644 --- a/README.md +++ b/README.md @@ -37,15 +37,15 @@ def reply(query: str) -> str: class ChatRunner(OfflineRunner): - def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: + def run_case(self, case: Case, *, seed_results: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: return {"response": reply(case.input["query"])} class Greets(Judge): name = "greets_judge" - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: - response = case.output.get("response", "") + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + response = case.run_results.get("response", "") if "hello" in response: return Score(name=self.name, score=1.0) diff --git a/core/PROTOCOL.md b/core/PROTOCOL.md index 5a3bd84..ba4cc6a 100644 --- a/core/PROTOCOL.md +++ b/core/PROTOCOL.md @@ -20,7 +20,7 @@ eac writes requests to the process's **fd 3** and reads responses from its **fd **Ready line.** -The first line a process writes to fd 4 is its ready line, which says which protocol version it speaks. After that, every response carries the `id` of the request it answers. +The first line a process writes to fd 4 is its ready line, which says which protocol version it speaks. After that, every line is the response to the request eac just sent, carrying that request's `id`. eac stops with an error on any other line. ```jsonc {"protocol": 1} // ready line @@ -70,14 +70,14 @@ These types show up in the params and results of many methods: ```jsonc // Case: an offline case, or a production run collected for online judging {"name": "get_dsn", "input": {}, "expected_output": {}, - "output": {}, "conversation_id": "abc", // what the system produced: set by online.execute, and by eac when judging + "run_results": {}, "conversation_id": "abc", // what the system produced: set by online.execute, and by eac when judging "splits": ["smoke"], "enabled": true, // disabled cases run only when picked by name or split "seeds": [Seed], "judges": ["regex"]} // judge names are for display; judges run in the worker // Seed: key is a content hash, and seeds with the same key are set up once {"name": "project", "key": "4d950d98...", "cache": true, // false: torn down after each run (e.g. the agent mutates it) - "credentials": [Credential]} // optional: what setting it up and tearing it down need, children's included + "credentials": [Credential]} // optional: what setting it up and tearing it down need // Credential: a token, CLI login and so on that something needs. The SDK // rebuilds it from path and fields, and the same path and fields are the @@ -96,7 +96,8 @@ These types show up in the params and results of many methods: // Score: 0..1; null is a diagnostic that doesn't gate pass/fail {"name": "regex", "score": 1.0, "explanation": null, "metadata": {}, - "llm_judge_metrics": Metrics} // optional: what an LLM judge spent on this score + "llm_judge_metrics": Metrics, // optional: what an LLM judge spent on this score + "error": "TimeoutError: ..."} // optional: why the judge raised instead of scoring, which errors the case // Metrics: every field optional, default 0 {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "cache_read_tokens": 0, @@ -133,32 +134,33 @@ eac calls this before setting anything up. `judges` is an online run's chosen ju ### `seed.setup` / `seed.teardown` -- `seed.setup` takes `{"dataset", "seed"}` and returns `{"handle": {...}}`. The handle must be JSON, since later phases read it back from `seeds.json`. -- `seed.teardown` takes `{"dataset", "seed", "handle"}`. +- `seed.setup` takes `{"dataset", "seed"}` and returns `{"seed_results": {...}}`, whatever the seed's setup returned. It must be JSON, since later phases read it back from `seeds.json`. +- `seed.teardown` takes `{"dataset", "seed", "seed_results"}`. eac keeps cached seeds (`cache: true`) in `/seed-cache.json` and only sends `seed.setup` for one it doesn't have there. A seed can also have a cache of its own, shared between machines, like a bucket: -- In `seed.setup` for a cached seed, look the seed's `key` up in its own cache first. If it's there, return `{"handle": {...}, "from_cache": true}` without setting anything up. Otherwise set it up and save the handle to its cache. A cache that fails to load or save should only warn. +- In `seed.setup` for a cached seed, look the seed's `key` up in its own cache first. If it's there, return `{"seed_results": {...}, "from_cache": true}` without setting anything up. Otherwise set it up and save its results to its cache. A cache that fails to load or save should only warn. - In `seed.teardown` for a cached seed, remove `key` from its own cache before tearing the seed down, and fail without tearing it down if that fails, so no machine loads a fixture that's gone. `key` is the one the seed was set up with, which may not be the seed's current key, as when pruning. `eac offline prune` tears down the seeds in eac's local seed cache that no case uses. Seeds in a seed's own cache that no machine has locally are the seed's to clean up. ### `case.run` -Params: `{"dataset", "case", "seeds": {name: handle}, "args", "conversation_id"}`. +Params: `{"dataset", "case", "seed_results": {name: seed_results}, "args", "conversation_id"}`. Runs the system under test on one case. - Tag the agent run with `conversation_id`, so a judge can fetch its trace later. -- Return `{"output": {...}, "conversation_id"?, "metrics"?}`. If the agent used its own conversation id, return it and it replaces eac's. +- Return `{"run_results": {...}, "conversation_id"?, "metrics"?}`. If the agent used its own conversation id, return it and it replaces eac's. ### `case.judge` -Params: `{"dataset", "case", "judges"?, "error"?, "seeds": {name: handle}, "judge_args"?, "trace"?, "started_at"?, "ended_at"?}`. +Params: `{"dataset", "case", "judges"?, "error"?, "seed_results": {name: seed_results}, "judge_args"?, "trace"?, "started_at"?, "ended_at"?}`. -Scores one case's output and returns `{"scores": [Score]}`. +Scores one case's run results and returns `{"judge_results": [Score]}`. -- `case` carries the runner's `output` and `conversation_id`. If the runner failed, it has no `output`, `error` says why, and there's nothing to score. +- A judge that raises gets a Score with its `error` and no `score`. +- `case` carries its `run_results` and `conversation_id`. If the runner failed, it has no `run_results`, `error` says why, and there's nothing to score. - `judges`, when given, names judges to score with instead of the case's own, as in a comparison. Build each one from the class of the case's judge with that name. - `judge_args` is `--judge-args`, keyed by judge name. - `trace` is the case's agent trace, if an earlier judge phase saved one. @@ -169,7 +171,7 @@ Scores one case's output and returns `{"scores": [Score]}`. Params: `{"dataset", "window", "args"}`. -Returns `{"cases": [Case]}`, at most `limit` of the window's runs. Each case has its `output`, and its `conversation_id` if it has one. +Returns `{"cases": [Case]}`, at most `limit` of the window's runs. Each case has its `run_results`, and its `conversation_id` if it has one. Return only sampled runs: those whose id's SHA-256 has its first 8 bytes, as a big-endian integer, below `sample_rate × 2^64`. SDKs should give runners a helper for this, so every SDK picks the same runs. @@ -177,7 +179,7 @@ Return only sampled runs: those whose id's SHA-256 has its first 8 bytes, as a b Params: `{"dataset", "case", "judges", "judge_args"?, "trace"?}`. -Scores a collected case, with its `output` and `conversation_id`, with the named online judges and returns `{"scores": [Score]}`. The names are the ones in the DatasetRef, and `judge_args` is keyed by them. Agent traces work as in `case.judge`, and collected cases have no run times. +Scores a collected case, with its `run_results` and `conversation_id`, with the named online judges and returns `{"judge_results": [Score]}`. The names are the ones in the DatasetRef, and `judge_args` is keyed by them. Judge errors and agent traces work as in `case.judge`, and collected cases have no run times. ### `credentials.check` / `credentials.login` diff --git a/core/README.md b/core/README.md index be088e2..1970ee8 100644 --- a/core/README.md +++ b/core/README.md @@ -66,7 +66,7 @@ Offline evals run evals on cases you wrote, in three phases: ``` eac offline seed pick the cases, create a run, set up its seeds -> seeds.json eac offline execute run the system under test on each case & save its output -> outputs/ -eac offline judge score each output -> scores/ traces/ results/ summary.json +eac offline judge score each output -> traces/ results/ ``` **Seed** @@ -89,7 +89,7 @@ Online evals judge what your system already did in production. There are no seed ``` eac online execute collect production runs from a time window as cases -> outputs/ -eac online judge score each case with the picked judges -> scores/ traces/ results/ summary.json +eac online judge score each case with the picked judges -> traces/ results/ ``` **Execute** @@ -211,12 +211,10 @@ online: .eac/credentials/saved.json values from credential logins, owner-only and git-ignored .eac/runs// manifest.json what was selected, the args, the source (git or CI) - seeds.json handles of every seed the run used + seeds.json results of every seed the run used outputs//.json traces//.json agent traces the judges fetched - scores//.json results/.json each dataset's results, see schemas/results.schema.json - summary.json ``` To store or upload results, run your own script on the run's directory after the judge phase. Read only `results/`, whose format [`schemas/results.schema.json`](../schemas/results.schema.json) describes. The other files are eac's own and may change. Every command that judges, `run` included, prints the run's id to stdout, even when cases fail (`compare` prints one per arm). Judging exits with `1` when a case fails, so run the script whatever eac's exit code is: diff --git a/core/src/cli/args.rs b/core/src/cli/args.rs index 369df90..a3ff893 100644 --- a/core/src/cli/args.rs +++ b/core/src/cli/args.rs @@ -48,7 +48,7 @@ pub enum Offline { /// Execute the AI system we want to test Execute(PhaseArgs), /// Score recorded outputs - Judge(PhaseArgs), + Judge(OfflineJudgeArgs), /// Seed, execute and judge in one go Run(RunArgs), /// Run a dataset comparison, one run per arm with shared seeds @@ -61,7 +61,7 @@ pub enum Offline { pub enum Online { /// Collect production runs from a window as cases -> outputs/, printing the new run's id Execute(OnlineExecuteArgs), - /// Score a collected run's cases with --judge -> scores/, results/, summary.json + /// Score a collected run's cases with --judge -> results/ Judge(OnlineJudgeArgs), /// Execute and judge in one go Run(OnlineRunArgs), @@ -92,22 +92,29 @@ pub struct SeedArgs { pub run_flags: RunFlags, #[arg(long, value_name = "JSON", value_parser = parse_object, help = JUDGE_ARGS)] pub judge_args: Option, - /// Tear down an existing run's uncached seeds instead - #[arg(long)] - pub teardown: bool, +} + +// For `eac offline execute`, which works on an existing run. +#[derive(Args)] +pub struct PhaseArgs { + #[command(flatten)] + pub project: Project, /// Run id to operate on #[arg(long, value_name = "ID", default_value = LATEST)] pub run: String, + #[arg(long, value_name = "N", value_parser = parse_count, help = CONCURRENCY)] + pub concurrency: Option, } -// For the offline phases that work on an existing run. #[derive(Args)] -pub struct PhaseArgs { +pub struct OfflineJudgeArgs { #[command(flatten)] pub project: Project, /// Run id to operate on #[arg(long, value_name = "ID", default_value = LATEST)] pub run: String, + #[arg(long, value_name = "JSON", value_parser = parse_object, help = JUDGE_ARGS)] + pub judge_args: Option, #[arg(long, value_name = "N", value_parser = parse_count, help = CONCURRENCY)] pub concurrency: Option, } diff --git a/core/src/cli/flags.rs b/core/src/cli/flags.rs index d83c55a..7cb19d1 100644 --- a/core/src/cli/flags.rs +++ b/core/src/cli/flags.rs @@ -11,14 +11,12 @@ use crate::eac::{Config, Discovered, Engine, Selection}; use crate::report; use crate::schema::{Mode, Object}; -/// TODO: Rename #[derive(Args)] pub struct Project { #[arg(short = 'C', value_name = "DIR", default_value = ".")] pub dir: PathBuf, } -/// TODO #[derive(Args)] pub struct Scope { #[command(flatten)] @@ -40,7 +38,7 @@ pub struct Select { /// What a new run records: its runner args and metadata. #[derive(Args)] pub struct RunFlags { - /// JSON args for the runner, checked by the dataset's SDK + /// JSON args for the runner, e.g. '{"model": "big"}' #[arg(long, value_name = "JSON", value_parser = parse_object)] pub args: Option, /// Extra metadata for results (repeatable) diff --git a/core/src/cli/mod.rs b/core/src/cli/mod.rs index 9b28a81..01377e9 100644 --- a/core/src/cli/mod.rs +++ b/core/src/cli/mod.rs @@ -15,7 +15,6 @@ pub fn dispatch(command: Command) -> Result<()> { match command { Command::List(a) => commands::list(&a), Command::Schema { which } => commands::schema(which), - Command::Offline(Offline::Seed(a)) if a.teardown => offline::teardown(&a), Command::Offline(Offline::Seed(a)) => offline::seed(&a), Command::Offline(Offline::Execute(a)) => offline::execute(&a), Command::Offline(Offline::Judge(a)) => offline::judge(&a), diff --git a/core/src/commands/offline.rs b/core/src/commands/offline.rs index 336b778..7b0781c 100644 --- a/core/src/commands/offline.rs +++ b/core/src/commands/offline.rs @@ -6,9 +6,8 @@ use anyhow::Result; use super::runs::{ check_judge_args, create_run, fail_on, judge_run, open_run, seed_execute_judge, seed_run, - teardown_uncached, }; -use crate::cli::{PhaseArgs, PruneArgs, RunArgs, RunFlags, SeedArgs}; +use crate::cli::{OfflineJudgeArgs, PhaseArgs, PruneArgs, RunArgs, RunFlags, SeedArgs}; use crate::eac::{ seed_id, select, Discovered, Engine, Manifest, Phase, Run, Selection, ALL_PHASES, }; @@ -29,19 +28,6 @@ pub fn seed(a: &SeedArgs) -> Result<()> { Ok(()) } -/// Tears down a run's uncached seeds. Cached ones are kept for later runs. -pub fn teardown(a: &SeedArgs) -> Result<()> { - let mut engine = a.scope.project.engine()?; - let run = Run::open(&engine.config().artifacts, &a.run)?; - let seeds = run.read_seeds()?; - if seeds.seeds.values().all(|e| e.cached) { - info!("run {} has no uncached seeds; 'eac offline prune' tears down cached ones", run.id); - return Ok(()); - } - engine.check_seed_credentials(seeds.seeds.values().filter(|e| !e.cached))?; - teardown_uncached(&mut engine, &seeds) -} - /// Executes a seeded run: runs the system under test on each case and saves /// its output. pub fn execute(a: &PhaseArgs) -> Result<()> { @@ -57,11 +43,22 @@ pub fn execute(a: &PhaseArgs) -> Result<()> { Ok(()) } -/// Re-scores a run's recorded outputs without re-running the system. -pub fn judge(a: &PhaseArgs) -> Result<()> { +/// Re-scores a run's recorded outputs without re-running the system, with +/// the judge args the run recorded unless --judge-args replaces them. +pub fn judge(a: &OfflineJudgeArgs) -> Result<()> { let mut engine = a.project.engine()?; engine.set_concurrency(a.concurrency); - let (run, m) = open_run(&engine, &a.run, Mode::Offline, "judge")?; + let (run, mut m) = open_run(&engine, &a.run, Mode::Offline, "judge")?; + if let Some(judge_args) = &a.judge_args { + check_judge_args(judge_args, m.datasets.iter().flat_map(|d| d.used_judges()))?; + for d in &mut m.datasets { + d.judge_args = judge_args.clone(); + let args = d.args.clone(); + engine.validate_args(d, &args)?; + } + // Recorded, so results and a later re-judge use them. + run.write_manifest(&m)?; + } engine.check_credentials(&m.datasets, &[Phase::Judge])?; fail_on(judge_run(&mut engine, &run, &m)?) } diff --git a/core/src/commands/runs.rs b/core/src/commands/runs.rs index b28d36d..aa53c80 100644 --- a/core/src/commands/runs.rs +++ b/core/src/commands/runs.rs @@ -102,7 +102,6 @@ pub fn teardown_uncached(engine: &mut Engine, seeds: &Seeds) -> Result<()> { pub fn judge_run(engine: &mut Engine, run: &Run, m: &Manifest) -> Result { report::phase("judge"); let (summary, results) = engine.judge(run, m)?; - run.write_summary(&summary)?; run.write_results(&results)?; for r in &results { report::saved(&run.results_file(&r.dataset_name)); diff --git a/core/src/eac/phases/credentials.rs b/core/src/eac/phases/credentials.rs index 862d404..1c90038 100644 --- a/core/src/eac/phases/credentials.rs +++ b/core/src/eac/phases/credentials.rs @@ -21,9 +21,6 @@ pub enum Phase { pub const ALL_PHASES: &[Phase] = &[Phase::Seed, Phase::Execute, Phase::Judge]; -/// A credential to check, with the runtime whose SDK checks it. -type Needed = (String, Credential); - impl Engine { /// Checks what the datasets need for phases before any phase starts. On a /// terminal, offers to log in to the credentials that aren't set up. CI @@ -51,9 +48,10 @@ impl Engine { self.ensure(needed) } - /// Checks each credential and, on a terminal, offers to log in to the ones - /// that aren't set up. Fails listing the ones that still aren't. - fn ensure(&mut self, needed: Vec) -> Result<()> { + /// Checks each credential, which comes with the runtime whose SDK checks + /// it, and on a terminal offers to log in to the ones that aren't set up. + /// Fails listing the ones that still aren't. + fn ensure(&mut self, needed: Vec<(String, Credential)>) -> Result<()> { if needed.is_empty() { return Ok(()); } @@ -65,7 +63,7 @@ impl Engine { let mut failures = Vec::new(); // Each credential logged in to, with the variables its login set. - let mut logins: Vec<(Needed, BTreeMap)> = Vec::new(); + let mut logins: Vec<((String, Credential), BTreeMap)> = Vec::new(); for ((runtime, c), ok) in needed.into_iter().zip(checked) { if ok { continue; @@ -86,7 +84,8 @@ impl Engine { if !logins.is_empty() { // Workers restart once, after every login, since imports can be slow. self.add_login_env(logins.iter().flat_map(|(_, env)| env.clone()).collect()); - let logged_in: Vec = logins.iter().map(|(n, _)| n.clone()).collect(); + let logged_in: Vec<(String, Credential)> = + logins.iter().map(|(n, _)| n.clone()).collect(); let rechecked = self.check(&logged_in)?; let mut working = BTreeMap::new(); for (((_, c), env), ok) in logins.into_iter().zip(rechecked) { @@ -107,7 +106,7 @@ impl Engine { } /// Whether each credential works, asking the SDK of each one's runtime. - fn check(&mut self, needed: &[Needed]) -> Result> { + fn check(&mut self, needed: &[(String, Credential)]) -> Result> { let mut ok = vec![false; needed.len()]; let runtimes: BTreeSet<&str> = needed.iter().map(|(r, _)| r.as_str()).collect(); for runtime in runtimes { @@ -163,7 +162,7 @@ impl Engine { } /// What the datasets need for phases, each credential once. -fn needed(datasets: &[Dataset], phases: &[Phase]) -> Vec { +fn needed(datasets: &[Dataset], phases: &[Phase]) -> Vec<(String, Credential)> { let mut needed = Vec::new(); for d in datasets { if phases.contains(&Phase::Seed) { @@ -184,7 +183,7 @@ fn needed(datasets: &[Dataset], phases: &[Phase]) -> Vec { /// Adds the credentials needed doesn't have yet. Credentials with the same /// key are the same, and each runtime checks its own. fn add<'a>( - needed: &mut Vec, + needed: &mut Vec<(String, Credential)>, runtime: &str, credentials: impl IntoIterator, ) { diff --git a/core/src/eac/phases/discover.rs b/core/src/eac/phases/discover.rs index 55d35fb..9227225 100644 --- a/core/src/eac/phases/discover.rs +++ b/core/src/eac/phases/discover.rs @@ -73,7 +73,7 @@ impl Engine { judge_args: &d.judge_args, }; let res: ArgsValidateResult = (self.call(&d.runtime, "args.validate", params)) - .with_context(|| format!("invalid --args or --judge-args for {}", d.name))?; + .with_context(|| format!("validating dataset {}", d.name))?; d.args = args.clone(); d.runner_credentials = res.runner_credentials; d.judge_credentials = res.judge_credentials; diff --git a/core/src/eac/phases/execute.rs b/core/src/eac/phases/execute.rs index 79314bb..7482479 100644 --- a/core/src/eac/phases/execute.rs +++ b/core/src/eac/phases/execute.rs @@ -4,11 +4,11 @@ use std::time::Instant; use anyhow::{Context, Result}; use chrono::Utc; -use super::seed::handles_for; +use super::seed::seed_results_for; use crate::eac::{Dataset, Engine, Manifest, Output, Run, Seeds}; use crate::report::first_line; use crate::schema::{ - Case, CaseRunParams, CaseRunResult, Handle, OnlineExecuteParams, OnlineExecuteResult, Window, + Case, CaseRunParams, CaseRunResult, Object, OnlineExecuteParams, OnlineExecuteResult, Window, }; use crate::worker::{each, Interrupted, Worker}; @@ -18,9 +18,8 @@ impl Engine { pub fn execute(&mut self, run: &Run, m: &Manifest, seeds: &Seeds) -> Result<()> { for d in &m.datasets { let n = self.concurrency(d); - let jobs = d.cases.iter().map(|c| Ok((c, handles_for(seeds, d, c, true)?))); - each(self.workers(&d.runtime, n)?, jobs, |worker, (c, handles)| { - run.write_output(&run_case(worker, d, c, handles)?) + each(self.workers(&d.runtime, n)?, d.cases.iter().collect(), |worker, c| { + run.write_output(&run_case(worker, d, c, seed_results_for(seeds, d, c, true)?)?) })?; } Ok(()) @@ -46,12 +45,12 @@ impl Engine { dataset: d.name.clone(), case: c.name.clone(), input: c.input.clone(), - output: c.output.clone(), + run_results: c.run_results.clone(), conversation_id: c.conversation_id.clone(), ..Default::default() }); // Outputs are saved on their own, so the manifest's cases leave them out. - d.cases.push(Case { output: None, conversation_id: None, ..c }); + d.cases.push(Case { run_results: None, conversation_id: None, ..c }); } } Ok(outputs) @@ -64,7 +63,7 @@ fn run_case( worker: &mut Worker, d: &Dataset, c: &Case, - seeds: BTreeMap<&str, &Handle>, + seed_results: BTreeMap<&str, &Object>, ) -> Result { // Tags the agent run so its trace can be found later. let conversation_id = format!("eval-{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); @@ -73,7 +72,7 @@ fn run_case( let params = CaseRunParams { dataset: &d.code, case: c, - seeds, + seed_results, args: &d.args, conversation_id: &conversation_id, }; @@ -91,7 +90,7 @@ fn run_case( }; match res { Ok(res) => { - out.output = res.output; + out.run_results = res.run_results; out.metrics = res.metrics; out.conversation_id = res.conversation_id.or(out.conversation_id); detail!("{}/{} ran in {:.2}s", d.name, c.name, out.duration_seconds); diff --git a/core/src/eac/phases/judge.rs b/core/src/eac/phases/judge.rs index 23bae92..7e6b7d5 100644 --- a/core/src/eac/phases/judge.rs +++ b/core/src/eac/phases/judge.rs @@ -4,7 +4,7 @@ use std::time::Instant; use anyhow::{anyhow, Result}; -use super::seed::handles_for; +use super::seed::seed_results_for; use crate::eac::{ aggregate, case_result, run_result, status_for, CaseResult, Dataset, Engine, Manifest, Output, Run, RunResult, Scored, Seeds, Status, Summary, TraceFile, @@ -19,32 +19,19 @@ impl Engine { /// time. pub fn judge(&mut self, run: &Run, m: &Manifest) -> Result<(Summary, Vec)> { let seeds = if m.online { Seeds::default() } else { run.read_seeds()? }; - let mut summary = Summary { - run_id: run.id.clone(), - created_at: m.created_at, - online: m.online, - ..Default::default() - }; + let mut summary = + Summary { run_id: run.id.clone(), online: m.online, ..Default::default() }; let mut results = Vec::new(); let start = Instant::now(); for d in &m.datasets { let dataset_start = Instant::now(); let n = self.concurrency(d); - let jobs = d.cases.iter().map(|c| { - let out = run.read_output(&d.name, &c.name).map_err(|_| { - anyhow!( - "no recorded output for {}/{}: run 'eac offline execute' first", - d.name, - c.name - ) - })?; - Ok((c, out, run.read_trace(&d.name, &c.name))) - }); let judging = Judging { run, online: m.online, d, seeds: &seeds }; - let judged = each(self.workers(&d.runtime, n)?, jobs, |worker, (c, out, trace)| { - judging.case(worker, c, out, trace) - })?; + let judged = + each(self.workers(&d.runtime, n)?, d.cases.iter().collect(), |worker, c| { + judging.case(worker, c) + })?; let mut cases = Vec::new(); for (scored, case) in judged { @@ -56,7 +43,7 @@ impl Engine { summary.duration_seconds = start.elapsed().as_secs_f64(); if summary.online { - summary.judges = aggregate(&run.read_scores()?); + summary.judges = aggregate(&summary.results); } Ok((summary, results)) } @@ -71,22 +58,20 @@ struct Judging<'a> { } impl Judging<'_> { - /// Judges one case's recorded output, and saves its scores and any trace - /// the judges fetched. - fn case( - &self, - worker: &mut Worker, - c: &Case, - out: Output, - mut trace: Option, - ) -> Result<(Scored, CaseResult)> { + /// Judges one case's recorded output, and saves any trace the judges + /// fetched. + fn case(&self, worker: &mut Worker, c: &Case) -> Result<(Scored, CaseResult)> { let (run, d) = (self.run, self.d); + let out = run.read_output(&d.name, &c.name).map_err(|_| { + anyhow!("no recorded output for {}/{}: run 'eac offline execute' first", d.name, c.name) + })?; + let mut trace = run.read_trace(&d.name, &c.name); let res = self.call(worker, c, &out, trace.as_ref().map(|t| &t.trace)); let mut scored = Scored { dataset: d.name.clone(), case: c.name.clone(), status: Status::Error, - scores: vec![], + judge_results: vec![], error: out.error.clone(), duration_seconds: out.duration_seconds, }; @@ -102,15 +87,14 @@ impl Judging<'_> { run.write_trace(&d.name, &c.name, &fetched)?; trace = Some(fetched); } - scored.status = status_for(&res.scores, &out.error); - scored.scores = res.scores; + scored.status = status_for(&res.judge_results, &out.error); + scored.judge_results = res.judge_results; } Err(e) if e.is::() => return Err(e), // A runner error is the more useful one to report. Err(e) if scored.error.is_empty() => scored.error = format!("judge failed: {e:#}"), Err(_) => {} } - run.write_scored(&scored)?; if !self.online { detail!("{}/{} judged", d.name, c.name); } @@ -129,7 +113,7 @@ impl Judging<'_> { ) -> Result { let d = self.d; let case = Case { - output: out.output.clone(), + run_results: out.run_results.clone(), conversation_id: out.conversation_id.clone(), ..c.clone() }; @@ -148,7 +132,7 @@ impl Judging<'_> { case, judges: &d.judges, error: Some(out.error.as_str()).filter(|e| !e.is_empty()), - seeds: handles_for(self.seeds, d, c, false)?, + seed_results: seed_results_for(self.seeds, d, c, false)?, judge_args: &d.judge_args, trace: saved_trace, started_at: out.started_at, diff --git a/core/src/eac/phases/seed.rs b/core/src/eac/phases/seed.rs index 656eb90..b17e5ae 100644 --- a/core/src/eac/phases/seed.rs +++ b/core/src/eac/phases/seed.rs @@ -6,7 +6,7 @@ use serde_json::Value; use crate::eac::{ read_seed_cache, seed_id, write_seed_cache, Dataset, Engine, Manifest, SeedEntry, Seeds, }; -use crate::schema::{Case, Handle, SeedSetupParams, SeedSetupResult, SeedTeardownParams}; +use crate::schema::{Case, Object, SeedSetupParams, SeedSetupResult, SeedTeardownParams}; impl Engine { /// Sets up every seed the run's cases need, once per seed id. Cached seeds @@ -48,7 +48,7 @@ impl Engine { runtime: d.runtime.clone(), dataset: d.name.clone(), code: d.code.clone(), - handle: res.handle, + seed_results: res.seed_results, cached: seed.cache, }; if seed.cache { @@ -104,8 +104,11 @@ impl Engine { } fn teardown_one(&mut self, entry: &SeedEntry) -> Result<()> { - let params = - SeedTeardownParams { dataset: &entry.code, seed: &entry.seed, handle: &entry.handle }; + let params = SeedTeardownParams { + dataset: &entry.code, + seed: &entry.seed, + seed_results: &entry.seed_results, + }; match self.call::(&entry.runtime, "seed.teardown", params) { Ok(_) => detail!("tore down {} ({})", entry.seed.name, entry.dataset), Err(e) => { @@ -117,19 +120,19 @@ impl Engine { } } -/// The case's seed handles by seed name. Executing needs every one, but +/// The case's seed results by seed name. Executing needs every one, but /// judging makes do with what the run has. -pub(super) fn handles_for<'a>( +pub(super) fn seed_results_for<'a>( seeds: &'a Seeds, d: &Dataset, c: &'a Case, required: bool, -) -> Result> { - let mut handles = BTreeMap::new(); +) -> Result> { + let mut seed_results = BTreeMap::new(); for seed in &c.seeds { match seeds.seeds.get(&seed_id(&d.runtime, seed)) { Some(entry) => { - handles.insert(seed.name.as_str(), &entry.handle); + seed_results.insert(seed.name.as_str(), &entry.seed_results); } None if required => bail!( "case {}/{} needs seed {:?} but it is missing from seeds.json: run 'eac offline seed' first", @@ -140,5 +143,5 @@ pub(super) fn handles_for<'a>( None => {} } } - Ok(handles) + Ok(seed_results) } diff --git a/core/src/eac/run/cases.rs b/core/src/eac/run/cases.rs index 259a9f8..e7cd112 100644 --- a/core/src/eac/run/cases.rs +++ b/core/src/eac/run/cases.rs @@ -37,7 +37,7 @@ pub struct Output { #[serde(default, skip_serializing_if = "is_empty")] pub input: Option, #[serde(default)] - pub output: Option, + pub run_results: Option, #[serde(default, deserialize_with = "nullable", skip_serializing_if = "String::is_empty")] pub error: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -62,24 +62,23 @@ pub struct TraceFile { pub metrics: Option, } -#[derive(Clone, Debug, Serialize, Deserialize)] +/// A judged case, for the summary. +#[derive(Clone, Debug)] pub struct Scored { pub dataset: String, pub case: String, pub status: Status, - #[serde(default, deserialize_with = "nullable")] - pub scores: Vec, - #[serde(default, deserialize_with = "nullable", skip_serializing_if = "String::is_empty")] + pub judge_results: Vec, pub error: String, - #[serde(default)] pub duration_seconds: f64, } -/// An error always wins. A case with no non-null score is skipped, otherwise -/// every non-null score must be 1.0 to pass. -pub fn status_for(scores: &[Score], exec_err: &str) -> Status { - let scores: Vec = scores.iter().filter_map(|s| s.score).collect(); - if !exec_err.is_empty() { +/// An error, the runner's or a judge's, always wins. A case with no non-null +/// score is skipped, otherwise every non-null score must be 1.0 to pass. +pub fn status_for(judge_results: &[Score], exec_err: &str) -> Status { + let errored = judge_results.iter().any(|s| s.error.is_some()); + let scores: Vec = judge_results.iter().filter_map(|s| s.score).collect(); + if !exec_err.is_empty() || errored { Status::Error } else if scores.is_empty() { Status::Skipped @@ -107,5 +106,7 @@ mod tests { assert_eq!(status_for(&[], ""), Status::Skipped); assert_eq!(status_for(&[], "boom"), Status::Error); assert_eq!(status_for(&[score(Some(1.0))], "boom"), Status::Error); + let raised = Score { error: Some("TimeoutError".into()), ..score(None) }; + assert_eq!(status_for(&[score(Some(1.0)), raised], ""), Status::Error); } } diff --git a/core/src/eac/run/dir.rs b/core/src/eac/run/dir.rs index 925dd6d..778fbcd 100644 --- a/core/src/eac/run/dir.rs +++ b/core/src/eac/run/dir.rs @@ -8,11 +8,10 @@ use chrono::Utc; use serde::de::DeserializeOwned; use serde::Serialize; -use super::cases::{Output, Scored, TraceFile}; +use super::cases::{Output, TraceFile}; use super::manifest::Manifest; use super::results::RunResult; use super::seeds::Seeds; -use super::summary::Summary; pub struct Run { pub id: String, @@ -62,7 +61,7 @@ impl Run { Ok(Run { id, dir }) } - /// What the seed phase saved: each seed's handle. + /// What the seed phase saved: each seed's results. pub fn seeds_file(&self) -> PathBuf { self.dir.join("seeds.json") } @@ -90,10 +89,6 @@ impl Run { write_json(&self.seeds_file(), s) } - pub fn write_summary(&self, s: &Summary) -> Result<()> { - write_json(&self.dir.join("summary.json"), s) - } - pub fn write_output(&self, o: &Output) -> Result<()> { write_json(&self.case_path("outputs", &o.dataset, &o.case), o) } @@ -102,10 +97,6 @@ impl Run { write_json(&self.case_path("traces", dataset, case), t) } - pub fn write_scored(&self, s: &Scored) -> Result<()> { - write_json(&self.case_path("scores", &s.dataset, &s.case), s) - } - pub fn write_results(&self, results: &[RunResult]) -> Result<()> { for r in results { write_json(&self.results_file(&r.dataset_name), r)?; @@ -131,33 +122,6 @@ impl Run { pub fn read_trace(&self, dataset: &str, case: &str) -> Option { read_json(&self.case_path("traces", dataset, case)).ok() } - - pub fn read_scores(&self) -> Result> { - let mut out = read_all::(&self.dir.join("scores"))?; - out.sort_by(|a, b| (&a.dataset, &a.case).cmp(&(&b.dataset, &b.case))); - Ok(out) - } -} - -/// Reads every .json file under dir, which may not exist. -fn read_all(dir: &Path) -> Result> { - let mut paths = Vec::new(); - find_json(dir, &mut paths); - paths.iter().map(|p| read_json(p)).collect() -} - -fn find_json(dir: &Path, out: &mut Vec) { - let Ok(entries) = fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if entry.file_type().is_ok_and(|t| t.is_dir()) { - find_json(&path, out); - } else if path.extension().is_some_and(|ext| ext == "json") { - out.push(path); - } - } } pub(super) fn write_json(path: &Path, value: &impl Serialize) -> Result<()> { diff --git a/core/src/eac/run/mod.rs b/core/src/eac/run/mod.rs index e3f5558..cbf8102 100644 --- a/core/src/eac/run/mod.rs +++ b/core/src/eac/run/mod.rs @@ -2,12 +2,10 @@ //! run as a separate command: //! //! manifest.json what was discovered and selected -//! seeds.json seed id -> handle, for every seed the run used +//! seeds.json seed id -> seed results, for every seed the run used //! outputs//.json raw output, no scores //! traces//.json agent traces the judges fetched -//! scores//.json scores and status -//! results/.json each dataset's results, for scripts to upload -//! summary.json totals +//! results/.json each dataset's scores, for scripts to upload //! //! Cached seeds outlive runs, in /seed-cache.json. diff --git a/core/src/eac/run/results.rs b/core/src/eac/run/results.rs index bde0cd3..80bb91d 100644 --- a/core/src/eac/run/results.rs +++ b/core/src/eac/run/results.rs @@ -15,14 +15,13 @@ use crate::schema::{schema_settings, Case, Metrics, Object, Score, Window}; /// The results format's version. Bump it on any change a reader could trip /// over, like a removed or renamed field or a new status. -pub const RESULTS_VERSION: u32 = 3; +pub const RESULTS_VERSION: u32 = 1; -/// The results of judging one dataset in one run, saved as -/// results/.json in the run's directory. +/// One dataset's results from one run, saved as results/.json. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[schemars(title = "eac results")] pub struct RunResult { - /// The version of this format. Changes that could break a reader bump it. + /// This format's version, bumped by any change that could break a reader. #[schemars(extend("const" = RESULTS_VERSION))] pub schema_version: u32, pub run_id: String, @@ -34,7 +33,7 @@ pub struct RunResult { pub cases: Vec, /// How long judging the dataset took. pub duration_seconds: f64, - /// The dataset.yml's `metadata`, with the run's --meta values over it. + /// The dataset.yml's `metadata`, overridden by --meta. pub metadata: Object, pub source: Source, } @@ -51,7 +50,7 @@ pub enum Args { pub struct OfflineArgs { /// --args. pub runner_args: Object, - /// A comparison's judges, replaces each case's defined judges. + /// A comparison's judges, used instead of each case's own. pub judges: Vec, /// --judge-args. pub judge_args: Object, @@ -77,17 +76,15 @@ pub struct CaseResult { pub status: Status, pub input: Object, /// Null if the runner failed. - pub output: Option, + pub run_results: Option, pub expected_output: Option, - /// Why the case errored. pub error: Option, - pub scores: Vec, - /// The case's LLM usage, taken from its agent trace when a judge fetched - /// one. - pub otel_metrics: Metrics, - /// The agent conversation, for looking up its trace. + pub judge_results: Vec, + /// The agent's LLM usage on the case. + pub llm_metrics: Metrics, + /// The agent's conversation ID used for agent trace retrieval. pub conversation_id: Option, - /// The output's `attributes` object, plus the case's `splits`. + /// The run results' `attributes` object, plus the case's `splits`. pub attributes: Object, /// When the runner started. Null for online runs. pub start_time: Option>, @@ -106,7 +103,7 @@ pub fn case_result( ) -> CaseResult { let metrics = trace_metrics.or_else(|| out.metrics.clone()).unwrap_or_default(); let mut attributes = out - .output + .run_results .as_ref() .and_then(|o| o.get("attributes")) .and_then(Value::as_object) @@ -119,11 +116,11 @@ pub fn case_result( name: case.name.clone(), status: scored.status, input: out.input.clone().unwrap_or_default(), - output: out.output.clone(), + run_results: out.run_results.clone(), expected_output: case.expected_output.clone(), error: Some(scored.error.clone()).filter(|e| !e.is_empty()), - scores: scored.scores.clone(), - otel_metrics: metrics, + judge_results: scored.judge_results.clone(), + llm_metrics: metrics, conversation_id: out.conversation_id.clone(), attributes, start_time: out.started_at, diff --git a/core/src/eac/run/seeds.rs b/core/src/eac/run/seeds.rs index 7806f89..d586910 100644 --- a/core/src/eac/run/seeds.rs +++ b/core/src/eac/run/seeds.rs @@ -8,7 +8,7 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; use super::dir::{read_json_or_default, write_json}; -use crate::schema::{nullable, DatasetRef, Handle, Seed}; +use crate::schema::{nullable, DatasetRef, Object, Seed}; /// Keyed by seed_id, so cases needing the same fixture share one entry. #[derive(Clone, Debug, Default, Serialize, Deserialize)] @@ -28,7 +28,7 @@ pub struct SeedEntry { /// Where the seed's code is, for tearing it down. pub code: DatasetRef, #[serde(default, deserialize_with = "nullable")] - pub handle: Handle, + pub seed_results: Object, /// Kept in the seed cache instead of torn down with the run. #[serde(default)] pub cached: bool, diff --git a/core/src/eac/run/summary.rs b/core/src/eac/run/summary.rs index 0a5da96..4d39306 100644 --- a/core/src/eac/run/summary.rs +++ b/core/src/eac/run/summary.rs @@ -1,12 +1,8 @@ -//! summary.json: a judged run's totals, and each judge's mean for online runs. - -use chrono::{DateTime, Utc}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; +//! A judged run's totals, and each judge's mean for online runs, for printing. use super::cases::{Scored, Status}; -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +#[derive(Clone, Debug, Default)] pub struct Summary { pub run_id: String, pub total: usize, @@ -14,17 +10,12 @@ pub struct Summary { pub failed: usize, pub errors: usize, /// Cases no judge applied to. - #[serde(default)] pub skipped: usize, pub duration_seconds: f64, - pub created_at: DateTime, /// Online runs report each judge's mean instead of a verdict. - #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub online: bool, - #[serde(default, skip_serializing_if = "Vec::is_empty")] pub judges: Vec, - /// Every scored case, in judge order, for printing. - #[serde(skip)] + /// Every scored case, in judge order. pub results: Vec, } @@ -44,12 +35,12 @@ impl Summary { /// The mean of every non-null score. pub fn mean_score(&self) -> Option { let scores: Vec = - self.results.iter().flat_map(|r| &r.scores).filter_map(|s| s.score).collect(); + self.results.iter().flat_map(|r| &r.judge_results).filter_map(|s| s.score).collect(); (!scores.is_empty()).then(|| scores.iter().sum::() / scores.len() as f64) } } -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[derive(Clone, Debug)] pub struct JudgeStat { pub name: String, pub mean: f64, @@ -59,7 +50,7 @@ pub struct JudgeStat { /// Each judge's mean non-null score, in the order the judges first appear. pub fn aggregate(scored: &[Scored]) -> Vec { let mut stats: Vec = Vec::new(); - for sc in scored.iter().flat_map(|s| &s.scores) { + for sc in scored.iter().flat_map(|s| &s.judge_results) { let Some(score) = sc.score else { continue }; let i = match stats.iter().position(|s| s.name == sc.name) { Some(i) => i, @@ -92,7 +83,7 @@ mod tests { dataset: "d".into(), case: "c".into(), status: Status::Passed, - scores: values.iter().map(|v| score(*v)).collect(), + judge_results: values.iter().map(|v| score(*v)).collect(), error: String::new(), duration_seconds: 0.0, }; diff --git a/core/src/report/format.rs b/core/src/report/format.rs index 6ff6274..f0d3538 100644 --- a/core/src/report/format.rs +++ b/core/src/report/format.rs @@ -1,27 +1,8 @@ -/// Three significant digits, like Go's %.3g: "1", "0.5", "0.667". +/// A score to three decimals, without trailing zeros: "1", "0.5", "0.667". pub fn format_score(score: Option) -> String { - let Some(x) = score else { - return "—".to_string(); - }; - if x == 0.0 || !x.is_finite() { - return x.to_string(); - } - // Rounds to three significant digits, e.g. "6.67e-1". - let sci = format!("{x:.2e}"); - let (mantissa, exp) = sci.split_once('e').expect("exponent format"); - let exp: i32 = exp.parse().expect("integer exponent"); - if !(-4..3).contains(&exp) { - let sign = if exp < 0 { '-' } else { '+' }; - return format!("{}e{sign}{:02}", trim_zeros(mantissa), exp.abs()); - } - trim_zeros(&format!("{x:.*}", (2 - exp) as usize)).to_string() -} - -fn trim_zeros(s: &str) -> &str { - if s.contains('.') { - s.trim_end_matches('0').trim_end_matches('.') - } else { - s + match score { + Some(x) => format!("{x:.3}").trim_end_matches('0').trim_end_matches('.').to_string(), + None => "—".to_string(), } } @@ -67,8 +48,6 @@ mod tests { assert_eq!(format_score(Some(0.5)), "0.5"); assert_eq!(format_score(Some(2.0 / 3.0)), "0.667"); assert_eq!(format_score(Some(0.9999)), "1"); - assert_eq!(format_score(Some(0.00012345)), "0.000123"); - assert_eq!(format_score(Some(0.0000123)), "1.23e-05"); } #[test] diff --git a/core/src/report/tables.rs b/core/src/report/tables.rs index 476ef9e..1248ce7 100644 --- a/core/src/report/tables.rs +++ b/core/src/report/tables.rs @@ -24,8 +24,11 @@ fn print_offline(s: &Summary) { let name = format!("{}/{}", r.dataset, r.case); let status = r.status.as_str().to_uppercase(); rows.push(vec![name.clone(), status, format_duration(r.duration_seconds)]); - for sc in &r.scores { + for sc in &r.judge_results { rows.push(vec![format!(" └ {}", sc.name), format_score(sc.score), String::new()]); + if let Some(error) = &sc.error { + errors.push(format!("{name} › {}: {}", sc.name, first_line(error))); + } let explanation = sc.explanation.as_deref().unwrap_or_default(); if sc.score.is_some_and(|v| v < 1.0) && !explanation.is_empty() { misses.push(format!("{name} › {}: {}", sc.name, first_line(explanation))); @@ -63,7 +66,7 @@ fn print_online(s: &Summary) { print_table(&["Judge", "Mean score", "Cases"], &rows, None); let cases = paint(BOLD, &format!("{} {}", s.total, plural(s.total, "case", "cases"))); - let below = paint(DIM, &format!("{} below 1 or errored; see scores/", s.failed + s.errors)); + let below = paint(DIM, &format!("{} below 1 or errored; see results/", s.failed + s.errors)); eprintln!("\n {cases} {below}"); detail!("judged in {}", format_duration(s.duration_seconds)); } diff --git a/core/src/schema/document.rs b/core/src/schema/document.rs index 51ad2d1..54fa238 100644 --- a/core/src/schema/document.rs +++ b/core/src/schema/document.rs @@ -17,36 +17,35 @@ pub fn document() -> Value { m.add::( "discover", - "Imports the dataset's code and describes it, with no side effects beyond the import.", + "Imports the dataset's code and describes it.", ); m.add::( "args.validate", - "Returns what the run's runner and judges need, before anything is set up. Return an error to reject the args.", + "Returns the credentials the run's runner and judges need.", ); m.add::( "seed.setup", - "Sets up a seed, or loads a cached one from its own cache. eac sends each seed key once.", + "Sets up a seed, or loads a cached one from its own cache.", ); m.add::( "seed.teardown", - "Tears down a seed that seed.setup returned.", + "Tears down a seed, removing a cached one from its own cache first.", ); m.add::( "case.run", - "Runs the system under test on a case and returns its raw output, unscored.", + "Runs the system under test on a case and returns its run results.", ); m.add::( "case.judge", - "Scores a recorded output with the case's judges, or with the judges in params if any are named. \ - Without a saved trace, the judges may fetch one.", + "Scores a case's run results with its judges, or the judges in params.", ); m.add::( "online.execute", - "Returns at most limit production runs from the window, as cases with their outputs.", + "Returns up to `limit` production runs from the window, as cases with their outputs.", ); m.add::( "online.judge", - "Scores a collected case with the named online judges.", + "Scores a collected case with the judges picked with --judge.", ); m.add::( "credentials.check", @@ -54,7 +53,7 @@ pub fn document() -> Value { ); m.add::( "credentials.login", - "Logs in to a credential. Sent to a worker started on the terminal, so login can prompt.", + "Logs in to a credential. Runs on the terminal, so it can prompt.", ); json!({ diff --git a/core/src/schema/protocol.schema.json b/core/src/schema/protocol.schema.json index ea0aef3..e6e65ed 100644 --- a/core/src/schema/protocol.schema.json +++ b/core/src/schema/protocol.schema.json @@ -13,7 +13,7 @@ "type": "object" }, "judges": { - "description": "For an online run, the judges picked with --judge. For an offline run, judges that replace every case's own, as in a comparison. Empty keeps each case's judges.", + "description": "Online: the judges picked with --judge. Offline: judges that replace every case's. Empty keeps each case's judges.", "items": { "type": "string" }, @@ -39,7 +39,7 @@ }, "type": "array" }, - "description": "The credentials each of the run's judges needs, by judge name.", + "description": "The credentials each of the run's judges needs by judge name.", "type": "object" }, "runner_credentials": { @@ -53,10 +53,10 @@ "type": "object" }, "Case": { - "description": "An offline case, or a production run collected for online judging.", + "description": "An offline case's name.", "properties": { "conversation_id": { - "description": "The ID the agent's run was tagged with, for judges to fetch its trace by. Set like `output`.", + "description": "The agent's conversation ID used for agent trace retrieval.", "type": [ "string", "null" @@ -79,7 +79,6 @@ ] }, "judges": { - "description": "The judges' names, for display. The worker runs the judges itself.", "items": { "type": "string" }, @@ -89,7 +88,7 @@ "description": "Unique in its dataset. An online case's id.", "type": "string" }, - "output": { + "run_results": { "description": "What the system produced: a collected online case's production output, or the runner's output when eac sends the case to be judged. Absent otherwise, including when the runner failed.", "type": [ "object", @@ -117,8 +116,7 @@ "CaseJudgeParams": { "properties": { "case": { - "$ref": "#/$defs/Case", - "description": "With the runner's `output` and `conversation_id`." + "$ref": "#/$defs/Case" }, "dataset": { "$ref": "#/$defs/DatasetRef" @@ -131,7 +129,6 @@ ] }, "error": { - "description": "Why the runner failed, in which case there's no output.", "type": [ "string", "null" @@ -142,15 +139,15 @@ "type": "object" }, "judges": { - "description": "Judges to use instead of the case's own, as in a comparison. Empty keeps the case's judges.", + "description": "Judges to use instead of the case's own. Empty defaults to the case's judges.", "items": { "type": "string" }, "type": "array" }, - "seeds": { + "seed_results": { "additionalProperties": { - "$ref": "#/$defs/Handle" + "type": "object" }, "type": "object" }, @@ -175,7 +172,7 @@ "CaseJudgeResult": { "description": "What case.judge and online.judge return.", "properties": { - "scores": { + "judge_results": { "items": { "$ref": "#/$defs/Score" }, @@ -213,11 +210,11 @@ "dataset": { "$ref": "#/$defs/DatasetRef" }, - "seeds": { + "seed_results": { "additionalProperties": { - "$ref": "#/$defs/Handle" + "type": "object" }, - "description": "Each seed's handle, by seed name.", + "description": "Each seed's results, by seed name.", "type": "object" } }, @@ -247,7 +244,7 @@ } ] }, - "output": { + "run_results": { "description": "Saved for the judge phase, so it must be JSON.", "type": [ "object", @@ -258,7 +255,7 @@ "type": "object" }, "Credential": { - "description": "A credential a seed, runner or judge needs, like a token or a CLI login. The SDK rebuilds it from `path` and `fields`, so eac can check each distinct one once.", + "description": "A credential a seed, runner or judge needs, like a token or a CLI login.", "properties": { "fields": { "description": "The arguments its class is built with.", @@ -326,14 +323,14 @@ "additionalProperties": { "type": "string" }, - "description": "Environment variables the credential sets. eac passes them to every process it starts and saves them once the credential checks out.", + "description": "Environment variables the credential sets. eac saves them for later commands.", "type": "object" } }, "type": "object" }, "DatasetRef": { - "description": "Where a dataset's code is, from its dataset.yml. Sent with every method that needs the dataset, so any worker can import it.", + "description": "Where a dataset's code is, from its dataset.yml. Code references are `module.path:attr` or `./file.py:attr`, relative to the project root.", "properties": { "cases": { "description": "The dataset's cases. Offline only.", @@ -353,7 +350,6 @@ "$ref": "#/$defs/Mode" }, "name": { - "description": "The dataset's name, from its dataset.yml.", "type": "string" }, "runner": { @@ -380,7 +376,7 @@ "type": "object" }, "DiscoverResult": { - "description": "What eac learns by importing the dataset's code. Its dataset.yml covers the rest.", + "description": "What eac learns by importing the dataset's code.", "properties": { "cases": { "description": "Every case. Offline only.", @@ -406,15 +402,11 @@ ], "type": "object" }, - "Handle": { - "description": "What a seed's setup returned. Saved to seeds.json for later phases, so it must be JSON.", - "type": "object" - }, "JudgeRef": { "description": "A judge named in a dataset.yml's online.judges.", "properties": { "name": { - "description": "The name --judge and --judge-args use. Scores still carry the judge's own name.", + "description": "The name --judge and --judge-args use.", "type": "string" }, "path": { @@ -492,7 +484,7 @@ "OnlineExecuteResult": { "properties": { "cases": { - "description": "One case per production run, each with its `output` and, if it has one, its `conversation_id`.", + "description": "One case per production run, with its `run_results` and `conversation_id`.", "items": { "$ref": "#/$defs/Case" }, @@ -504,8 +496,7 @@ "OnlineJudgeParams": { "properties": { "case": { - "$ref": "#/$defs/Case", - "description": "A collected case, with its `output` and `conversation_id`." + "$ref": "#/$defs/Case" }, "dataset": { "$ref": "#/$defs/DatasetRef" @@ -515,14 +506,14 @@ "type": "object" }, "judges": { - "description": "The judges picked, by their YAML names.", + "description": "The judges picked with --judge.", "items": { "type": "string" }, "type": "array" }, "trace": { - "description": "As in case.judge. The case's conversation_id identifies the trace." + "description": "The agent trace an earlier judge phase saved. Without one, the judges may fetch it by the case's conversation_id." } }, "required": [ @@ -586,10 +577,15 @@ "type": "object" }, "Score": { - "description": "A judge's score from 0 to 1. A null score is recorded but doesn't count toward pass or fail.", + "description": "A judge's score from 0 to 1. Null doesn't count toward pass or fail.", "properties": { + "error": { + "type": [ + "string", + "null" + ] + }, "explanation": { - "description": "Why the judge gave this score.", "type": [ "string", "null" @@ -607,14 +603,12 @@ "description": "The judge's own LLM usage." }, "metadata": { - "description": "Anything else the judge recorded.", "type": [ "object", "null" ] }, "name": { - "description": "The judge's name.", "type": "string" }, "score": { @@ -633,11 +627,11 @@ "description": "A fixture. Seeds with the same `key`, a content hash, are set up once and shared.", "properties": { "cache": { - "description": "Whether to reuse the seed across runs while its key matches. Turn it off for seeds the agent changes, so they're torn down after each run.", + "description": "Whether to keep the seed for later runs, instead of tearing it down after this one.", "type": "boolean" }, "credentials": { - "description": "The credentials setting it up or tearing it down needs, including its children's.", + "description": "The credentials setting it up or tearing it down needs.", "items": { "$ref": "#/$defs/Credential" }, @@ -677,34 +671,35 @@ "description": "The seed's own cache had it, so nothing was set up.", "type": "boolean" }, - "handle": { - "$ref": "#/$defs/Handle" + "seed_results": { + "description": "What the seed's setup returned. Saved for later phases, so it must be JSON.", + "type": "object" } }, "type": "object" }, "SeedTeardownParams": { - "description": "A cached seed is also removed from its own cache before it's torn down.", "properties": { "dataset": { "$ref": "#/$defs/DatasetRef" }, - "handle": { - "$ref": "#/$defs/Handle" - }, "seed": { "$ref": "#/$defs/Seed" + }, + "seed_results": { + "description": "What seed.setup returned.", + "type": "object" } }, "required": [ "dataset", "seed", - "handle" + "seed_results" ], "type": "object" }, "Window": { - "description": "The params to select cases from production", + "description": "Which production runs to collect.", "properties": { "limit": { "type": "integer" @@ -736,7 +731,7 @@ "properties": { "args.validate": { "additionalProperties": false, - "description": "Returns what the run's runner and judges need, before anything is set up. Return an error to reject the args.", + "description": "Returns the credentials the run's runner and judges need.", "properties": { "params": { "$ref": "#/$defs/ArgsValidateParams" @@ -753,7 +748,7 @@ }, "case.judge": { "additionalProperties": false, - "description": "Scores a recorded output with the case's judges, or with the judges in params if any are named. Without a saved trace, the judges may fetch one.", + "description": "Scores a case's run results with its judges, or the judges in params.", "properties": { "params": { "$ref": "#/$defs/CaseJudgeParams" @@ -770,7 +765,7 @@ }, "case.run": { "additionalProperties": false, - "description": "Runs the system under test on a case and returns its raw output, unscored.", + "description": "Runs the system under test on a case and returns its run results.", "properties": { "params": { "$ref": "#/$defs/CaseRunParams" @@ -804,7 +799,7 @@ }, "credentials.login": { "additionalProperties": false, - "description": "Logs in to a credential. Sent to a worker started on the terminal, so login can prompt.", + "description": "Logs in to a credential. Runs on the terminal, so it can prompt.", "properties": { "params": { "$ref": "#/$defs/CredentialsLoginParams" @@ -821,7 +816,7 @@ }, "discover": { "additionalProperties": false, - "description": "Imports the dataset's code and describes it, with no side effects beyond the import.", + "description": "Imports the dataset's code and describes it.", "properties": { "params": { "$ref": "#/$defs/DiscoverParams" @@ -838,7 +833,7 @@ }, "online.execute": { "additionalProperties": false, - "description": "Returns at most limit production runs from the window, as cases with their outputs.", + "description": "Returns up to `limit` production runs from the window, as cases with their outputs.", "properties": { "params": { "$ref": "#/$defs/OnlineExecuteParams" @@ -855,7 +850,7 @@ }, "online.judge": { "additionalProperties": false, - "description": "Scores a collected case with the named online judges.", + "description": "Scores a collected case with the judges picked with --judge.", "properties": { "params": { "$ref": "#/$defs/OnlineJudgeParams" @@ -872,7 +867,7 @@ }, "seed.setup": { "additionalProperties": false, - "description": "Sets up a seed, or loads a cached one from its own cache. eac sends each seed key once.", + "description": "Sets up a seed, or loads a cached one from its own cache.", "properties": { "params": { "$ref": "#/$defs/SeedSetupParams" @@ -889,7 +884,7 @@ }, "seed.teardown": { "additionalProperties": false, - "description": "Tears down a seed that seed.setup returned.", + "description": "Tears down a seed, removing a cached one from its own cache first.", "properties": { "params": { "$ref": "#/$defs/SeedTeardownParams" diff --git a/core/src/schema/types.rs b/core/src/schema/types.rs index 2739b79..cf6b4e5 100644 --- a/core/src/schema/types.rs +++ b/core/src/schema/types.rs @@ -8,7 +8,7 @@ use super::fields::{is_empty, is_true, nullable, yes}; pub type Object = Map; -/// An offline case, or a production run collected for online judging. +/// An offline case's name. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct Case { /// Unique in its dataset. An online case's id. @@ -21,9 +21,8 @@ pub struct Case { /// or the runner's output when eac sends the case to be judged. Absent /// otherwise, including when the runner failed. #[serde(default, skip_serializing_if = "Option::is_none")] - pub output: Option, - /// The ID the agent's run was tagged with, for judges to fetch its trace - /// by. Set like `output`. + pub run_results: Option, + /// The agent's conversation ID used for agent trace retrieval. #[serde(default, skip_serializing_if = "Option::is_none")] pub conversation_id: Option, #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] @@ -33,7 +32,6 @@ pub struct Case { pub enabled: bool, #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub seeds: Vec, - /// The judges' names, for display. The worker runs the judges itself. #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub judges: Vec, } @@ -44,7 +42,7 @@ impl Default for Case { name: String::new(), input: None, expected_output: None, - output: None, + run_results: None, conversation_id: None, splits: vec![], enabled: true, @@ -60,23 +58,20 @@ impl Default for Case { pub struct Seed { pub name: String, pub key: String, - /// Whether to reuse the seed across runs while its key matches. Turn it off - /// for seeds the agent changes, so they're torn down after each run. + /// Whether to keep the seed for later runs, instead of tearing it down after + /// this one. #[serde(default = "yes", skip_serializing_if = "is_true")] pub cache: bool, - /// The credentials setting it up or tearing it down needs, including its - /// children's. + /// The credentials setting it up or tearing it down needs. #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub credentials: Vec, } -/// A credential a seed, runner or judge needs, like a token or a CLI login. The -/// SDK rebuilds it from `path` and `fields`, so eac can check each distinct one -/// once. +/// A credential a seed, runner or judge needs, like a token or a CLI login. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct Credential { /// The credential's class, as a code reference. - pub path: CodeRef, + pub path: String, /// The arguments its class is built with. #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Object::is_empty")] pub fields: Object, @@ -94,35 +89,21 @@ impl Credential { } } -/// What a seed's setup returned. Saved to seeds.json for later phases, so it -/// must be JSON. -pub type Handle = Object; - -// An alias can't derive JsonSchema. Handle fields use this schema so the -// generated types keep the name. -/// What a seed's setup returned. Saved to seeds.json for later phases, so it -/// must be JSON. -#[derive(JsonSchema)] -#[schemars(rename = "Handle")] -pub(super) struct HandleSchema(#[allow(dead_code)] Object); - -/// A judge's score from 0 to 1. A null score is recorded but doesn't count -/// toward pass or fail. +/// A judge's score from 0 to 1. Null doesn't count toward pass or fail. #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] pub struct Score { - /// The judge's name. pub name: String, #[serde(default)] pub score: Option, - /// Why the judge gave this score. #[serde(default, skip_serializing_if = "Option::is_none")] pub explanation: Option, - /// Anything else the judge recorded. #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option, /// The judge's own LLM usage. #[serde(default, skip_serializing_if = "Option::is_none")] pub llm_judge_metrics: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, } /// LLM usage: tokens, calls, time and cost. @@ -141,7 +122,7 @@ pub struct Metrics { pub cost_usd: f64, } -/// The params to select cases from production +/// Which production runs to collect. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct Window { #[schemars(extend("format" = "date-time"))] @@ -158,22 +139,17 @@ fn full_sample() -> f64 { 1.0 } -/// A code reference, either `module.path:attr` or `./file.py:attr` relative -/// to the project root. -pub type CodeRef = String; - -/// Where a dataset's code is, from its dataset.yml. Sent with every method that -/// needs the dataset, so any worker can import it. +/// Where a dataset's code is, from its dataset.yml. Code references are +/// `module.path:attr` or `./file.py:attr`, relative to the project root. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct DatasetRef { - /// The dataset's name, from its dataset.yml. pub name: String, pub mode: Mode, /// The OfflineRunner or OnlineRunner, as a class or a configured instance. - pub runner: CodeRef, + pub runner: String, /// The dataset's cases. Offline only. #[serde(default, skip_serializing_if = "Option::is_none")] - pub cases: Option, + pub cases: Option, /// The judges --judge picks from. Online only. #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub judges: Vec, @@ -182,11 +158,10 @@ pub struct DatasetRef { /// A judge named in a dataset.yml's online.judges. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct JudgeRef { - /// The name --judge and --judge-args use. Scores still carry the judge's - /// own name. + /// The name --judge and --judge-args use. pub name: String, /// A Judge class, built with no arguments, or a configured instance. - pub path: CodeRef, + pub path: String, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] diff --git a/core/src/schema/worker_methods.rs b/core/src/schema/worker_methods.rs index 752ef9a..c7d5cf6 100644 --- a/core/src/schema/worker_methods.rs +++ b/core/src/schema/worker_methods.rs @@ -8,17 +8,14 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use super::fields::{no_object, no_strings, nullable}; -use super::types::{ - Case, Credential, DatasetRef, Handle, HandleSchema, Metrics, Mode, Object, Score, Seed, Window, -}; +use super::types::{Case, Credential, DatasetRef, Metrics, Mode, Object, Score, Seed, Window}; #[derive(Serialize, JsonSchema)] pub struct DiscoverParams<'a> { pub dataset: &'a DatasetRef, } -/// What eac learns by importing the dataset's code. Its dataset.yml covers the -/// rest. +/// What eac learns by importing the dataset's code. #[derive(Default, Deserialize, JsonSchema)] pub struct DiscoverResult { /// Every case. Offline only. @@ -31,9 +28,8 @@ pub struct ArgsValidateParams<'a> { pub dataset: &'a DatasetRef, pub mode: Mode, pub args: &'a Object, - /// For an online run, the judges picked with --judge. For an offline run, - /// judges that replace every case's own, as in a comparison. Empty keeps - /// each case's judges. + /// Online: the judges picked with --judge. Offline: judges that replace + /// every case's. Empty keeps each case's judges. #[serde(skip_serializing_if = "no_strings")] pub judges: &'a [String], /// --judge-args, by judge name. @@ -46,7 +42,7 @@ pub struct ArgsValidateResult { /// The credentials the runner needs. #[serde(default, deserialize_with = "nullable")] pub runner_credentials: Vec, - /// The credentials each of the run's judges needs, by judge name. + /// The credentials each of the run's judges needs by judge name. #[serde(default, deserialize_with = "nullable")] pub judge_credentials: BTreeMap>, } @@ -70,8 +66,8 @@ pub struct CredentialsLoginParams<'a> { #[derive(Default, Deserialize, JsonSchema)] pub struct CredentialsLoginResult { - /// Environment variables the credential sets. eac passes them to every - /// process it starts and saves them once the credential checks out. + /// Environment variables the credential sets. eac saves them for later + /// commands. #[serde(default, deserialize_with = "nullable")] pub env: BTreeMap, } @@ -84,31 +80,30 @@ pub struct SeedSetupParams<'a> { #[derive(Default, Deserialize, JsonSchema)] pub struct SeedSetupResult { + /// What the seed's setup returned. Saved for later phases, so it must be + /// JSON. #[serde(default, deserialize_with = "nullable")] - #[schemars(with = "HandleSchema")] - pub handle: Handle, + pub seed_results: Object, /// The seed's own cache had it, so nothing was set up. #[serde(default)] pub from_cache: bool, } -/// A cached seed is also removed from its own cache before it's torn down. #[derive(Serialize, JsonSchema)] pub struct SeedTeardownParams<'a> { pub dataset: &'a DatasetRef, pub seed: &'a Seed, - #[schemars(with = "HandleSchema")] - pub handle: &'a Handle, + /// What seed.setup returned. + pub seed_results: &'a Object, } #[derive(Serialize, JsonSchema)] pub struct CaseRunParams<'a> { pub dataset: &'a DatasetRef, pub case: &'a Case, - /// Each seed's handle, by seed name. + /// Each seed's results, by seed name. #[serde(skip_serializing_if = "BTreeMap::is_empty")] - #[schemars(with = "BTreeMap")] - pub seeds: BTreeMap<&'a str, &'a Handle>, + pub seed_results: BTreeMap<&'a str, &'a Object>, #[serde(skip_serializing_if = "no_object")] pub args: &'a Object, /// Tag the agent's run with this so judges can fetch its trace. @@ -119,7 +114,7 @@ pub struct CaseRunParams<'a> { pub struct CaseRunResult { /// Saved for the judge phase, so it must be JSON. #[serde(default)] - pub output: Option, + pub run_results: Option, /// The conversation ID the agent used, if it isn't the one eac sent. #[serde(default)] pub conversation_id: Option, @@ -130,18 +125,15 @@ pub struct CaseRunResult { #[derive(Serialize, JsonSchema)] pub struct CaseJudgeParams<'a> { pub dataset: &'a DatasetRef, - /// With the runner's `output` and `conversation_id`. pub case: Case, - /// Judges to use instead of the case's own, as in a comparison. Empty keeps - /// the case's judges. + /// Judges to use instead of the case's own. Empty defaults to the case's + /// judges. #[serde(skip_serializing_if = "no_strings")] pub judges: &'a [String], - /// Why the runner failed, in which case there's no output. #[serde(skip_serializing_if = "Option::is_none")] pub error: Option<&'a str>, #[serde(skip_serializing_if = "BTreeMap::is_empty")] - #[schemars(with = "BTreeMap")] - pub seeds: BTreeMap<&'a str, &'a Handle>, + pub seed_results: BTreeMap<&'a str, &'a Object>, /// --judge-args, by judge name. #[serde(skip_serializing_if = "no_object")] pub judge_args: &'a Object, @@ -160,7 +152,7 @@ pub struct CaseJudgeParams<'a> { #[derive(Default, Deserialize, JsonSchema)] pub struct CaseJudgeResult { #[serde(default, deserialize_with = "nullable")] - pub scores: Vec, + pub judge_results: Vec, /// The agent trace a judge fetched, if eac didn't send one. eac saves it /// for later judge runs. #[serde(default)] @@ -181,8 +173,7 @@ pub struct OnlineExecuteParams<'a> { #[derive(Default, Deserialize, JsonSchema)] pub struct OnlineExecuteResult { - /// One case per production run, each with its `output` and, if it has - /// one, its `conversation_id`. + /// One case per production run, with its `run_results` and `conversation_id`. #[serde(default, deserialize_with = "nullable")] pub cases: Vec, } @@ -190,14 +181,14 @@ pub struct OnlineExecuteResult { #[derive(Serialize, JsonSchema)] pub struct OnlineJudgeParams<'a> { pub dataset: &'a DatasetRef, - /// A collected case, with its `output` and `conversation_id`. pub case: Case, - /// The judges picked, by their YAML names. + /// The judges picked with --judge. pub judges: &'a [String], /// --judge-args, by judge name. #[serde(skip_serializing_if = "no_object")] pub judge_args: &'a Object, - /// As in case.judge. The case's conversation_id identifies the trace. + /// The agent trace an earlier judge phase saved. Without one, the judges + /// may fetch it by the case's conversation_id. #[serde(skip_serializing_if = "Option::is_none")] pub trace: Option<&'a Value>, } diff --git a/core/src/worker/pool.rs b/core/src/worker/pool.rs index 6d7d4e8..c407f9b 100644 --- a/core/src/worker/pool.rs +++ b/core/src/worker/pool.rs @@ -1,105 +1,48 @@ //! Runs calls on several workers at once. Each worker gets its own thread and //! answers one request at a time, so SDKs don't need to handle concurrency. -use std::panic::{self, AssertUnwindSafe}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{mpsc, Mutex}; +use std::sync::Mutex; use std::thread; -use anyhow::{anyhow, Result}; +use anyhow::Result; -use super::{check_interrupted, interrupted, Interrupted, Worker}; +use super::{interrupted, Interrupted, Worker}; -/// Hands each job to the next free worker and runs `call` on that worker's -/// thread, returning results in job order. Jobs are made on this thread right -/// before a worker takes each one, so making a job can use values that aren't -/// Send. With one worker everything runs on this thread. -/// -/// The first error from a job or `call` stops the rest and is returned once -/// in-flight calls finish. Ctrl-C returns Interrupted the same way. +/// Runs `call` on each job, on the thread of the next free worker, and +/// returns the results in job order. The first error, or Ctrl-C, stops the +/// jobs that haven't started, and is returned once the running ones finish. pub fn each( workers: &mut [Worker], - jobs: impl IntoIterator>, + jobs: Vec, call: impl Fn(&mut Worker, J) -> Result + Sync, ) -> Result> { - if let [worker] = workers { - let mut out = Vec::new(); - for job in jobs { - check_interrupted()?; - out.push(call(worker, job?)?); - } - return Ok(out); - } - + let total = jobs.len(); + let jobs = Mutex::new(jobs.into_iter().enumerate()); + let done = Mutex::new(Vec::new()); let failed = AtomicBool::new(false); - let stopped = || failed.load(Ordering::Relaxed) || interrupted(); - // With no buffer, a job is only made once a worker is free to take it. - let (job_tx, job_rx) = mpsc::sync_channel::<(usize, J)>(0); - let job_rx = Mutex::new(job_rx); - let (done_tx, done_rx) = mpsc::channel::<(usize, Result)>(); - thread::scope(|s| { - for worker in workers.iter_mut() { - let (job_rx, done_tx, call, failed) = (&job_rx, done_tx.clone(), &call, &failed); + for worker in workers { + let (jobs, done, failed, call) = (&jobs, &done, &failed, &call); s.spawn(move || loop { // A separate statement, so the lock is released before the call. - let next = job_rx.lock().expect("no thread panics holding it").recv(); - let Ok((i, job)) = next else { + let next = jobs.lock().expect("no thread panics holding it").next(); + let Some((i, job)) = next else { return }; + if failed.load(Ordering::Relaxed) || interrupted() { return; - }; - // Once stopped, a thread keeps taking jobs without running - // them, so handing one over never waits on a thread that quit. - if stopped() { - continue; } - let res = panic::catch_unwind(AssertUnwindSafe(|| call(worker, job))) - .unwrap_or_else(|_| Err(anyhow!("{} panicked", worker.label()))); - if res.is_err() { - failed.store(true, Ordering::Relaxed); - } - let _ = done_tx.send((i, res)); + let res = call(worker, job); + failed.fetch_or(res.is_err(), Ordering::Relaxed); + done.lock().expect("no thread panics holding it").push((i, res)); }); } - drop(done_tx); - - let mut first_err = None; - let mut made = 0; - for job in jobs { - if let Err(e) = check_interrupted() { - first_err = Some(e); - break; - } - if failed.load(Ordering::Relaxed) { - break; - } - match job { - Ok(job) => { - let _ = job_tx.send((made, job)); - made += 1; - } - Err(e) => { - failed.store(true, Ordering::Relaxed); - first_err = Some(e); - break; - } - } - } - // The threads finish once the jobs run out. - drop(job_tx); - - let mut out: Vec> = (0..made).map(|_| None).collect(); - for (i, res) in done_rx { - match res { - Ok(r) => out[i] = Some(r), - Err(e) => { - first_err.get_or_insert(e); - } - } - } - if let Some(e) = first_err { - return Err(e); - } - // Every job made ran unless Ctrl-C skipped some. - out.into_iter().map(|r| r.ok_or_else(|| Interrupted.into())).collect() - }) + }); + let mut done = done.into_inner().expect("no thread panics holding it"); + done.sort_by_key(|(i, _)| *i); + let out = done.into_iter().map(|(_, res)| res).collect::>>()?; + // Every job ran unless Ctrl-C stopped some. + if out.len() < total { + return Err(Interrupted.into()); + } + Ok(out) } diff --git a/core/src/worker/process.rs b/core/src/worker/process.rs index fbd6ea5..3d744cf 100644 --- a/core/src/worker/process.rs +++ b/core/src/worker/process.rs @@ -9,7 +9,7 @@ use serde::de::DeserializeOwned; use serde::Serialize; use super::responses::Responses; -use super::{logs, pipes, Interrupted}; +use super::{check_interrupted, logs, pipes, Interrupted}; use crate::schema::{Ready, Request, Response, VERSION}; /// How long a closing worker gets to exit before it is killed. @@ -81,12 +81,9 @@ impl Worker { Ok(()) } - pub fn label(&self) -> &str { - &self.label - } - /// Sends one request and decodes its result. A missing or null result - /// decodes as T's default. + /// decodes as T's default. Fails if the worker sends anything but the + /// response. pub fn call( &mut self, method: &str, @@ -99,29 +96,45 @@ impl Worker { let requests = self.requests.as_mut().expect("open until dropped"); requests.write_all(&line).with_context(|| format!("sending {method} to {}", self.label))?; - loop { - let line = match self.responses.next_line() { - Ok(Some(line)) => line, - Ok(None) => bail!("{} exited during {method}", self.label), - Err(e) if e.is::() => return Err(e), - Err(e) => bail!("{} exited during {method}: {e}", self.label), - }; - // Skip anything that isn't this call's response, such as a stale - // reply to a call that stopped waiting. - let Ok(resp) = serde_json::from_str::(&line) else { - continue; - }; - if resp.id != id { - continue; - } - if let Some(err) = resp.error { - return Err(err.into()); - } - if resp.result.is_null() { - return Ok(T::default()); + let line = match self.responses.next_line() { + Ok(Some(line)) => line, + Ok(None) => bail!("{} exited during {method}", self.label), + Err(e) if e.is::() => return Err(e), + Err(e) => bail!("{} exited during {method}: {e}", self.label), + }; + // Requests go one at a time, so the next line is this one's response. + let resp = match serde_json::from_str::(&line) { + Ok(resp) if resp.id == id => resp, + parsed => { + // After Ctrl-C, this can be the late reply to the call that + // was interrupted. + check_interrupted()?; + let why = match parsed { + Ok(resp) => format!("it answers request {}, not {id}", resp.id), + Err(e) => e.to_string(), + }; + bail!( + "{} sent an invalid response to {method} ({why}): {}", + self.label, + excerpt(&line) + ); } - return Ok(serde_json::from_value(resp.result)?); + }; + if let Some(err) = resp.error { + return Err(err.into()); + } + if resp.result.is_null() { + return Ok(T::default()); } + Ok(serde_json::from_value(resp.result)?) + } +} + +/// The start of a line, short enough for an error message. +fn excerpt(line: &str) -> String { + match line.char_indices().nth(200) { + Some((end, _)) => format!("{}...", &line[..end]), + None => line.to_string(), } } diff --git a/core/tests/cli.rs b/core/tests/cli.rs index 4c3f7fe..baac919 100644 --- a/core/tests/cli.rs +++ b/core/tests/cli.rs @@ -238,7 +238,7 @@ fn run_writes_results_and_fails_on_a_wrong_case() { let greets = &results["cases"][0]; assert_eq!(greets["status"], "passed"); assert_eq!(results["cases"][1]["status"], "failed"); - assert_eq!(greets["otel_metrics"]["total_tokens"], 10.0); + assert_eq!(greets["llm_metrics"]["total_tokens"], 10.0); assert_eq!(greets["expected_output"], json!({"reply": "hello"})); assert_eq!(greets["attributes"], json!({"turns": 1, "splits": ["smoke"]})); assert!(greets["conversation_id"].as_str().unwrap().starts_with("eval-")); @@ -255,7 +255,7 @@ fn run_writes_results_and_fails_on_a_wrong_case() { }) ); assert_eq!(results["metadata"], json!({"team": "chat", "tier": 1})); - assert_eq!(results["schema_version"], 3); + assert_eq!(results["schema_version"], 1); assert_eq!(results["source"]["trigger"], "local"); assert!(results.get("summary").is_none(), "totals come from the cases"); @@ -267,7 +267,7 @@ fn run_writes_results_and_fails_on_a_wrong_case() { json!({"name": "chat", "mode": "offline", "runner": "./evals/chat_eval.py:Runner", "cases": "./evals/chat_eval.py:CASES"}) ); let judged = p.events("judge"); - assert_eq!(judged[1]["seeds"], json!(["project", "scratch"])); + assert_eq!(judged[1]["seed_results"], json!(["project", "scratch"])); // The uncached seed is torn down with the run and the cached one stays. assert_eq!(names(&p.events("seed_teardown"), "name"), ["scratch"]); let cache = p.json(&p.path(".eac/seed-cache.json")); @@ -286,8 +286,26 @@ fn phases_run_separately() { judged.code(1); assert_eq!(judged.stdout.trim(), id, "judge prints the id of the run it judged"); assert!(p.events("seed_teardown").is_empty()); - p.eac(&["offline", "seed", "--teardown", "--run", &id]).code(0); - assert_eq!(names(&p.events("seed_teardown"), "name"), ["scratch"]); +} + +#[test] +fn judging_again_can_change_the_judge_args() { + let p = Project::new(&base()); + p.eac(&["offline", "run", "--case", "greets"]).code(0); + let strict = json!({"matches": {"strict": true}}); + p.eac(&["offline", "judge", "--judge-args", &strict.to_string()]).code(0); + // The SDK checks them, and the run records them for its results and the + // next re-judge. + assert_eq!(p.events("validate").last().unwrap()["judge_args"], strict); + let judge_args = + |p: &Project| p.json(&p.latest().join("results/chat.json"))["args"]["judge_args"].clone(); + assert_eq!(judge_args(&p), strict); + p.eac(&["offline", "judge"]).code(0); + assert_eq!(judge_args(&p), strict); + + p.eac(&["offline", "judge", "--judge-args", r#"{"politeness": {}}"#]) + .code(2) + .says("--judge-args names politeness"); } #[test] @@ -406,7 +424,7 @@ fn invalid_args_fail_before_anything_is_set_up() { let p = Project::new(&base()); p.eac(&["offline", "run", "--args", r#"{"temperature": 1}"#]) .code(2) - .says("invalid --args or --judge-args for chat: ValueError: unknown args: temperature"); + .says("validating dataset chat: ValueError: unknown args: temperature"); assert!(p.runs().is_empty()); assert!(p.events("seed_setup").is_empty()); } @@ -433,7 +451,31 @@ fn cases_without_a_score_are_skipped_and_dont_fail_the_run() { let results = p.json(&p.latest().join("results/chat.json")); assert_eq!(results["cases"][0]["status"], "skipped"); assert_eq!(results["cases"][1]["status"], "skipped"); - assert_eq!(p.json(&p.latest().join("summary.json"))["skipped"], 2); +} + +#[test] +fn a_judge_that_raises_errors_its_case() { + let p = Project::new(&base()); + p.write("broken-judge", ""); + p.eac(&["offline", "run", "--case", "greets"]) + .code(1) + .says("chat/greets › flaky: TimeoutError: the LLM timed out") + .says("1 errored"); + let greets = &p.json(&p.latest().join("results/chat.json"))["cases"][0]; + assert_eq!(greets["status"], "error"); + assert_eq!(greets["judge_results"][0]["score"], 1.0); + assert_eq!(greets["judge_results"][1]["error"], "TimeoutError: the LLM timed out"); +} + +#[test] +fn a_worker_that_breaks_the_protocol_fails_instead_of_hanging() { + let p = Project::new(&base()); + p.write("bad-response", r#"{"id": "1", "result": {}}"#); + p.eac(&["list"]) + .code(2) + .says(r#"python worker sent an invalid response to discover (invalid type: string "1""#); + p.write("bad-response", r#"{"id": 7, "result": {}}"#); + p.eac(&["list"]).code(2).says("(it answers request 7, not 1)"); } #[test] @@ -498,7 +540,7 @@ fn judges_fetch_traces_that_are_saved_for_judging_again() { let metrics = |p: &Project| { let results = p.json(&run.join("results/chat.json")); let greets = &results["cases"][0]; - (greets["otel_metrics"]["total_tokens"].clone(), greets["otel_metrics"]["cost_usd"].clone()) + (greets["llm_metrics"]["total_tokens"].clone(), greets["llm_metrics"]["cost_usd"].clone()) }; assert_eq!(metrics(&p), (json!(99.0), json!(0.5))); @@ -516,7 +558,7 @@ fn a_seed_can_come_from_its_own_cache() { p.eac(&["offline", "run", "--split", "smoke"]).code(0).says("project came from its own cache"); assert!(p.events("seed_setup").is_empty()); let cache = p.json(&p.path(".eac/seed-cache.json")); - assert_eq!(cache["seeds"]["python:project-1"]["handle"], json!({"id": "shared"})); + assert_eq!(cache["seeds"]["python:project-1"]["seed_results"], json!({"id": "shared"})); // It's in the local seed cache now, so the next run doesn't ask for it. p.eac(&["offline", "run", "--split", "smoke"]).code(0).says("project (project-) cached"); @@ -634,8 +676,8 @@ fn online_run_fetches_the_window_with_judge_args() { }) ); // Only conv-0 has a trace. - assert_eq!(results["cases"][0]["otel_metrics"]["total_tokens"], 99.0); - assert_eq!(results["cases"][1]["otel_metrics"]["total_tokens"], 0.0); + assert_eq!(results["cases"][0]["llm_metrics"]["total_tokens"], 99.0); + assert_eq!(results["cases"][1]["llm_metrics"]["total_tokens"], 0.0); p.eac(&["online", "run", "--judge", "rude"]).code(2).says("has no online judge rude"); } diff --git a/core/tests/fixtures/project/eac/worker.py b/core/tests/fixtures/project/eac/worker.py index 17d87bf..0bde555 100644 --- a/core/tests/fixtures/project/eac/worker.py +++ b/core/tests/fixtures/project/eac/worker.py @@ -7,6 +7,9 @@ Its stand-in credentials are set up when the variable their fields name is "good". Logging in prints a line and returns that, unless the variable's name ends in REFUSED. + +A `bad-response` file in its cwd makes it answer with that file's line +instead, then exit. """ import importlib @@ -56,16 +59,16 @@ def handle(method, p): if method == "seed.setup": return ds.seed_setup(p["seed"]) if method == "seed.teardown": - ds.seed_teardown(p["seed"], p.get("handle", {})) + ds.seed_teardown(p["seed"], p.get("seed_results", {})) return {} if method == "case.run": - return ds.run_case(p["case"], p.get("seeds", {}), p.get("args", {}), p["conversation_id"]) + return ds.run_case(p["case"], p.get("seed_results", {}), p.get("args", {}), p["conversation_id"]) if method == "case.judge": case = p["case"] run = {k: p[k] for k in ("started_at", "ended_at") if k in p} if "conversation_id" in case: run["conversation_id"] = case["conversation_id"] - return ds.judge(case, case.get("output"), p.get("judges", []), p.get("seeds", {}), p.get("trace"), run) + return ds.judge(case, case.get("run_results"), p.get("judges", []), p.get("seed_results", {}), p.get("trace"), run) if method == "online.execute": w = p["window"] return {"cases": ds.collect(w["since"], w["until"], w["limit"], w["sample_rate"], p.get("args", {}))} @@ -84,6 +87,13 @@ def send(message): send({"protocol": 1}) for line in os.fdopen(3): request = json.loads(line) + if os.path.exists("bad-response"): + # Exits after, so a CLI that skipped the line fails the test + # instead of hanging it. + with open("bad-response") as f: + out.write(f.read().strip() + "\n") + out.flush() + return try: send({"id": request["id"], "result": handle(request["method"], request.get("params") or {})}) except Exception as exc: diff --git a/core/tests/fixtures/project/evals/chat_eval.py b/core/tests/fixtures/project/evals/chat_eval.py index c7a1d27..8a7afab 100644 --- a/core/tests/fixtures/project/evals/chat_eval.py +++ b/core/tests/fixtures/project/evals/chat_eval.py @@ -7,9 +7,10 @@ credentials that the seeds, runner and judges need, e.g. {"seed": ["TOKEN_A"]}. Those whose names end in MANUAL can only be set up by hand. -A shared-seeds.json maps seed keys to the handles the seeds' own cache has, and +A shared-seeds.json maps seed keys to the results the seeds' own cache has, and a `traces` file lets the judges fetch traces, which every conversation but -conv-1 has. +conv-1 has. A `broken-judge` file adds a judge named flaky that raises on every +case. """ import copy @@ -130,13 +131,13 @@ def seed_setup(seed): shared = {} if seed.get("cache", True) and seed["key"] in shared: log("seed_load", name=seed["name"]) - return {"handle": shared[seed["key"]], "from_cache": True} + return {"seed_results": shared[seed["key"]], "from_cache": True} log("seed_setup", name=seed["name"]) - return {"handle": {"id": seed["key"]}} + return {"seed_results": {"id": seed["key"]}} -def seed_teardown(seed, handle): - log("seed_teardown", name=seed["name"], key=seed["key"], cache=seed.get("cache", True), handle=handle) +def seed_teardown(seed, seed_results): + log("seed_teardown", name=seed["name"], key=seed["key"], cache=seed.get("cache", True), seed_results=seed_results) def fetch_trace(conversation_id): @@ -150,51 +151,53 @@ def fetch_trace(conversation_id): } -def run_case(case, seeds, args, conversation_id): +def run_case(case, seed_results, args, conversation_id): log( "run", case=case["name"], - seeds=sorted(seeds), + seed_results=sorted(seed_results), args=args, conversation_id=conversation_id, together=together("run", case["name"]), ) - output = {"reply": case["input"]["reply"], "model": args.get("model"), "attributes": {"turns": 1}} - return {"output": output, "metrics": {"total_tokens": 10, "cost_usd": 0.001, "llm_calls": 1}} + run_results = {"reply": case["input"]["reply"], "model": args.get("model"), "attributes": {"turns": 1}} + return {"run_results": run_results, "metrics": {"total_tokens": 10, "cost_usd": 0.001, "llm_calls": 1}} -def judge(case, output, judges, seeds, trace, run): - fetched = fetch_trace(run.get("conversation_id")) if trace is None and output is not None else None +def judge(case, run_results, judges, seed_results, trace, run): + fetched = fetch_trace(run.get("conversation_id")) if trace is None and run_results is not None else None if fetched: trace = fetched["trace"] log( "judge", case=case["name"], judges=judges, - seeds=sorted(seeds), + seed_results=sorted(seed_results), trace=trace, conversation_id=run.get("conversation_id"), timed="started_at" in run and "ended_at" in run, together=together("judge", case["name"]), ) - ok = output is not None and output["reply"] == case["expected_output"]["reply"] - scores = [ + ok = run_results is not None and run_results["reply"] == case["expected_output"]["reply"] + judge_results = [ { "name": name, "score": 1.0 if ok else 0.0, - "explanation": None if ok else f"replied {output['reply']!r}", - "metadata": {"saw_trace": trace is not None, "seeds": sorted(seeds)}, + "explanation": None if ok else f"replied {run_results['reply']!r}", + "metadata": {"saw_trace": trace is not None, "seed_results": sorted(seed_results)}, } for name in judges or ["matches"] ] - return {"scores": scores, **(fetched or {})} + if os.path.exists("broken-judge"): + judge_results.append({"name": "flaky", "error": "TimeoutError: the LLM timed out"}) + return {"judge_results": judge_results, **(fetched or {})} def collect(since, until, limit, sample_rate, args): log("collect", since=since, until=until, limit=limit, sample_rate=sample_rate, args=args) cases = [ - {"name": "trace_0", "conversation_id": "conv-0", "input": {"q": "hi"}, "output": {"reply": "thanks!"}}, - {"name": "trace_1", "conversation_id": "conv-1", "input": {"q": "hey"}, "output": {"reply": ""}}, + {"name": "trace_0", "conversation_id": "conv-0", "input": {"q": "hi"}, "run_results": {"reply": "thanks!"}}, + {"name": "trace_1", "conversation_id": "conv-1", "input": {"q": "hey"}, "run_results": {"reply": ""}}, ] return cases[:limit] @@ -208,6 +211,6 @@ def online_judge(case, judges, judge_args, trace): judge_args=judge_args, together=together("online_judge", case["name"]), ) - reply = (case.get("output") or {}).get("reply", "") + reply = (case.get("run_results") or {}).get("reply", "") checks = {"nonempty": bool(reply), "polite": "thanks" in reply} - return {"scores": [{"name": j, "score": 1.0 if checks[j] else 0.0} for j in judges], **(fetched or {})} + return {"judge_results": [{"name": j, "score": 1.0 if checks[j] else 0.0} for j in judges], **(fetched or {})} diff --git a/docs/app/cases-and-runners/page.mdx b/docs/app/cases-and-runners/page.mdx index 8690661..837e4e8 100644 --- a/docs/app/cases-and-runners/page.mdx +++ b/docs/app/cases-and-runners/page.mdx @@ -39,7 +39,7 @@ OFFLINE_CASES = [ -A case also has an `output`, which is what your system returned. eac fills it in after your runner runs, so your judges can read it. +A case also has `run_results`, which is what your system returned. eac fills them in after your runner runs, so your judges can read them. A few other options you might want: @@ -66,8 +66,8 @@ from eac import Case, OfflineRunner class OfflineTriageRunner(OfflineRunner): credentials = [OpenRouterKey(), SentryLogin()] - def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: - alert = case.input["alert"].format(release=seeds["incident"]["release"]) + def run_case(self, case: Case, *, seed_results: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: + alert = case.input["alert"].format(release=seed_results["incident"]["release"]) model = self.args.get("model", DEFAULT_MODEL) return triage(alert, conversation_id=conversation_id, model=model) ``` @@ -78,7 +78,7 @@ class OfflineTriageRunner(OfflineRunner): Return plain JSON and leave the scoring to your judges. Along with the case, you get: -- `seeds`, each fixture's handle by name. Here the seed made a new release, so the runner puts it in the alert. +- `seed_results`, what each seed's `setup()` returned, by seed name. Here the seed made a new release, so the runner puts it in the alert. - `conversation_id` to tag your agent's run, so judges can find its trace later. - `self.args`, whatever was passed with `--args`, as a plain dict. eac doesn't check it, so check anything you rely on. diff --git a/docs/app/concepts/page.mdx b/docs/app/concepts/page.mdx index 074fed6..3bd5ee1 100644 --- a/docs/app/concepts/page.mdx +++ b/docs/app/concepts/page.mdx @@ -28,4 +28,4 @@ An offline run has three phases: ## Passing and failing -A case passes when every judge gives it a 1. Anything lower is a failure, and if your runner throws, the case errors. A case no judge scored is skipped, which counts as neither. Online runs just report average scores, so they never fail. +A case passes when every judge gives it a 1. Anything lower is a failure, and if your runner or a judge throws, the case errors. A case no judge scored is skipped, which counts as neither. Online runs just report average scores, so they never fail. diff --git a/docs/app/introduction/page.mdx b/docs/app/introduction/page.mdx index 66c5531..ca19e53 100644 --- a/docs/app/introduction/page.mdx +++ b/docs/app/introduction/page.mdx @@ -106,15 +106,15 @@ def reply(query: str) -> str: class ChatRunner(OfflineRunner): - def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: + def run_case(self, case: Case, *, seed_results: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: return {"response": reply(case.input["query"])} class Greets(Judge): name = "greets" - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: - ok = "hello" in case.output.get("response", "") + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + ok = "hello" in case.run_results.get("response", "") return Score(name=self.name, score=1.0 if ok else 0.0) diff --git a/docs/app/judges/page.mdx b/docs/app/judges/page.mdx index d7dc5da..ef13d2e 100644 --- a/docs/app/judges/page.mdx +++ b/docs/app/judges/page.mdx @@ -2,7 +2,7 @@ export const metadata = {title: 'Judges'}; # Judges -A judge looks at one case's output and gives it a score between 0 and 1. Judges are your own code: subclass `Judge`, read `case.output`, and return a `Score`. +A judge looks at one case's output and gives it a score between 0 and 1. Judges are your own code: subclass `Judge`, read `case.run_results`, and return a `Score`. @@ -18,10 +18,10 @@ class FoundIssueJudge(Judge): name = "found_issue" - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: error = case.expected_output["error"] - expected = seeds["incident"]["issues"][error] if error else None - actual = case.output.get("issue") + expected = seed_results["incident"]["issues"][error] if error else None + actual = case.run_results.get("issue") if actual == expected: return Score.passed(self.name) @@ -32,9 +32,9 @@ class FoundIssueJudge(Judge): -`seeds` holds the case's fixtures by name, the same ones the runner got. This judge needs them because the issue's ID only exists once the seed has created it. +`seed_results` holds what the case's seeds set up, by name, the same as the runner got. This judge needs them because the issue's ID only exists once the seed has created it. -If the judge doesn't apply to a case, return `None`. A score of `None` is saved but doesn't count toward pass or fail. If a judge throws, it scores 0, with an explanation starting "judge error". +If the judge doesn't apply to a case, return `None`. A score of `None` is saved but doesn't count toward pass or fail. If a judge throws, its score records the error instead, and the case errors. ## Reading agent traces @@ -73,7 +73,7 @@ An LLM judge asks a model to grade the trace. This one asks two true-or-false qu ```python - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: if agent_trace is None: return None with client() as openrouter: @@ -115,3 +115,5 @@ eac offline run --judge-args '{"triage_llm_judge": {"model": "openai/gpt-6.2-sol ``` The judge gets its entry as `self.args`, a plain dict, or `{}` without one. eac doesn't check what's inside, so check anything you rely on. It does reject a name that no judge in the run has, to catch typos. + +To try new settings without running the cases again, re-judge the last run with them: `eac offline judge --judge-args '...'`. diff --git a/docs/app/online-evals/page.mdx b/docs/app/online-evals/page.mdx index 4568fc0..a988b93 100644 --- a/docs/app/online-evals/page.mdx +++ b/docs/app/online-evals/page.mdx @@ -26,7 +26,7 @@ online: -The runner's `collect_cases` returns what happened in a time window, as cases with their `output` already filled in. In [the Sentry triage example](https://github.com/getsentry/eac/tree/main/examples/sentry-assistant-python), the agent saves each conversation to a local folder, standing in for production traces: +The runner's `collect_cases` returns what happened in a time window, as cases with their `run_results` already filled in. In [the Sentry triage example](https://github.com/getsentry/eac/tree/main/examples/sentry-assistant-python), the agent saves each conversation to a local folder, standing in for production traces: @@ -47,7 +47,7 @@ class OnlineTriageRunner(OnlineRunner): Case( name=c["conversation_id"], input={"alert": c["alert"]}, - output=c["answer"], + run_results=c["answer"], conversation_id=c["conversation_id"], # lets judges fetch the agent trace ) ) diff --git a/docs/app/protocol/page.mdx b/docs/app/protocol/page.mdx index ab716a6..4a2b0fc 100644 --- a/docs/app/protocol/page.mdx +++ b/docs/app/protocol/page.mdx @@ -15,7 +15,7 @@ eac starts a worker process for your language and talks to it with JSON, one mes ```json {"id": 1, "method": "case.run", "params": {}} -{"id": 1, "result": {"output": {}}} +{"id": 1, "result": {"run_results": {}}} ``` ## Methods diff --git a/docs/app/run-directory/page.mdx b/docs/app/run-directory/page.mdx index 03089be..0457cfd 100644 --- a/docs/app/run-directory/page.mdx +++ b/docs/app/run-directory/page.mdx @@ -10,9 +10,7 @@ Every run is saved to its own folder: seeds.json the fixtures it used outputs/ what your runner returned, per case traces/ agent traces the judges fetched - scores/ each judge's scores, per case results/ each dataset's results, for your own scripts - summary.json the overall results ``` ## Uploading results diff --git a/docs/app/seeds/page.mdx b/docs/app/seeds/page.mdx index 8a01d03..b025df3 100644 --- a/docs/app/seeds/page.mdx +++ b/docs/app/seeds/page.mdx @@ -37,8 +37,8 @@ class Incident(Seed): "issues": {error: self.wait_for_issue(release, error) for error in REQUESTS}, } - def cleanup(self, handle: dict[str, Any]) -> None: - for short_id in handle["issues"].values(): + def cleanup(self, seed_results: dict[str, Any]) -> None: + for short_id in seed_results["issues"].values(): cli("issue", "resolve", f"{ORG}/{short_id}") ``` @@ -46,7 +46,7 @@ class Incident(Seed): -`setup()` returns a **handle**: plain JSON, like IDs and URLs, that says what it made. Attach the seed with `Case(seeds=[Incident()])`, then read its handle in your runner and judges as `seeds["incident"]`. `cleanup()` gets the same handle back. +`setup()` returns the seed's **results**: plain JSON, like IDs and URLs, that says what it made. Attach the seed with `Case(seeds=[Incident()])`, then read its results in your runner and judges as `seed_results["incident"]`. `cleanup()` gets the same results back. ## Caching @@ -80,8 +80,8 @@ class SharedSeed(Seed): def load_cached(self, key: str) -> dict[str, Any] | None: return bucket.get(f"seeds/{self.name}/{key}") - def save_cached(self, key: str, handle: dict[str, Any]) -> None: - bucket.put(f"seeds/{self.name}/{key}", handle) + def save_cached(self, key: str, seed_results: dict[str, Any]) -> None: + bucket.put(f"seeds/{self.name}/{key}", seed_results) def delete_cached(self, key: str) -> None: bucket.delete(f"seeds/{self.name}/{key}") diff --git a/docs/components/landing.tsx b/docs/components/landing.tsx index 239f241..aaf5a9a 100644 --- a/docs/components/landing.tsx +++ b/docs/components/landing.tsx @@ -30,15 +30,15 @@ def reply(query: str) -> str: class ChatRunner(OfflineRunner): - def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: + def run_case(self, case: Case, *, seed_results: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: return {"response": reply(case.input["query"])} class GreetsJudge(Judge): name = "greets_judge" - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: - response = case.output.get("response", "") + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + response = case.run_results.get("response", "") if "hello" in response: return Score(name=self.name, score=1.0) diff --git a/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py b/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py index 4860e55..d19786e 100644 --- a/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py +++ b/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py @@ -8,9 +8,9 @@ class FoundCauseJudge(Judge): name = "found_cause" - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: expected = case.expected_output["function"] - actual = case.output.get("function") + actual = case.run_results.get("function") # Accepts "checkout.apply_coupon()" for "apply_coupon". if (actual or "").split(".")[-1].removesuffix("()") == (expected or ""): diff --git a/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py b/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py index 8e6952d..8b3833d 100644 --- a/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py +++ b/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py @@ -9,11 +9,11 @@ class FoundIssueJudge(Judge): name = "found_issue" - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: error = case.expected_output["error"] - expected = seeds["incident"]["issues"][error] if error else None - actual = case.output.get("issue") + expected = seed_results["incident"]["issues"][error] if error else None + actual = case.run_results.get("issue") if actual == expected: return Score.passed(self.name) diff --git a/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py b/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py index be089db..4ea8253 100644 --- a/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py +++ b/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py @@ -35,7 +35,7 @@ def get_agent_trace(self, run: AgentRun) -> AgentTrace | None: return None return AgentTrace(trace=conversation["messages"], metrics=LLMMetrics(**conversation["usage"])) - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: if agent_trace is None: return None with client() as openrouter: diff --git a/examples/sentry-assistant-python/evals/triage/runners/offline.py b/examples/sentry-assistant-python/evals/triage/runners/offline.py index a35cac7..9b9398d 100644 --- a/examples/sentry-assistant-python/evals/triage/runners/offline.py +++ b/examples/sentry-assistant-python/evals/triage/runners/offline.py @@ -12,6 +12,6 @@ class OfflineTriageRunner(OfflineRunner): credentials = [OpenRouterKey(), SentryLogin()] - def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: - alert = case.input["alert"].format(release=seeds["incident"]["release"]) + def run_case(self, case: Case, *, seed_results: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: + alert = case.input["alert"].format(release=seed_results["incident"]["release"]) return triage(alert, conversation_id=conversation_id, model=self.args.get("model", DEFAULT_MODEL)) diff --git a/examples/sentry-assistant-python/evals/triage/runners/online.py b/examples/sentry-assistant-python/evals/triage/runners/online.py index 4041949..20c9a34 100644 --- a/examples/sentry-assistant-python/evals/triage/runners/online.py +++ b/examples/sentry-assistant-python/evals/triage/runners/online.py @@ -16,7 +16,7 @@ def collect_cases(self, window: Window) -> list[Case]: Case( name=c["conversation_id"], input={"alert": c["alert"]}, - output=c["answer"], + run_results=c["answer"], conversation_id=c["conversation_id"], ) ) diff --git a/examples/sentry-assistant-python/evals/triage/seed.py b/examples/sentry-assistant-python/evals/triage/seed.py index 0d05726..e0cfdc9 100644 --- a/examples/sentry-assistant-python/evals/triage/seed.py +++ b/examples/sentry-assistant-python/evals/triage/seed.py @@ -53,6 +53,6 @@ def wait_for_issue(self, release: str, error: str) -> str: time.sleep(2) raise TimeoutError(f"the {error} issue didn't show up in Sentry within 2 minutes") - def cleanup(self, handle: dict[str, Any]) -> None: - for short_id in handle["issues"].values(): + def cleanup(self, seed_results: dict[str, Any]) -> None: + for short_id in seed_results["issues"].values(): cli("issue", "resolve", f"{ORG}/{short_id}") diff --git a/schemas/results.schema.json b/schemas/results.schema.json index a75f36b..5613efe 100644 --- a/schemas/results.schema.json +++ b/schemas/results.schema.json @@ -33,11 +33,11 @@ "description": "One case: what the runner returned and how the judges scored it.", "properties": { "attributes": { - "description": "The output's `attributes` object, plus the case's `splits`.", + "description": "The run results' `attributes` object, plus the case's `splits`.", "type": "object" }, "conversation_id": { - "description": "The agent conversation, for looking up its trace.", + "description": "The agent's conversation ID used for agent trace retrieval.", "type": [ "string", "null" @@ -56,7 +56,6 @@ ] }, "error": { - "description": "Why the case errored.", "type": [ "string", "null" @@ -71,26 +70,26 @@ "input": { "type": "object" }, - "name": { - "type": "string" + "judge_results": { + "items": { + "$ref": "#/$defs/Score" + }, + "type": "array" }, - "otel_metrics": { + "llm_metrics": { "$ref": "#/$defs/Metrics", - "description": "The case's LLM usage, taken from its agent trace when a judge fetched one." + "description": "The agent's LLM usage on the case." }, - "output": { + "name": { + "type": "string" + }, + "run_results": { "description": "Null if the runner failed.", "type": [ "object", "null" ] }, - "scores": { - "items": { - "$ref": "#/$defs/Score" - }, - "type": "array" - }, "start_time": { "description": "When the runner started. Null for online runs.", "format": "date-time", @@ -107,11 +106,11 @@ "name", "status", "input", - "output", + "run_results", "expected_output", "error", - "scores", - "otel_metrics", + "judge_results", + "llm_metrics", "conversation_id", "attributes", "start_time", @@ -187,7 +186,7 @@ "type": "object" }, "judges": { - "description": "A comparison's judges, replaces each case's defined judges.", + "description": "A comparison's judges, used instead of each case's own.", "items": { "type": "string" }, @@ -237,10 +236,15 @@ "type": "object" }, "Score": { - "description": "A judge's score from 0 to 1. A null score is recorded but doesn't count toward pass or fail.", + "description": "A judge's score from 0 to 1. Null doesn't count toward pass or fail.", "properties": { + "error": { + "type": [ + "string", + "null" + ] + }, "explanation": { - "description": "Why the judge gave this score.", "type": [ "string", "null" @@ -258,14 +262,12 @@ "description": "The judge's own LLM usage." }, "metadata": { - "description": "Anything else the judge recorded.", "type": [ "object", "null" ] }, "name": { - "description": "The judge's name.", "type": "string" }, "score": { @@ -375,7 +377,7 @@ "type": "string" }, "Window": { - "description": "The params to select cases from production", + "description": "Which production runs to collect.", "properties": { "limit": { "type": "integer" @@ -403,7 +405,7 @@ } }, "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "The results of judging one dataset in one run, saved as results/.json in the run's directory.", + "description": "One dataset's results from one run, saved as results/.json.", "properties": { "args": { "$ref": "#/$defs/Args" @@ -428,15 +430,15 @@ "type": "number" }, "metadata": { - "description": "The dataset.yml's `metadata`, with the run's --meta values over it.", + "description": "The dataset.yml's `metadata`, overridden by --meta.", "type": "object" }, "run_id": { "type": "string" }, "schema_version": { - "const": 3, - "description": "The version of this format. Changes that could break a reader bump it." + "const": 1, + "description": "This format's version, bumped by any change that could break a reader." }, "source": { "$ref": "#/$defs/Source" diff --git a/scripts/upload_evals.py b/scripts/upload_evals.py index 2393e31..42a9772 100755 --- a/scripts/upload_evals.py +++ b/scripts/upload_evals.py @@ -24,11 +24,9 @@ "name", "status", "input", - "output", "error", "conversation_id", "attributes", - "otel_metrics", "duration_seconds", ] @@ -104,10 +102,13 @@ def case_of(case): body = {} for field in CASE_FIELDS: body[field] = case.get(field) + # evals.sentry.dev takes these under its own names. + body["output"] = case.get("run_results") + body["otel_metrics"] = case.get("llm_metrics") body = without_nulls(body, keep=["error"]) body["scores"] = [] - for score in case["scores"]: + for score in case["judge_results"]: body["scores"].append(without_nulls(score, keep=["score", "explanation"])) return body diff --git a/sdks/python/README.md b/sdks/python/README.md index 40ca59b..0fa9430 100644 --- a/sdks/python/README.md +++ b/sdks/python/README.md @@ -96,9 +96,9 @@ CASES = [ - `name` must be unique in the dataset. `--case` picks by it. - `input` and `expected_output` are dicts that your runner and judges read. -- `output` and `conversation_id` are what the system produced. eac sets them - to what the runner returned before judging, and an online runner sets them - on the cases it collects. +- `run_results` and `conversation_id` are what the system produced. eac sets + them to what the runner returned before judging, and an online runner sets + them on the cases it collects. - `enabled=False` leaves a case out unless it's picked by name or split. - `seeds` lists the fixtures the case needs. See [Seeds](#seeds). - `cache=False` sets the case's seeds up fresh and tears them down after the @@ -110,33 +110,34 @@ files relative to the calling file. ## Offline runner -The runner calls your system on one case and returns its raw output. Scoring -is left to the judges. +The runner calls your system on one case and returns its results. Scoring is +left to the judges. ```python from eac import Case, OfflineRunner class ChatRunner(OfflineRunner): - def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: + def run_case(self, case: Case, *, seed_results: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: model = self.args.get("model", "small") reply = my_chatbot(case.input["query"], model=model, tag=conversation_id) return {"response": reply} ``` -- `seeds` maps each of the case's seed names to its handle. +- `seed_results` maps each of the case's seed names to what its `setup()` + returned. - Tag your agent's run with `conversation_id`, so a judge's `get_agent_trace()` can find the trace. - `self.args` is the run's `--args`, as a plain dict. eac doesn't check them, so check any you rely on yourself. Each distinct set of args gets its own copy of the runner, as in a comparison's arms. -Return plain JSON data. eac writes the output to disk and the judge phase -reads it back, maybe in another process. +Return plain JSON data. eac writes the run results to disk and the judge +phase reads them back, maybe in another process. ## Judges A judge scores one case's output from 0 to 1. Judges are your own code: subclass -`Judge` and read `case.output`. +`Judge` and read `case.run_results`. ```python from eac import Case, Judge, Score @@ -144,11 +145,11 @@ from eac import Case, Judge, Score class Matches(Judge): name = "matches" # what its scores are called - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: expected = case.expected_output.get("response") if expected is None: return None # doesn't apply, e.g. online - if case.output.get("response") == expected: + if case.run_results.get("response") == expected: return Score.passed(self.name) return Score.failed(self.name, "wrong reply") @@ -158,21 +159,22 @@ class CalledTool(Judge): def __init__(self, tool: str): self.tool = tool - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: - ok = self.tool in (case.output.get("tool_calls") or []) + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + ok = self.tool in (case.run_results.get("tool_calls") or []) return Score(name=self.name, score=1.0 if ok else 0.0) ``` -- `seeds` maps each of the case's seed names to its handle. +- `seed_results` maps each of the case's seed names to what its `setup()` + returned. - `agent_trace` is the case's agent trace, from a judge's `get_agent_trace()`, or `None`. - Return `None` when the judge doesn't apply to the case. - A score of `None` is recorded but doesn't count toward pass or fail. A case passes when every score is 1 and fails when any is lower. It's skipped -when it has no scores, which counts as neither, and errors when the runner -raised, in which case it isn't judged. A judge that raises scores 0, with an -explanation starting "judge error". +when it has no scores, which counts as neither, and errors when the runner or a +judge raised. A case whose runner raised isn't judged. A judge that raises +gets its error in place of a score. For settings that change per run, like a rubric, pass `--judge-args '{"called_tool": {...}}'`, keyed by the judge's name. The judge @@ -203,7 +205,7 @@ class SentryJudge(Judge): class UsedTheRightTool(SentryJudge): name = "used_the_right_tool" - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: ... ``` @@ -229,7 +231,6 @@ class Project(Seed): name = "project" # how runners and judges look it up def __init__(self, slug: str = "demo"): - super().__init__() self.slug = slug def key(self) -> str: @@ -239,23 +240,18 @@ class Project(Seed): project = create_project(self.slug) return {"id": project.id, "slug": self.slug} - def cleanup(self, handle: dict[str, Any]) -> None: - delete_project(handle["id"]) + def cleanup(self, seed_results: dict[str, Any]) -> None: + delete_project(seed_results["id"]) ``` -- `setup()` returns a handle: plain JSON, like ids and URLs, never live - clients. +- `setup()` returns the seed's results: plain JSON, like ids and URLs, never + live clients. - `key()` decides sharing. Cases whose seeds have the same key share one setup. The default hashes the seed's module source, so editing the seed - sets it up again. Override it when instances differ, as above, and add - `current_week_salt()` for data that should be refreshed weekly. + sets it up again. Override it when instances differ, as above. - Seeds are cached between runs until their key changes. `eac offline prune` tears down the ones no case uses anymore. Set `cacheable = False` on a seed that can never be reused. -- A seed can hold others: pass them to `super().__init__(*children)`, and - they're set up after it, inside what it created, and cleaned up before it. - Each child gets the parent's `share(handle)` as `self.parent`, which by - default is the parent's handle. ### Sharing seeds between machines @@ -267,19 +263,19 @@ class SharedSeed(Seed): """A base for seeds that machines share through a bucket.""" def load_cached(self, key: str) -> dict[str, Any] | None: - return bucket.get(f"seeds/{self.name}/{key}") # the handle, or None + return bucket.get(f"seeds/{self.name}/{key}") # the seed's results, or None - def save_cached(self, key: str, handle: dict[str, Any]) -> None: - bucket.put(f"seeds/{self.name}/{key}", handle) + def save_cached(self, key: str, seed_results: dict[str, Any]) -> None: + bucket.put(f"seeds/{self.name}/{key}", seed_results) def delete_cached(self, key: str) -> None: bucket.delete(f"seeds/{self.name}/{key}") ``` - For a cached seed its local cache doesn't have, eac calls `load_cached()` - first, and uses a handle it returns instead of setting the seed and its - children up. Otherwise it sets them up and calls `save_cached()` with the - handle, children's included. Either failing only warns. + first, and uses the results it returns instead of setting the seed up. + Otherwise it sets it up and calls `save_cached()` with its results. Either + failing only warns. - Before tearing a cached seed down, eac calls `delete_cached()` with the key it was set up with, which isn't `key()` once the seed has changed. If it raises, the seed isn't torn down. @@ -303,7 +299,7 @@ class ProdChats(OnlineRunner): Case( name=row.id, input={"query": row.query}, - output={"response": row.reply}, + run_results={"response": row.reply}, conversation_id=row.trace_id, # for get_agent_trace() ) for row in query_traces(window.since, window.until, window.limit) @@ -363,8 +359,8 @@ class GitHub(Credential): Declare credentials on whatever needs them: - A seed's `credentials`, e.g. `self.credentials = (GitHub(self.repo),)` in - `__init__`. eac checks them, and its children's, before seeding and tearing - down. Include what its shared cache needs. + `__init__`. eac checks them before seeding and tearing down. Include what + its shared cache needs. - A runner's `credentials`. eac checks them before executing. - A judge's `credentials`, checked before judging. Include what `get_agent_trace()` needs. diff --git a/sdks/python/eac/__init__.py b/sdks/python/eac/__init__.py index 433419f..51e482b 100644 --- a/sdks/python/eac/__init__.py +++ b/sdks/python/eac/__init__.py @@ -4,7 +4,7 @@ from eac.models import AgentRun, AgentTrace, Case, LLMMetrics, Score, Window, from_jsonl, stable_hash from eac.protocol import PROTOCOL_VERSION from eac.runner import OfflineRunner, OnlineRunner -from eac.seed import Seed, current_week_salt +from eac.seed import Seed __all__ = [ "__version__", @@ -20,7 +20,6 @@ "Score", "Seed", "Window", - "current_week_salt", "from_jsonl", "stable_hash", ] diff --git a/sdks/python/eac/judge/judge.py b/sdks/python/eac/judge/judge.py index 1a21919..623b9d4 100644 --- a/sdks/python/eac/judge/judge.py +++ b/sdks/python/eac/judge/judge.py @@ -9,7 +9,7 @@ class Judge(ABC): - """Scores a case's output from 0 to 1.""" + """Scores a case's run results from 0 to 1.""" #: What its scores are called, and what --judge-args are keyed by. name: ClassVar[str] @@ -25,13 +25,14 @@ class Judge(ABC): credentials: Sequence[Credential] = () @abstractmethod - def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: - """Score `case.output`, or return None if this judge doesn't apply to + def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: + """Score `case.run_results`, or return None if this judge doesn't apply to the case, e.g. one without the expected output it compares against. - Cases whose runner raised are never judged. `seeds` maps each of the - case's seed names to its handle, and is empty online. `agent_trace` is - the trace a judge's get_agent_trace() found, or None. + Cases whose runner raised are never judged. `seed_results` maps each + of the case's seed names to what its setup() returned, and is empty + online. `agent_trace` is the trace a judge's get_agent_trace() found, + or None. """ def get_agent_trace(self, run: AgentRun) -> AgentTrace | None: diff --git a/sdks/python/eac/models.py b/sdks/python/eac/models.py index cfb8126..cbe9cc1 100644 --- a/sdks/python/eac/models.py +++ b/sdks/python/eac/models.py @@ -87,9 +87,9 @@ class Case: #: What the system produced, which judges score. An OnlineRunner sets it #: on the cases it collects. Offline, eac sets it to what the runner #: returned before judging. - output: dict[str, Any] = field(default_factory=dict) + run_results: dict[str, Any] = field(default_factory=dict) #: The ID the agent's run was tagged with, for get_agent_trace(). Set - #: like `output`. + #: like `run_results`. conversation_id: str | None = None #: Named groups `eac --split` picks cases by. splits: Sequence[str] = () @@ -102,10 +102,8 @@ class Case: cache: bool = True def __post_init__(self) -> None: - from eac.seed.seed import walk - - # Runners and judges look seeds up by name, children included. - names = [seed.name for seed in walk(self.seeds)] + # Runners and judges look seeds up by name. + names = [seed.name for seed in self.seeds] if duplicates := sorted({name for name in names if names.count(name) > 1}): raise ValueError(f"case {self.name!r} has more than one seed named {', '.join(duplicates)}") diff --git a/sdks/python/eac/protocol.py b/sdks/python/eac/protocol.py index 69b8409..b165056 100644 --- a/sdks/python/eac/protocol.py +++ b/sdks/python/eac/protocol.py @@ -18,55 +18,49 @@ class ArgsValidateParams(TypedDict): dataset: DatasetRef #: --judge-args, by judge name. judge_args: NotRequired[dict[str, Any]] - #: For an online run, the judges picked with --judge. For an offline run, judges - #: that replace every case's own, as in a comparison. Empty keeps each case's - #: judges. + #: Online: the judges picked with --judge. Offline: judges that replace every + #: case's. Empty keeps each case's judges. judges: NotRequired[list[str]] mode: Mode class ArgsValidateResult(TypedDict): - #: The credentials each of the run's judges needs, by judge name. + #: The credentials each of the run's judges needs by judge name. judge_credentials: NotRequired[dict[str, list[Credential]]] #: The credentials the runner needs. runner_credentials: NotRequired[list[Credential]] class Case(TypedDict): - """An offline case, or a production run collected for online judging.""" + """An offline case's name.""" - #: The ID the agent's run was tagged with, for judges to fetch its trace by. Set - #: like `output`. + #: The agent's conversation ID used for agent trace retrieval. conversation_id: NotRequired[str | None] #: A disabled case runs only when picked by name or by one of its splits. enabled: NotRequired[bool] expected_output: NotRequired[dict[str, Any] | None] input: NotRequired[dict[str, Any] | None] - #: The judges' names, for display. The worker runs the judges itself. judges: NotRequired[list[str]] #: Unique in its dataset. An online case's id. name: str #: What the system produced: a collected online case's production output, or the #: runner's output when eac sends the case to be judged. Absent otherwise, including #: when the runner failed. - output: NotRequired[dict[str, Any] | None] + run_results: NotRequired[dict[str, Any] | None] seeds: NotRequired[list[Seed]] splits: NotRequired[list[str]] class CaseJudgeParams(TypedDict): - #: With the runner's `output` and `conversation_id`. case: Case dataset: DatasetRef ended_at: NotRequired[str | None] - #: Why the runner failed, in which case there's no output. error: NotRequired[str | None] #: --judge-args, by judge name. judge_args: NotRequired[dict[str, Any]] - #: Judges to use instead of the case's own, as in a comparison. Empty keeps the - #: case's judges. + #: Judges to use instead of the case's own. Empty defaults to the case's judges. judges: NotRequired[list[str]] - seeds: NotRequired[dict[str, dict[str, Any]]] + seed_results: NotRequired[dict[str, dict[str, Any]]] #: When the runner started. started_at: NotRequired[str | None] #: The agent trace an earlier judge phase saved. Without one, the judges may fetch @@ -77,7 +71,7 @@ class CaseJudgeParams(TypedDict): class CaseJudgeResult(TypedDict): """What case.judge and online.judge return.""" - scores: NotRequired[list[Score]] + judge_results: NotRequired[list[Score]] #: The agent trace a judge fetched, if eac didn't send one. eac saves it for later #: judge runs. trace: NotRequired[Any] @@ -92,8 +86,8 @@ class CaseRunParams(TypedDict): #: Tag the agent's run with this so judges can fetch its trace. conversation_id: str dataset: DatasetRef - #: Each seed's handle, by seed name. - seeds: NotRequired[dict[str, dict[str, Any]]] + #: Each seed's results, by seed name. + seed_results: NotRequired[dict[str, dict[str, Any]]] class CaseRunResult(TypedDict): @@ -101,13 +95,11 @@ class CaseRunResult(TypedDict): conversation_id: NotRequired[str | None] metrics: NotRequired[Metrics | None] #: Saved for the judge phase, so it must be JSON. - output: NotRequired[dict[str, Any] | None] + run_results: NotRequired[dict[str, Any] | None] class Credential(TypedDict): - """A credential a seed, runner or judge needs, like a token or a CLI login. The SDK - rebuilds it from `path` and `fields`, so eac can check each distinct one once. - """ + """A credential a seed, runner or judge needs, like a token or a CLI login.""" #: The arguments its class is built with. fields: NotRequired[dict[str, Any]] @@ -133,14 +125,13 @@ class CredentialsLoginParams(TypedDict): class CredentialsLoginResult(TypedDict): - #: Environment variables the credential sets. eac passes them to every process it - #: starts and saves them once the credential checks out. + #: Environment variables the credential sets. eac saves them for later commands. env: NotRequired[dict[str, str]] class DatasetRef(TypedDict): - """Where a dataset's code is, from its dataset.yml. Sent with every method that - needs the dataset, so any worker can import it. + """Where a dataset's code is, from its dataset.yml. Code references are + `module.path:attr` or `./file.py:attr`, relative to the project root. """ #: The dataset's cases. Offline only. @@ -148,7 +139,6 @@ class DatasetRef(TypedDict): #: The judges --judge picks from. Online only. judges: NotRequired[list[JudgeRef]] mode: Mode - #: The dataset's name, from its dataset.yml. name: str #: The OfflineRunner or OnlineRunner, as a class or a configured instance. runner: str @@ -159,8 +149,7 @@ class DiscoverParams(TypedDict): class DiscoverResult(TypedDict): - """What eac learns by importing the dataset's code. Its dataset.yml covers the rest. - """ + """What eac learns by importing the dataset's code.""" #: Every case. Offline only. cases: NotRequired[list[Case]] @@ -174,7 +163,7 @@ class Error(TypedDict): class JudgeRef(TypedDict): """A judge named in a dataset.yml's online.judges.""" - #: The name --judge and --judge-args use. Scores still carry the judge's own name. + #: The name --judge and --judge-args use. name: str #: A Judge class, built with no arguments, or a configured instance. path: str @@ -202,20 +191,19 @@ class OnlineExecuteParams(TypedDict): class OnlineExecuteResult(TypedDict): - #: One case per production run, each with its `output` and, if it has one, its - #: `conversation_id`. + #: One case per production run, with its `run_results` and `conversation_id`. cases: NotRequired[list[Case]] class OnlineJudgeParams(TypedDict): - #: A collected case, with its `output` and `conversation_id`. case: Case dataset: DatasetRef #: --judge-args, by judge name. judge_args: NotRequired[dict[str, Any]] - #: The judges picked, by their YAML names. + #: The judges picked with --judge. judges: list[str] - #: As in case.judge. The case's conversation_id identifies the trace. + #: The agent trace an earlier judge phase saved. Without one, the judges may fetch + #: it by the case's conversation_id. trace: NotRequired[Any] @@ -238,17 +226,13 @@ class Response(TypedDict): class Score(TypedDict): - """A judge's score from 0 to 1. A null score is recorded but doesn't count toward - pass or fail. - """ + """A judge's score from 0 to 1. Null doesn't count toward pass or fail.""" - #: Why the judge gave this score. + error: NotRequired[str | None] explanation: NotRequired[str | None] #: The judge's own LLM usage. llm_judge_metrics: NotRequired[Metrics | None] - #: Anything else the judge recorded. metadata: NotRequired[dict[str, Any] | None] - #: The judge's name. name: str score: NotRequired[float | None] @@ -257,10 +241,10 @@ class Seed(TypedDict): """A fixture. Seeds with the same `key`, a content hash, are set up once and shared. """ - #: Whether to reuse the seed across runs while its key matches. Turn it off for - #: seeds the agent changes, so they're torn down after each run. + #: Whether to keep the seed for later runs, instead of tearing it down after this + #: one. cache: NotRequired[bool] - #: The credentials setting it up or tearing it down needs, including its children's. + #: The credentials setting it up or tearing it down needs. credentials: NotRequired[list[Credential]] key: str name: str @@ -274,19 +258,19 @@ class SeedSetupParams(TypedDict): class SeedSetupResult(TypedDict): #: The seed's own cache had it, so nothing was set up. from_cache: NotRequired[bool] - handle: NotRequired[dict[str, Any]] + #: What the seed's setup returned. Saved for later phases, so it must be JSON. + seed_results: NotRequired[dict[str, Any]] class SeedTeardownParams(TypedDict): - """A cached seed is also removed from its own cache before it's torn down.""" - dataset: DatasetRef - handle: dict[str, Any] seed: Seed + #: What seed.setup returned. + seed_results: dict[str, Any] class Window(TypedDict): - """The params to select cases from production""" + """Which production runs to collect.""" limit: int #: The fraction of runs to collect, picked by a hash of each run's id. diff --git a/sdks/python/eac/runner/offline_runner.py b/sdks/python/eac/runner/offline_runner.py index 2b1bc90..5a01a7c 100644 --- a/sdks/python/eac/runner/offline_runner.py +++ b/sdks/python/eac/runner/offline_runner.py @@ -15,10 +15,10 @@ class OfflineRunner(Runner): """ @abstractmethod - def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: - """Run the case and return its output as a JSON-serializable dict. + def run_case(self, case: Case, *, seed_results: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: + """Run the case and return its results as a JSON-serializable dict. - `seeds` maps each of the case's seed names to its handle. Tag the - agent's run with `conversation_id`, so a judge's get_agent_trace() can - find it. + `seed_results` maps each of the case's seed names to what its setup() + returned. Tag the agent's run with `conversation_id`, so a judge's + get_agent_trace() can find it. """ diff --git a/sdks/python/eac/runner/online_runner.py b/sdks/python/eac/runner/online_runner.py index 7583084..41ab05d 100644 --- a/sdks/python/eac/runner/online_runner.py +++ b/sdks/python/eac/runner/online_runner.py @@ -18,5 +18,5 @@ class OnlineRunner(Runner): @abstractmethod def collect_cases(self, window: Window) -> Iterable[Case]: """Return at most `window.limit` production runs from the window, each - as a Case with its `output`, and its `conversation_id` for + as a Case with its `run_results`, and its `conversation_id` for get_agent_trace().""" diff --git a/sdks/python/eac/seed/__init__.py b/sdks/python/eac/seed/__init__.py index a2d33d2..4706010 100644 --- a/sdks/python/eac/seed/__init__.py +++ b/sdks/python/eac/seed/__init__.py @@ -1,3 +1,3 @@ -from eac.seed.seed import Seed, current_week_salt +from eac.seed.seed import Seed -__all__ = ["Seed", "current_week_salt"] +__all__ = ["Seed"] diff --git a/sdks/python/eac/seed/seed.py b/sdks/python/eac/seed/seed.py index 94d088a..6710a8c 100644 --- a/sdks/python/eac/seed/seed.py +++ b/sdks/python/eac/seed/seed.py @@ -5,20 +5,14 @@ import sys from abc import ABC, abstractmethod -from datetime import UTC, datetime -from typing import Any, ClassVar, Iterator, Sequence +from typing import Any, ClassVar, Sequence from eac.credential import Credential from eac.models import stable_hash class Seed(ABC): - """A fixture a case needs before it can run. - - A seed's children are set up after it, inside what it created, and cleaned - up before it. If a child fails to set up, the seeds already set up are - cleaned up before the error is reported. - """ + """A fixture a case needs before it can run.""" name: ClassVar[str] @@ -26,70 +20,45 @@ class Seed(ABC): #: fake. A case that changes its fixtures sets Case(cache=False) instead. cacheable: ClassVar[bool] = True - children: Sequence[Seed] = () - - #: What setting this seed up and cleaning it up needs. eac checks them, - #: and its children's, before seeding and tearing down. + #: What setting this seed up and cleaning it up needs. eac checks them + #: before seeding and tearing down. credentials: Sequence[Credential] = () - #: What the parent seed's share() returned. None for a top-level seed. - parent: Any = None - - def __init__(self, *children: Seed): - self.children = children - def key(self) -> str: """Return a hash of everything that changes what setup() produces. Seeds with the same key are set up once and shared. - The default hashes the seed's module source and its children's keys, - so editing a seed reseeds it. Override it when instances differ by - constructor arguments, and salt it with current_week_salt() for data - anchored to the current date. + The default hashes the seed's module source, so editing a seed reseeds + it. Override it when instances differ by constructor arguments. """ - return stable_hash( - { - "seed": self.name, - "source": stable_hash(_module_source(type(self))), - "children": [child.key() for child in self.children], - } - ) + return stable_hash({"seed": self.name, "source": stable_hash(_module_source(type(self)))}) @abstractmethod def setup(self) -> dict[str, Any]: - """Create the fixture and return a handle. + """Create the fixture and return its results, like ids and URLs. - The handle is saved to seeds.json and read back by a later phase, so - return ids and URLs, not live clients. If setup fails partway, - undo what it created before raising. + They're saved to seeds.json and read back by a later phase, so return + plain JSON, not live clients. If setup fails partway, undo what it + created before raising. """ - def share(self, handle: dict[str, Any]) -> Any: - """Return what the children get as their `parent`, e.g. clients for - the project this seed created. Defaults to the handle. - - Called before the children are set up and again before they're - cleaned up, possibly in another process, so build it from the handle. - """ - return handle - - def cleanup(self, handle: dict[str, Any]) -> None: + def cleanup(self, seed_results: dict[str, Any]) -> None: """Release the fixture. Default is a no-op.""" def load_cached(self, key: str) -> dict[str, Any] | None: - """Return the handle a cache shared between machines, like a bucket, - has for this seed with key, or None. Defaults to None. + """Return the seed results a cache shared between machines, like a + bucket, has for this seed with key, or None. Defaults to None. Only called for cached seeds that eac's local seed cache doesn't - have. A handle it returns is used instead of setting the seed and its - children up. If it raises, the seed is set up instead. + have. Results it returns are used instead of setting the seed up. If + it raises, the seed is set up instead. """ return None - def save_cached(self, key: str, handle: dict[str, Any]) -> None: - """Save the handle a cached seed was just set up with, children's - included, for load_cached() to return. A failure only warns, since - the fixture exists either way. Default is a no-op.""" + def save_cached(self, key: str, seed_results: dict[str, Any]) -> None: + """Save the results a cached seed was just set up with, for + load_cached() to return. A failure only warns, since the fixture + exists either way. Default is a no-op.""" def delete_cached(self, key: str) -> None: """Remove this seed from the shared cache before eac tears it down, @@ -99,20 +68,6 @@ def delete_cached(self, key: str) -> None: Default is a no-op.""" -def current_week_salt() -> str: - """The current ISO week in UTC, e.g. "2026-W45". Salt a key with it to - reseed weekly.""" - year, week, _ = datetime.now(UTC).isocalendar() - return f"{year}-W{week:02d}" - - -def walk(seeds: Sequence[Seed]) -> Iterator[Seed]: - """Each seed, then its children, depth first.""" - for seed in seeds: - yield seed - yield from walk(seed.children) - - @functools.cache def _module_source(cls: type) -> str: module = sys.modules.get(cls.__module__) diff --git a/sdks/python/eac/worker.py b/sdks/python/eac/worker.py index 8e5a8ec..2975c25 100644 --- a/sdks/python/eac/worker.py +++ b/sdks/python/eac/worker.py @@ -26,7 +26,7 @@ from eac.judge import Judge from eac.models import AgentRun, AgentTrace, Case, LLMMetrics, Score, Window, stable_hash from eac.runner import OfflineRunner, OnlineRunner, Runner -from eac.seed.seed import Seed, walk +from eac.seed.seed import Seed REQUEST_FD, RESPONSE_FD = 3, 4 @@ -82,7 +82,7 @@ def _dispatch(self, method: str, params: Any) -> Any: case "seed.setup": return dataset.seed_setup(params["seed"]) case "seed.teardown": - return dataset.seed_teardown(params["seed"], params.get("handle") or {}) + return dataset.seed_teardown(params["seed"], params.get("seed_results") or {}) case "case.run": return dataset.run_case(params) case "online.execute": @@ -172,7 +172,7 @@ def seed(self, name: str, key: str, *, cleanup: bool = False) -> Seed: self._seeds = {(seed.name, _seed_key(case, seed)): seed for case in self.cases for seed in case.seeds} if (name, key) in self._seeds: return self._seeds[(name, key)] - # Cleanup needs only the seed's code and handle, so a seed whose key + # Cleanup needs only the seed's code and results, so a seed whose key # changed since setup, like one being pruned, is matched by name. if cleanup: for (seed_name, _), seed in self._seeds.items(): @@ -225,31 +225,31 @@ def seed_setup(self, sent: wire.Seed) -> wire.SeedSetupResult: key = sent["key"] seed = self.seed(sent["name"], key) cached = sent.get("cache", True) - if cached and (handle := _load_cached(seed, key)) is not None: - return {"handle": handle, "from_cache": True} - handle = _set_up(seed) + if cached and (seed_results := _load_cached(seed, key)) is not None: + return {"seed_results": seed_results, "from_cache": True} + seed_results = _json_dict(_call(seed.setup), f"{type(seed).__name__}.setup()") if cached: try: - _call(seed.save_cached, key, handle) + _call(seed.save_cached, key, seed_results) except Exception as exc: _warn(f"saving {seed.name} to its cache", exc) - return {"handle": handle} + return {"seed_results": seed_results} - def seed_teardown(self, sent: wire.Seed, handle: dict[str, Any]) -> dict[str, Any]: + def seed_teardown(self, sent: wire.Seed, seed_results: dict[str, Any]) -> dict[str, Any]: seed = self.seed(sent["name"], sent["key"], cleanup=True) # Forgotten first, so the cache never points at a fixture that's gone. # If forgetting fails, the fixture stays. if sent.get("cache", True): _call(seed.delete_cached, sent["key"]) - _clean_up(seed, handle) + _call(seed.cleanup, seed_results) return {} def run_case(self, params: wire.CaseRunParams) -> wire.CaseRunResult: case = self.case(params["case"]["name"]) runner = self.with_args(self.runner, params.get("args") or {}) - seeds = _seed_handles(case, params.get("seeds") or {}) - output = _call(runner.run_case, case, seeds=seeds, conversation_id=params["conversation_id"]) - return {"output": _json_dict(output, f"{type(runner).__name__}.run_case()")} + seed_results = params.get("seed_results") or {} + run_results = _call(runner.run_case, case, seed_results=seed_results, conversation_id=params["conversation_id"]) + return {"run_results": _json_dict(run_results, f"{type(runner).__name__}.run_case()")} def collect_cases(self, params: wire.OnlineExecuteParams) -> wire.OnlineExecuteResult: sent = params["window"] @@ -268,7 +268,7 @@ def collect_cases(self, params: wire.OnlineExecuteParams) -> wire.OnlineExecuteR break if not isinstance(case, Case): raise WorkerError(f"{what} must return Cases, got {type(case).__name__}") - collected: wire.Case = {"name": case.name, "input": case.input, "output": case.output} + collected: wire.Case = {"name": case.name, "input": case.input, "run_results": case.run_results} if case.conversation_id is not None: collected["conversation_id"] = case.conversation_id _require_serializable(collected, what) @@ -280,12 +280,12 @@ def judge(self, params: wire.CaseJudgeParams) -> wire.CaseJudgeResult: Without the trace eac saved, the judges fetch it, and it's returned for eac to save.""" sent = params["case"] - output = sent.get("output") - # A case whose runner raised has no output, and gets no scores. - if output is None: - return {"scores": []} + run_results = sent.get("run_results") + # A case whose runner raised has no run results, and isn't judged. + if run_results is None: + return {"judge_results": []} own = self.case(sent["name"]) if self.offline else Case(name=sent["name"], input=sent.get("input") or {}) - case = dataclasses.replace(own, output=output, conversation_id=sent.get("conversation_id")) + case = dataclasses.replace(own, run_results=run_results, conversation_id=sent.get("conversation_id")) judge_args = params.get("judge_args") or {} names = params.get("judges") or [] judges = self.judges_named(names) if names else [(judge.name, judge) for judge in case.judges] @@ -306,24 +306,24 @@ def judge(self, params: wire.CaseJudgeParams) -> wire.CaseJudgeResult: if fetched.metrics is not None: result["trace_metrics"] = _wire_metrics(fetched.metrics) - seeds = _seed_handles(case, params.get("seeds") or {}) - scores = [_score(judge, case, seeds, agent_trace) for _, judge in judges] - result["scores"] = [score for score in scores if score is not None] + seed_results = params.get("seed_results") or {} + judge_results = [_score(judge, case, seed_results, agent_trace) for _, judge in judges] + result["judge_results"] = [score for score in judge_results if score is not None] return result -def _score(judge: Judge, case: Case, seeds: dict[str, dict[str, Any]], agent_trace: Any) -> wire.Score | None: +def _score(judge: Judge, case: Case, seed_results: dict[str, dict[str, Any]], agent_trace: Any) -> wire.Score | None: """The judge's score, or None if it doesn't apply. A judge that raises - scores 0.""" + gets its error instead of a score, which errors the case.""" try: - score = _call(judge.judge, case, seeds=seeds, agent_trace=agent_trace) + score = _call(judge.judge, case, seed_results=seed_results, agent_trace=agent_trace) if score is None: return None if not isinstance(score, Score): raise WorkerError(f"returned {type(score).__name__}, not a Score or None") except Exception as exc: name = getattr(judge, "name", type(judge).__name__) - return {"name": name, "score": 0.0, "explanation": f"judge error: {type(exc).__name__}: {exc}"} + return {"name": name, "error": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}"} result: wire.Score = { "name": score.name, "score": score.score, @@ -451,84 +451,22 @@ def _seed_key(case: Case, seed: Seed) -> str: def _protocol_seed(case: Case, seed: Seed) -> wire.Seed: - """A case's top-level seed as the CLI sees it, children included.""" - cache = case.cache and all(s.cacheable for s in walk([seed])) - out: wire.Seed = {"name": seed.name, "key": _seed_key(case, seed), "cache": cache} - if credentials := _credentials(c for s in walk([seed]) for c in s.credentials): + """A case's seed as the CLI sees it.""" + out: wire.Seed = {"name": seed.name, "key": _seed_key(case, seed), "cache": case.cache and seed.cacheable} + if credentials := _credentials(seed.credentials): out["credentials"] = credentials return out def _load_cached(seed: Seed, key: str) -> dict[str, Any] | None: - """The handle the seed's own cache has, or None. A cache that fails only + """The results the seed's own cache has, or None. A cache that fails only warns, so the seed is set up instead.""" try: - handle = _call(seed.load_cached, key) + seed_results = _call(seed.load_cached, key) except Exception as exc: _warn(f"loading {seed.name} from its cache", exc) return None - return None if handle is None else _json_dict(handle, f"{type(seed).__name__}.load_cached()") - - -def _set_up(seed: Seed) -> dict[str, Any]: - """Set up the seed, then its children. A seed with children gets the - handle {"handle": its own, "children": {name: child's handle}}. If a child - fails, what was already set up is cleaned up before raising.""" - handle = _json_dict(_call(seed.setup), f"{type(seed).__name__}.setup()") - if not seed.children: - return handle - - tree: dict[str, Any] = {"handle": handle, "children": {}} - try: - shared = seed.share(handle) - for child in seed.children: - child.parent = shared - tree["children"][child.name] = _set_up(child) - except BaseException: - try: - _clean_up(seed, tree) - except Exception as exc: - _warn(f"cleaning up {seed.name} after its setup failed", exc) - raise - return tree - - -def _clean_up(seed: Seed, handle: dict[str, Any]) -> None: - """Clean up the seed's children in reverse order, then the seed.""" - if seed.children: - tree, handle = handle, handle["handle"] - children = tree["children"] - if unknown := set(children) - {child.name for child in seed.children}: - raise WorkerError( - f"can't clean up {seed.name}: it no longer has the children " - f"{', '.join(sorted(unknown))} that it was set up with" - ) - if children: - shared = seed.share(handle) - for child in reversed(seed.children): - if child.name in children: - child.parent = shared - _clean_up(child, children[child.name]) - _call(seed.cleanup, handle) - - -def _seed_handles(case: Case, handles: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: - """Flatten the handle trees into one handle per seed name.""" - out: dict[str, dict[str, Any]] = {} - - def add(seed: Seed, handle: dict[str, Any]) -> None: - if not seed.children: - out[seed.name] = handle - return - out[seed.name] = handle["handle"] - for child in seed.children: - if child.name in handle["children"]: - add(child, handle["children"][child.name]) - - for seed in case.seeds: - if seed.name in handles: - add(seed, handles[seed.name]) - return out + return None if seed_results is None else _json_dict(seed_results, f"{type(seed).__name__}.load_cached()") # Credentials.