diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3a64b8..f8420a9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,11 +32,27 @@ jobs: - name: Update Rust run: | rustup update stable --no-self-update && rustup default stable - rustup component add clippy + rustup component add clippy rustfmt - name: Lint run: make lint + generate: + name: make generate-check + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Update Rust + run: rustup update stable --no-self-update && rustup default stable + + # Other repos read schemas/, and the SDKs' types come from the protocol's + # schema, so both must match the Rust types. + # No Python setup: the script needs only the image's python3. + - name: Check generated files + run: make generate-check + version: name: make version-check runs-on: ubuntu-latest diff --git a/Makefile b/Makefile index 0dc33e6..0ebe252 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ PYTHON ?= python3 MANIFEST := core/Cargo.toml .DEFAULT_GOAL := help -.PHONY: help build install test lint generate generate-check version version-check +.PHONY: help build install test lint fmt generate generate-check version version-check help: ## list the targets @awk -F ':.*## ' '/^[a-z-]+:.*## / {printf " %-15s %s\n", $$1, $$2}' $(MAKEFILE_LIST) @@ -17,10 +17,14 @@ install: ## install eac into ~/.cargo/bin test: ## run the CLI's tests $(CARGO) test --manifest-path $(MANIFEST) -lint: ## run clippy on the CLI and its tests, failing on any warning +lint: ## check formatting and run clippy on the CLI and its tests, failing on any warning + $(CARGO) fmt --manifest-path $(MANIFEST) --check $(CARGO) clippy --manifest-path $(MANIFEST) --all-targets -- -D warnings -generate: ## regenerate protocol.schema.json and the Python SDK's protocol.py +fmt: ## format the CLI's code + $(CARGO) fmt --manifest-path $(MANIFEST) + +generate: ## regenerate the protocol's and results' JSON Schemas and the Python SDK's protocol.py $(PYTHON) scripts/generate.py generate-check: ## fail if a generated file is out of date diff --git a/README.md b/README.md index de95b35..4b9df81 100644 --- a/README.md +++ b/README.md @@ -17,24 +17,14 @@ You write the runner that calls your system, the cases, and the judges that scor pip install -e sdks/python # into the environment your evals run in ``` -2. Add a project. An empty `eac.yml` marks its root, and each dataset gets a folder with a `dataset.yml` and its code: +2. Add a dataset: a folder anywhere in your repo with a `dataset.yml` and its code. eac finds every `dataset.yml` under the repo's root, or under the nearest folder with an [`eac.yml`](core/README.md#eacyml) if you need shared settings. ``` - eac.yml evals/chat/ dataset.yml dataset.py ``` - ```yaml - # eac.yml - runtimes: - python: - # TODO - env: {PYTHONPATH: ../../sdks/python} - - ``` - ```yaml # evals/chat/dataset.yml name: chat @@ -46,8 +36,7 @@ You write the runner that calls your system, the cases, and the judges that scor ```python # evals/chat/dataset.py - from eac import Case, OfflineRunner - from eac.judges import Contains + from eac import Case, Judge, OfflineRunner, Score def reply(query: str) -> str: @@ -55,20 +44,22 @@ You write the runner that calls your system, the cases, and the judges that scor class ChatRunner(OfflineRunner): - def execute(self, case, ctx): + def run_case(self, case, *, seeds, conversation_id): return {"response": reply(case.input["query"])} - CASES = [ - Case( - name="greets", - input={"query": "hi"}, - judges=[Contains(["hello"])] - ) - ] + class Greets(Judge): + name = "greets" + + def judge(self, case, *, seeds, agent_trace=None): + ok = "hello" in case.output.get("response", "") + return Score(name=self.name, score=1.0 if ok else 0.0) + + + CASES = [Case(name="greets", input={"query": "hi"}, judges=[Greets()])] ``` -3. Run it from the project's root: +3. Run it from the repo's root: ```sh eac list # the datasets and cases eac found @@ -76,7 +67,7 @@ You write the runner that calls your system, the cases, and the judges that scor # Alternatively, run each step separately eac offline seed --dataset chat # seed (create fixtures) into a new run - eac offline collect # collect (execute cases) for the latest run + eac offline collect # collect (run each case) for the latest run eac offline judge # judge (judge output of collect) for the latest run ``` @@ -85,7 +76,7 @@ project to start from. ### Online evals -Online evals judge what your system already did in production, so there are no cases or seeds. You write the runner that collects production records and the judges that score them. +Online evals judge what your system already did in production, so nothing is re-run and there are no seeds. You write the runner that collects production runs as cases, and the judges that score them. 1. Install the `eac` CLI and SDK as in step 1 above. @@ -98,34 +89,30 @@ Online evals judge what your system already did in production, so there are no c online: runner: ./dataset.py:ProdChats judges: - - {name: greets, path: ./dataset.py:GREETS} + - {name: greets, path: ./dataset.py:Greets} ``` ```python - # evals/chat/dataset.py - from eac import OnlineRunner, Record - from eac.judges import Contains + # evals/chat/dataset.py, next to the Greets judge above + from eac import Case, OnlineRunner class ProdChats(OnlineRunner): - def fetch(self, since, until, limit): + def collect_cases(self, window): rows = [{"id": "trace-1", "query": "hi", "reply": "hello there"}] # query production here return [ - Record(id=row["id"], input={"query": row["query"]}, output={"response": row["reply"]}) - for row in rows[:limit] + Case(name=row["id"], input={"query": row["query"]}, output={"response": row["reply"]}) + for row in rows[: window.limit] ] - - - GREETS = Contains(["hello"]) ``` -3. Run it from the project's root: +3. Run it from the repo's root: ```sh - eac online run --dataset chat --judge greets --since 24h # fetch the last 24h of records and judge them + eac online run --dataset chat --judge greets --since 24h # collect the last 24h of production runs and judge them # Alternatively, run each step separately - eac online collect --dataset chat --since 24h # collect (fetch records) into a new run + eac online collect --dataset chat --since 24h # collect production runs as cases into a new run eac online judge --judge greets # judge the latest collected run ``` diff --git a/core/PROTOCOL.md b/core/PROTOCOL.md index 141efca..9e4bc15 100644 --- a/core/PROTOCOL.md +++ b/core/PROTOCOL.md @@ -8,7 +8,7 @@ The protocol is defined by the Rust types in [`src/schema/`](src/schema). `make Workers (`python -m eac.worker`) import the user's datasets and do the real work: setting up seeds, running cases and judging outputs. Connections to outside services, like a seed cache shared between machines or a source of agent traces, are methods on the user's seeds and judges, so the worker calls them too. -eac starts each worker the first time it's needed, in the project root next to `eac.yml`, and reuses it for the rest of the command. +eac starts each worker the first time it's needed, in the project root, and reuses it for the rest of the command. **One request at a time.** @@ -44,7 +44,7 @@ eac sets these variables for the workers it starts: | `EAC_WORKER=1` | Tells the worker the CLI started it | | `EAC_ROOT` | The project root | -Workers also get the variables in the `.env` next to `eac.yml`, unless the real environment, saved credentials or the runtime's `env` in `eac.yml` already set them. +Workers also get the variables in the `.env` in the project root, unless the real environment, saved credentials or the runtime's `env` in `eac.yml` already set them. ## What each command sends @@ -52,11 +52,11 @@ Each phase sends its own methods, so a worker only needs to answer the ones for ``` offline seed discover → args.validate → seed.setup -offline collect case.execute +offline collect case.run offline judge case.judge offline run all three phases, then seed.teardown for uncached seeds (compare does the same for each arm) offline prune discover → seed.teardown -online collect discover → args.validate → online.fetch +online collect discover → args.validate → online.collect online judge args.validate → online.judge list, catalog discover auth discover → args.validate → credentials.check → credentials.login @@ -69,8 +69,9 @@ Before each phase, eac also sends `credentials.check` for what the phase needs, These types show up in the params and results of many methods: ```jsonc -// Case +// 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.collect, 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 @@ -96,7 +97,7 @@ These types show up in the params and results of many methods: "judges": [{"name": "polite", "path": "evals.chat.judges:Polite"}]} // online: named judges // Score: 0..1; null is a diagnostic that doesn't gate pass/fail -{"name": "regex", "score": 1.0, "label": null, "explanation": null, "metadata": {}, +{"name": "regex", "score": 1.0, "explanation": null, "metadata": {}, "llm_judge_metrics": Metrics} // optional: what an LLM judge spent on this score // Metrics: every field optional, default 0 @@ -104,8 +105,6 @@ These types show up in the params and results of many methods: "cache_write_tokens": 0, "reasoning_tokens": 0, "llm_duration_seconds": 0, "llm_calls": 0, "tool_calls": 0, "cost_usd": 0} -// Record: a production run, for online judging -{"id": "run-123", "conversation_id": "abc", "input": {}, "output": {}} ``` ## Worker methods @@ -119,21 +118,17 @@ Params: `{"dataset"}`. Imports the dataset's code and returns what only the code knows. It shouldn't have side effects beyond the import. Everything else, like the name, agent, comparisons, shard config and online judges, comes from the `dataset.yml`. ```jsonc -{"cases": [Case], // offline: every case - "args_schema": {}, // optional: JSON Schema of the runner's args, for `eac catalog` - "judge_args_schemas": {"llm_judge": {}}} // JSON Schema of each judge's args, for judges that take any +{"cases": [Case]} // offline: every case; online: nothing ``` ### `args.validate` Params: `{"dataset", "mode": "offline"|"online", "args", "judges"?, "judge_args"?}`. -eac calls this with `--args` and `--judge-args` before setting anything up, so bad args fail early. `judges` is an online run's chosen judges, or the judges a comparison scores every case with. Check that those can be built. +eac calls this before setting anything up. `judges` is an online run's chosen judges, or the judges a comparison scores every case with. Check that those can be built. -- `judge_args` is keyed by judge name, e.g. `{"llm_judge": {"rubric_file": "r.md"}}`. Check the entries for this dataset's judges and ignore the rest. One run's `--judge-args` cover all its datasets, and eac itself rejects names that no dataset uses. -- Return an error to reject the args. -- Return `{"args": {...}}` with defaults filled in. Those are the args eac records and sends to the runner. -- Also return `"runner_credentials": [Credential]`, what the runner needs with these args, and `"judge_credentials": {name: [Credential]}`, what each of the run's judges needs. eac records both so later phases can check them. +- Return `"runner_credentials": [Credential]`, what the runner needs, and `"judge_credentials": {name: [Credential]}`, what each of the run's judges needs. eac records both so later phases can check them. +- `args` is `--args` and `judge_args` is `--judge-args`, keyed by judge name, e.g. `{"llm_judge": {"rubric_file": "r.md"}}`. eac records them as given and sends them on to the runner and judges, and rejects judge names that no dataset uses. An SDK may return an error to reject them, but doesn't have to check them. ### `seed.setup` / `seed.teardown` @@ -147,7 +142,7 @@ eac keeps cached seeds (`cache: true`) in `/seed-cache.json` and only `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.execute` +### `case.run` Params: `{"dataset", "case", "seeds": {name: handle}, "args", "conversation_id"}`. @@ -158,27 +153,28 @@ Runs the system under test on one case. ### `case.judge` -Params: `{"dataset", "case", "judges"?, "output", "error"?, "seeds": {name: handle}, "judge_args"?, "trace"?, "conversation_id"?, "agent"?, "started_at"?, "ended_at"?}`. +Params: `{"dataset", "case", "judges"?, "error"?, "seeds": {name: handle}, "judge_args"?, "trace"?, "agent"?, "started_at"?, "ended_at"?}`. Scores one case's output and returns `{"scores": [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. - `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. -**Agent traces.** Without a `trace`, the judges may fetch the agent run's trace, looking it up by `conversation_id`, the dataset's `agent` and when the case ran (`started_at` and `ended_at`, RFC 3339). Give every judge the same trace, and return it as `"trace"`, with the LLM usage it records as `"trace_metrics"` (a Metrics). eac saves it under `traces/` in the run and sends it back as `trace` when the run is judged again. Its metrics replace the ones `case.execute` returned. A failed fetch should only warn, since judges can run without a trace. +**Agent traces.** Without a `trace`, the judges may fetch the agent run's trace, looking it up by the case's `conversation_id`, the dataset's `agent` and when the case ran (`started_at` and `ended_at`, RFC 3339). Give every judge the same trace, and return it as `"trace"`, with the LLM usage it records as `"trace_metrics"` (a Metrics). eac saves it under `traces/` in the run and sends it back as `trace` when the run is judged again. Its metrics replace the ones `case.run` returned. A failed fetch should only warn, since judges can run without a trace. -### `online.fetch` +### `online.collect` Params: `{"dataset", "since", "until", "limit", "args"}`. -Returns `{"records": [Record]}`, the production records from the window between `since` and `until` (both RFC 3339 times), at most `limit` of them. +Returns `{"cases": [Case]}`, the production runs from the window between `since` and `until` (both RFC 3339 times), at most `limit` of them. Each case has its `output`, and its `conversation_id` if it has one. ### `online.judge` -Params: `{"dataset", "record", "judges", "judge_args"?, "trace"?, "agent"?}`. +Params: `{"dataset", "case", "judges", "judge_args"?, "trace"?, "agent"?}`. -Scores the record 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`, looked up by the record's `conversation_id`, and records have no run times. +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. ### `credentials.check` / `credentials.login` diff --git a/core/README.md b/core/README.md index 3343225..b53f7fc 100644 --- a/core/README.md +++ b/core/README.md @@ -29,7 +29,7 @@ The CLI drives every run, but your code runs in separate SDK processes. The CLI **Projects and datasets.** -`eac.yml` marks the root of a project and holds settings that every dataset shares. Each dataset is a `dataset.yml` file that sits next to its code, anywhere under the root. +A project's root is the nearest folder with an `eac.yml`, which holds settings that every dataset shares, or else the git repository's root. Each dataset is a `dataset.yml` file that sits next to its code, anywhere under the root. The CLI finds all of them, checks everything up front into a single `Config`, and then picks the datasets the command applies to. @@ -71,7 +71,7 @@ eac offline judge score each output **Seed** -Picks the cases, checks `--args`, creates the run and sets up each case's seeds (fixtures like a project or a database). Cases that share a seed share one setup, and cached seeds are reused from earlier runs, or loaded from the seed's own cache. The run id is printed to stdout so CI can pass it to the later phases. +Picks the cases, creates the run and sets up each case's seeds (fixtures like a project or a database). Cases that share a seed share one setup, and cached seeds are reused from earlier runs, or loaded from the seed's own cache. The run id is printed to stdout so CI can pass it to the later phases. **Collect** @@ -88,13 +88,13 @@ Runs the case's judges on its output, and saves the scores, results and a summar Online evals judge what your system already did in production. There are no seeds, so there are only two phases: ``` -eac online collect fetch production records from a time window -> outputs/ -eac online judge score each record with the picked judges -> scores/ traces/ results/ summary.json +eac online collect 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 ``` **Collect** -Asks each dataset's online runner for the records in a time window (`--since`, `--window-end`, `--limit`) and saves each one as an output. +Asks each dataset's online runner for the production runs in a time window (`--since`, `--window-end`, `--limit`), as cases with their outputs, and saves each output. **Judge** @@ -120,8 +120,9 @@ Building needs Rust 1.87 or newer ([rustup](https://rustup.rs)) on macOS or Linu make build # release build -> core/target/release/eac make install # install eac into ~/.cargo/bin make test # unit and end-to-end tests -make lint # clippy, failing on any warning -make generate # regenerate the files derived from src/schema/ +make lint # rustfmt check and clippy, failing on any warning +make fmt # format the code +make generate # regenerate the JSON schemas and SDK models make generate-check # fail if a generated file is out of date make version # copy the version in VERSION into the CLI and SDKs make version-check # fail if the CLI or an SDK doesn't match VERSION @@ -139,10 +140,11 @@ Unit tests sit next to the code they test. The end-to-end tests in `tests/cli.rs ## Making common changes -- **New flag or command** - define it in `src/cli/args.rs` (shared flags go in `flags.rs`), route it in `dispatch.rs` and implement it in `src/commands/`. -- **New config key** - add it to `eac_yml.rs` or `dataset_yml.rs` in `src/eac/config/` and check it in that module's `impl Loader`, so mistakes fail before anything runs. Then document it below. +- **New flag or command** - define it in `src/cli/args.rs` (groups of flags several commands share go in `flags.rs`), route it in `dispatch` in `src/cli/mod.rs` and implement it in `src/commands/`. +- **New config key** - add it to `EacYml` in `src/eac/config/mod.rs` or `DatasetConfig` in `dataset_yml.rs`, and check it where that file is loaded (`Config::load` or `DatasetConfig::load`), so mistakes fail before anything runs. Then document it below. - **New version** - change `VERSION` at the repo root and run `make version`, which updates `Cargo.toml`, `Cargo.lock` and each SDK's version. CI's `make version-check` fails if they drift. `eac --version` prints it. - **Protocol change** - edit the types in `src/schema/` and run `make generate` (needs Python 3.9+), which rewrites `protocol.schema.json` and the Python SDK's `protocol.py`. Then update [PROTOCOL.md](PROTOCOL.md), the Python SDK and the stand-in worker in `tests/fixtures/project`. +- **Results change** - edit the types in `src/eac/run/results.rs` and run `make generate`, which rewrites [`schemas/results.schema.json`](../schemas/results.schema.json). Bump `RESULTS_VERSION` for any change a reader could trip over, like a removed or renamed field or a new status. Seer's evals and the evals platform follow this schema, so keep them in step. ## Reference @@ -150,16 +152,12 @@ The full reference for the config files and the run directory. The [Python SDK's ### eac.yml -eac looks for `eac.yml` in the current directory (or `-C`), then in each parent. Paths in it are relative to it, workers run in its directory, and every key is optional. +`eac.yml` is optional. eac looks for it in the current directory (or `-C`), then in each parent, and its folder is the project root. Without one, the root is the git repository's root, or else the current directory. Paths are relative to the root, workers run in it, and every key is optional. ```yaml artifacts: .eac # where runs and the seed cache go exclude: [legacy_evals] # not searched for dataset.yml -online: - judges: # every online dataset offers these - - {name: llm_judge, path: "evals.judges.llm:LlmJudge", runtime: python} - runtimes: python: command: [uv, run, python] # eac appends: -u -m eac.worker @@ -167,8 +165,7 @@ runtimes: ``` - `exclude` - folders and files not searched for `dataset.yml`, like another tool's datasets with the same file name. Each must exist. -- `runtimes` - how each runtime's processes start. Python comes from the first of `$EAC_PYTHON`, `runtimes.python.command`, the active virtualenv, the nearest `.venv` up to the repo root, `uv run python` if there's a `uv.lock`, then `python3`. Every process eac starts also gets the variables in the `.env` next to `eac.yml` that the environment doesn't already set. -- `online.judges` - judges every online dataset offers. +- `runtimes` - how each runtime's processes start. Python comes from the first of `$EAC_PYTHON`, `runtimes.python.command`, the active virtualenv, the nearest `.venv` up to the repo root, `uv run python` if there's a `uv.lock`, then `python3`. Every process eac starts also gets the variables in the `.env` in the project root that the environment doesn't already set. Seed caches shared between machines and agent trace sources aren't config. They're methods on seeds and judges, covered in the [Python SDK's README](../sdks/python/README.md). @@ -182,12 +179,12 @@ runtime: python # required; python is the only one so far offline: runner: ./offline_runner.py:AutofixRcaEvalRunner # an OfflineRunner - cases: ./offline_cases.py:AUTOFIX_RCA_SCENARIOS # a sequence of Cases + cases: ./offline_cases.py:AUTOFIX_RCA_CASES # a sequence of Cases shard_config: {cases_per_shard: 12, max_shards: 10} concurrency: 4 # optional: cases run at once (default 1) comparisons: - name: coding_agents - judges: [AutofixRcaLlmEvaluator] # optional: score every case with these instead + judges: [AutofixRcaLlmJudge] # optional: score every case with these instead arms: - name: seer - name: claude_code @@ -204,7 +201,7 @@ online: - A dataset needs an `offline` section, an `online` section, or both. - Code references are `module.path:attr` (from the project root) or `./file.py:attr` (relative to the `dataset.yml`, and the file must exist). A file inside a package is imported under its module name, so it's the same module the rest of your code imports. - A runner or judge reference can be a configured instance or a class, which eac builds with no arguments. -- Online judges are named. `--judge` and `--judge-args` use the YAML name, while scores keep the judge's own name. A dataset's judges replace any of `eac.yml`'s `online.judges` with the same name. +- Online judges are named. `--judge` and `--judge-args` use the YAML name, while scores keep the judge's own name. Each online dataset lists its own judges, which run in its worker. To share a judge, reference the same code from each `dataset.yml`. - `concurrency` is how many cases run, and then judge, at once. eac starts up to that many workers, each importing your code separately and handling one case at a time. Seeding still happens one seed at a time. ### Run directory @@ -218,11 +215,11 @@ online: outputs//.json traces//.json agent traces the judges fetched scores//.json - results/.json each dataset's results in seer's RunResult shape + 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. 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: +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: ```sh id=$(eac offline run --dataset chat); ./upload.py ".eac/runs/$id" diff --git a/core/rustfmt.toml b/core/rustfmt.toml new file mode 100644 index 0000000..100574f --- /dev/null +++ b/core/rustfmt.toml @@ -0,0 +1,3 @@ +# Keeps short expressions, struct literals and calls on one line, up to the +# usual 100 columns, instead of rustfmt's narrower defaults. +use_small_heuristics = "Max" diff --git a/core/src/cli/args.rs b/core/src/cli/args.rs index dd92373..9cf7660 100644 --- a/core/src/cli/args.rs +++ b/core/src/cli/args.rs @@ -1,22 +1,21 @@ -//! The commands and the flags each takes. +//! Every command and its flags. Groups of flags several commands share are in +//! flags.rs. use std::path::PathBuf; -use clap::{Parser, Subcommand}; +use clap::{Args, Parser, Subcommand, ValueEnum}; -use super::flags::{ - Concurrency, JudgeArgs, JudgedRunArgs, KeepSeeds, Project, RunArgs, RunRef, Scope, Select, - ShardArgs, WindowArgs, -}; -use super::parse::{parse_meta, parse_object}; +use super::flags::{Project, RunFlags, Scope, Select, ShardFlags, WindowFlags}; +use super::parse::{parse_count, parse_meta, parse_object}; +use crate::eac::LATEST; use crate::schema::Object; #[derive(Parser)] #[command( name = "eac", version, - about = "Run evals defined in code", - after_help = "exit codes: 0 all passed, 1 failures or errors, 2 eac itself failed" + about = "Evals as Code", + after_help = "exit codes: 0 no failures or errors, 1 failures or errors, 2 eac itself failed" )] pub struct Cli { #[command(subcommand)] @@ -26,163 +25,208 @@ pub struct Cli { #[derive(Subcommand)] pub enum Command { /// Show the datasets and cases eac can see - List { - #[command(flatten)] - scope: Scope, - #[command(flatten)] - select: Select, - }, - /// Print each dataset's cases, splits, comparisons and args schemas as JSON - Catalog { - #[command(flatten)] - scope: Scope, - /// Write the catalog to a file instead of stdout - #[arg(long, value_name = "FILE")] - output: Option, - }, + List(ListArgs), + /// Print each dataset's cases, splits and comparisons as JSON + Catalog(CatalogArgs), /// Run the system on your own cases and score it #[command(subcommand)] Offline(Offline), - /// Score records fetched from production + /// Score what the system already did in production #[command(subcommand)] Online(Online), /// Check the credentials the datasets need, and log in to any that aren't set up - Auth { - #[command(flatten)] - scope: Scope, - }, - /// Print the worker protocol's JSON Schema, for `make generate` + Auth(Scope), + /// Print a JSON Schema, for `make generate` #[command(hide = true)] - Schema, + Schema { + #[arg(value_enum, default_value = "protocol")] + which: SchemaKind, + }, +} + +#[derive(Clone, Copy, ValueEnum)] +pub enum SchemaKind { + /// The worker protocol + Protocol, + /// results/.json + Results, } #[derive(Subcommand)] pub enum Offline { /// Set up fixtures -> seeds.json, printing the new run's id - Seed { - #[command(flatten)] - scope: Scope, - #[command(flatten)] - select: Select, - #[command(flatten)] - shard: ShardArgs, - #[command(flatten)] - run_args: JudgedRunArgs, - /// Tear down an existing run's uncached seeds instead - #[arg(long)] - teardown: bool, - #[command(flatten)] - run: RunRef, - }, + Seed(SeedArgs), /// Collect outputs by running the system under test on a seeded run -> outputs/ - Collect { - #[command(flatten)] - project: Project, - #[command(flatten)] - run: RunRef, - #[command(flatten)] - concurrency: Concurrency, - }, + Collect(PhaseArgs), /// Score recorded outputs -> scores/, results/, summary.json - Judge { - #[command(flatten)] - project: Project, - #[command(flatten)] - run: RunRef, - #[command(flatten)] - concurrency: Concurrency, - }, + Judge(PhaseArgs), /// Seed, collect and judge in one go - Run { - #[command(flatten)] - scope: Scope, - #[command(flatten)] - select: Select, - #[command(flatten)] - shard: ShardArgs, - #[command(flatten)] - run_args: JudgedRunArgs, - #[command(flatten)] - concurrency: Concurrency, - #[command(flatten)] - keep: KeepSeeds, - }, + Run(RunArgs), /// Run a dataset comparison, one run per arm with shared seeds - Compare { - /// Comparison name, as defined in the dataset - comparison: String, - #[command(flatten)] - scope: Scope, - #[command(flatten)] - select: Select, - /// JSON args for every arm, overridden by each arm's own args - #[arg(long, value_name = "JSON", value_parser = parse_object)] - args: Option, - /// JSON args for the judges, by judge name, for every arm - #[arg(long, value_name = "JSON", value_parser = parse_object)] - judge_args: Option, - #[arg(long = "meta", value_name = "KEY=VALUE", value_parser = parse_meta)] - meta: Vec<(String, String)>, - #[command(flatten)] - concurrency: Concurrency, - #[command(flatten)] - keep: KeepSeeds, - }, + Compare(CompareArgs), /// Print how many shards CI should run the selected cases in - Shards { - #[command(flatten)] - scope: Scope, - #[command(flatten)] - select: Select, - }, + Shards(ListArgs), /// Tear down the locally cached seeds no case uses - Prune { - #[command(flatten)] - project: Project, - /// Tear down every cached seed instead - #[arg(long)] - all: bool, - }, + Prune(PruneArgs), } #[derive(Subcommand)] pub enum Online { - /// Collect production records from a window -> outputs/, printing the new run's id - Collect { - #[command(flatten)] - scope: Scope, - #[command(flatten)] - window: WindowArgs, - #[command(flatten)] - run_args: RunArgs, - }, - /// Score a collected run's records with --judge -> scores/, results/, summary.json - Judge { - #[command(flatten)] - project: Project, - #[command(flatten)] - run: RunRef, - /// One of the datasets' online judges to score with (repeatable). Defaults - /// to the ones the run was last judged with - #[arg(long = "judge", visible_alias = "judges", value_name = "NAME")] - judges: Vec, - #[command(flatten)] - judge_args: JudgeArgs, - #[command(flatten)] - concurrency: Concurrency, - }, + /// Collect production runs from a window as cases -> outputs/, printing the new run's id + Collect(OnlineCollectArgs), + /// Score a collected run's cases with --judge -> scores/, results/, summary.json + Judge(OnlineJudgeArgs), /// Collect and judge in one go - Run { - #[command(flatten)] - scope: Scope, - /// One of the dataset's online judges to score with (required, repeatable) - #[arg(long = "judge", visible_alias = "judges", value_name = "NAME")] - judges: Vec, - #[command(flatten)] - window: WindowArgs, - #[command(flatten)] - run_args: JudgedRunArgs, - #[command(flatten)] - concurrency: Concurrency, - }, + Run(OnlineRunArgs), +} + +// The structs below have no doc comments of their own, so each command's help +// comes from its variant above. + +const CONCURRENCY: &str = "Cases to run at once per dataset, each on its own worker. \ + Overrides dataset.yml (default: its concurrency, or 1)"; +const JUDGE_ARGS: &str = r#"JSON args for the judges, by judge name, e.g. '{"llm_judge": {"rubric_file": "rubric.md"}}'"#; + +#[derive(Args)] +pub struct ListArgs { + #[command(flatten)] + pub scope: Scope, + #[command(flatten)] + pub select: Select, +} + +#[derive(Args)] +pub struct CatalogArgs { + #[command(flatten)] + pub scope: Scope, + /// Write the catalog to a file instead of stdout + #[arg(long, value_name = "FILE")] + pub output: Option, +} + +#[derive(Args)] +pub struct SeedArgs { + #[command(flatten)] + pub scope: Scope, + #[command(flatten)] + pub select: Select, + #[command(flatten)] + pub shard: ShardFlags, + #[command(flatten)] + 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, + /// Run id to operate on + #[arg(long, value_name = "ID", default_value = LATEST)] + pub run: String, +} + +// For the offline phases that work 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, +} + +#[derive(Args)] +pub struct RunArgs { + #[command(flatten)] + pub scope: Scope, + #[command(flatten)] + pub select: Select, + #[command(flatten)] + pub shard: ShardFlags, + #[command(flatten)] + pub run_flags: RunFlags, + #[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, + /// Leave uncached seeds in place after the run + #[arg(long)] + pub keep_seeds: bool, +} + +#[derive(Args)] +pub struct CompareArgs { + /// Comparison name, as defined in the dataset + pub comparison: String, + #[command(flatten)] + pub scope: Scope, + #[command(flatten)] + pub select: Select, + /// JSON args for every arm, overridden by each arm's own args + #[arg(long, value_name = "JSON", value_parser = parse_object)] + pub args: Option, + /// JSON args for the judges, by judge name, for every arm + #[arg(long, value_name = "JSON", value_parser = parse_object)] + pub judge_args: Option, + #[arg(long = "meta", value_name = "KEY=VALUE", value_parser = parse_meta)] + pub meta: Vec<(String, String)>, + #[arg(long, value_name = "N", value_parser = parse_count, help = CONCURRENCY)] + pub concurrency: Option, + /// Leave uncached seeds in place after the run + #[arg(long)] + pub keep_seeds: bool, +} + +#[derive(Args)] +pub struct PruneArgs { + #[command(flatten)] + pub project: Project, + /// Tear down every cached seed instead + #[arg(long)] + pub all: bool, +} + +#[derive(Args)] +pub struct OnlineCollectArgs { + #[command(flatten)] + pub scope: Scope, + #[command(flatten)] + pub window: WindowFlags, + #[command(flatten)] + pub run_flags: RunFlags, +} + +#[derive(Args)] +pub struct OnlineJudgeArgs { + #[command(flatten)] + pub project: Project, + /// Run id to operate on + #[arg(long, value_name = "ID", default_value = LATEST)] + pub run: String, + /// One of the datasets' online judges to score with (repeatable). Defaults + /// to the ones the run was last judged with + #[arg(long = "judge", visible_alias = "judges", value_name = "NAME")] + pub judges: Vec, + #[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, +} + +#[derive(Args)] +pub struct OnlineRunArgs { + #[command(flatten)] + pub scope: Scope, + /// One of the dataset's online judges to score with (required, repeatable) + #[arg(long = "judge", visible_alias = "judges", value_name = "NAME")] + pub judges: Vec, + #[command(flatten)] + pub window: WindowFlags, + #[command(flatten)] + pub run_flags: RunFlags, + #[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/dispatch.rs b/core/src/cli/dispatch.rs deleted file mode 100644 index a1fb614..0000000 --- a/core/src/cli/dispatch.rs +++ /dev/null @@ -1,99 +0,0 @@ -use anyhow::Result; - -use super::args::{Command, Offline, Online}; -use super::flags::{JudgeArgs, JudgedRunArgs, RunArgs}; -use crate::commands; - -pub fn dispatch(command: Command) -> Result<()> { - match command { - // TODO - Command::List { scope, select } => commands::list(&scope, &select), - // TODO - Command::Catalog { scope, output } => commands::catalog(&scope, output.as_deref()), - Command::Auth { scope } => commands::auth(&scope), - Command::Schema => commands::schema(), - Command::Offline(Offline::Seed { - scope, - select, - shard, - run_args, - teardown, - run, - }) => { - if teardown { - commands::teardown(&scope.project, &run) - } else { - commands::seed(&scope, &select, &shard, &run_args) - } - } - Command::Offline(Offline::Collect { - project, - run, - concurrency, - }) => commands::collect(&project, &run, &concurrency), - Command::Offline(Offline::Judge { - project, - run, - concurrency, - }) => commands::judge(&project, &run, &concurrency), - Command::Offline(Offline::Run { - scope, - select, - shard, - run_args, - concurrency, - keep, - }) => commands::run(&scope, &select, &shard, &run_args, &concurrency, &keep), - Command::Offline(Offline::Compare { - comparison, - scope, - select, - args, - judge_args, - meta, - concurrency, - keep, - }) => { - // Base args for every arm. Each arm's own args override them. - let run_args = JudgedRunArgs { - run: RunArgs { - args: Some(args.unwrap_or_default()), - variant: None, - meta, - }, - judge: JudgeArgs { - judge_args: Some(judge_args.unwrap_or_default()), - }, - }; - commands::compare( - &comparison, - &scope, - &select, - &run_args, - &concurrency, - &keep, - ) - } - Command::Offline(Offline::Shards { scope, select }) => commands::shards(&scope, &select), - Command::Offline(Offline::Prune { project, all }) => commands::prune(&project, all), - Command::Online(Online::Collect { - scope, - window, - run_args, - }) => commands::online_collect(&scope, &window, &run_args), - Command::Online(Online::Judge { - project, - run, - judges, - judge_args, - concurrency, - }) => commands::online_judge(&project, &run, &judges, &judge_args, &concurrency), - Command::Online(Online::Run { - scope, - judges, - window, - run_args, - concurrency, - }) => commands::online_run(&scope, &judges, &window, &run_args, &concurrency), - } -} diff --git a/core/src/cli/flags.rs b/core/src/cli/flags.rs index 5a09b02..e0a0f1a 100644 --- a/core/src/cli/flags.rs +++ b/core/src/cli/flags.rs @@ -1,4 +1,4 @@ -//! Flag groups shared across commands, with helpers to load what they point at. +//! Groups of flags that several commands share. use std::path::PathBuf; use std::time::Duration; @@ -6,14 +6,13 @@ use std::time::Duration; use anyhow::Result; use clap::Args; -use super::parse::{parse_count, parse_duration, parse_meta, parse_object}; -use crate::eac::{report, Config, Discovered, Engine, Manifest, Run, Selection, Shard, LATEST}; -use crate::schema::Object; +use super::parse::{parse_duration, parse_meta, parse_object}; +use crate::eac::{Config, Discovered, Engine, Selection, Shard}; +use crate::report; +use crate::schema::{Mode, Object}; #[derive(Args)] pub struct Project { - /// Directory to find eac.yml from. Below the root, it also limits datasets to - /// those under it #[arg(short = 'C', value_name = "DIR", default_value = ".")] pub dir: PathBuf, } @@ -22,7 +21,6 @@ pub struct Project { pub struct Scope { #[command(flatten)] pub project: Project, - /// Limit to a dataset (repeatable) #[arg(long = "dataset", value_name = "NAME")] pub datasets: Vec, } @@ -38,7 +36,7 @@ pub struct Select { } #[derive(Args)] -pub struct ShardArgs { +pub struct ShardFlags { /// Run only this shard of the selected cases (0-based) #[arg(long, value_name = "N")] pub shard_index: Option, @@ -49,7 +47,7 @@ pub struct ShardArgs { /// What a new run records: its runner args, variant and metadata. #[derive(Args)] -pub struct RunArgs { +pub struct RunFlags { /// JSON args for the runner, checked by the dataset's SDK #[arg(long, value_name = "JSON", value_parser = parse_object)] pub args: Option, @@ -61,98 +59,43 @@ pub struct RunArgs { pub meta: Vec<(String, String)>, } +/// The window of production runs an online run collects. #[derive(Args)] -pub struct JudgeArgs { - /// JSON args for the judges, by judge name, e.g. - /// '{"llm_judge": {"rubric_file": "rubric.md"}}' - #[arg(long, value_name = "JSON", value_parser = parse_object)] - pub judge_args: Option, -} - -/// A new run's args, and the judge args it's judged with. -#[derive(Args)] -pub struct JudgedRunArgs { - #[command(flatten)] - pub run: RunArgs, - #[command(flatten)] - pub judge: JudgeArgs, -} - -/// The window of production records an online run collects. -#[derive(Args)] -pub struct WindowArgs { - /// How far back from --window-end to fetch records, e.g. 30m, 24h +pub struct WindowFlags { + /// How far back from --window-end to collect, e.g. 30m, 24h #[arg(long, visible_alias = "lookback", value_name = "DURATION", default_value = "1h", value_parser = parse_duration)] pub since: Duration, /// End of the window, as an RFC 3339 time (default: now) #[arg(long, value_name = "TIME")] pub window_end: Option, - /// Most records to fetch per dataset + /// Most cases to collect per dataset #[arg(long, default_value_t = 500, allow_negative_numbers = true)] pub limit: i64, } -#[derive(Args)] -pub struct Concurrency { - /// Cases to run at once per dataset, each on its own worker. Overrides - /// dataset.yml (default: its concurrency, or 1) - #[arg(long, value_name = "N", value_parser = parse_count)] - pub concurrency: Option, -} - -#[derive(Args)] -pub struct RunRef { - /// Run id to operate on - #[arg(long = "run", value_name = "ID", default_value = LATEST)] - pub id: String, -} - -#[derive(Args)] -pub struct KeepSeeds { - /// Leave uncached seeds in place after the run - #[arg(long)] - pub keep_seeds: bool, -} - impl Project { /// Loads eac.yml and starts an engine, which closes its workers on drop. pub fn engine(&self) -> Result { - Ok(Engine::new(Config::load(&self.dir)?, &crate::INTERRUPTED)) + Ok(Engine::new(Config::load(&self.dir)?)) } } impl Scope { - /// Imports the selected offline datasets' code. - pub fn discover_offline(&self, engine: &mut Engine) -> Result> { - let datasets = engine.config().select_offline(&self.datasets)?; - report::phase("discover"); - engine.discover(&datasets, &[]) - } - - pub fn discover_online(&self, engine: &mut Engine) -> Result> { - let datasets = engine.config().select_online(&self.datasets)?; - report::phase("discover"); - engine.discover(&[], &datasets) - } - - pub fn discover_all(&self, engine: &mut Engine) -> Result> { - let (offline, online) = engine.config().select_all(&self.datasets)?; + /// Imports the code of the selected datasets that run in mode, or of + /// every selected dataset in both modes if mode is None. + pub fn discover(&self, engine: &mut Engine, mode: Option) -> Result> { + let datasets = engine.config().select(&self.datasets, mode)?; report::phase("discover"); - engine.discover(&offline, &online) + engine.discover(&datasets) } } impl Select { - pub fn selection(&self, shard: Option<&ShardArgs>) -> Selection { + pub fn selection(&self, shard: Option<&ShardFlags>) -> Selection { Selection { cases: self.cases.clone(), splits: self.splits.clone(), - shard: shard.and_then(|s| { - Some(Shard { - index: s.shard_index?, - count: s.shard_count, - }) - }), + shard: shard.and_then(|s| Some(Shard { index: s.shard_index?, count: s.shard_count })), } } @@ -160,11 +103,3 @@ impl Select { self.cases.is_empty() && self.splits.is_empty() } } - -impl RunRef { - pub fn open(&self, engine: &Engine) -> Result<(Run, Manifest)> { - let run = Run::open(&engine.config().artifacts, &self.id)?; - let m = run.read_manifest()?; - Ok((run, m)) - } -} diff --git a/core/src/cli/mod.rs b/core/src/cli/mod.rs index 7943ae8..7a1e206 100644 --- a/core/src/cli/mod.rs +++ b/core/src/cli/mod.rs @@ -1,13 +1,32 @@ -//! Clap definitions and dispatch to `commands`. +//! The command line, and dispatch to `commands`. mod args; -mod dispatch; mod flags; mod parse; -pub use args::Cli; -pub use dispatch::dispatch; -pub use flags::{ - Concurrency, JudgeArgs, JudgedRunArgs, KeepSeeds, Project, RunArgs, RunRef, Scope, Select, - ShardArgs, WindowArgs, -}; +use anyhow::Result; + +pub use args::*; +pub use flags::{RunFlags, Scope, WindowFlags}; + +use crate::commands::{self, offline, online}; + +pub fn dispatch(command: Command) -> Result<()> { + match command { + Command::List(a) => commands::list(&a), + Command::Catalog(a) => commands::catalog(&a), + Command::Auth(scope) => commands::auth(&scope), + 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::Collect(a)) => offline::collect(&a), + Command::Offline(Offline::Judge(a)) => offline::judge(&a), + Command::Offline(Offline::Run(a)) => offline::run(&a), + Command::Offline(Offline::Compare(a)) => commands::compare(&a), + Command::Offline(Offline::Shards(a)) => offline::shards(&a), + Command::Offline(Offline::Prune(a)) => offline::prune(&a), + Command::Online(Online::Collect(a)) => online::collect(&a), + Command::Online(Online::Judge(a)) => online::judge(&a), + Command::Online(Online::Run(a)) => online::run(&a), + } +} diff --git a/core/src/cli/parse.rs b/core/src/cli/parse.rs index 00fd0ac..9c82a90 100644 --- a/core/src/cli/parse.rs +++ b/core/src/cli/parse.rs @@ -24,7 +24,8 @@ pub fn parse_count(s: &str) -> Result { /// Parses a duration such as "30m", "1h30m", "1.5h" or "1d". pub fn parse_duration(s: &str) -> Result { - humantime::parse_duration(s).map_err(|e| format!("invalid duration {s:?} ({e}), e.g. 30m, 1h, 24h")) + humantime::parse_duration(s) + .map_err(|e| format!("invalid duration {s:?} ({e}), e.g. 30m, 1h, 24h")) } #[cfg(test)] @@ -46,10 +47,7 @@ mod tests { #[test] fn meta_and_args() { - assert_eq!( - parse_meta("team=evals=x"), - Ok(("team".into(), "evals=x".into())) - ); + assert_eq!(parse_meta("team=evals=x"), Ok(("team".into(), "evals=x".into()))); assert!(parse_meta("=x").is_err()); assert!(parse_meta("nope").is_err()); assert!(parse_object(r#"{"model": "big"}"#).is_ok()); diff --git a/core/src/commands/auth.rs b/core/src/commands/auth.rs index a609454..cc0da5f 100644 --- a/core/src/commands/auth.rs +++ b/core/src/commands/auth.rs @@ -8,20 +8,19 @@ use crate::schema::{Mode, Object}; /// asked with their default args. pub fn auth(scope: &Scope) -> Result<()> { let mut engine = scope.project.engine()?; - let found = scope.discover_all(&mut engine)?; let mut datasets = Vec::new(); - for f in &found { - if let Some(o) = &f.offline { - let mut d = f.to_dataset(Mode::Offline, o.cases.clone()); - engine.validate_args(&mut d, Mode::Offline, &Object::new())?; - datasets.push(d); + for d in scope.discover(&mut engine, None)? { + if d.config.offline.is_some() { + datasets.push(d.to_dataset(Mode::Offline, d.cases.clone())); } - if let Some(o) = &f.online { - let mut d = f.to_dataset(Mode::Online, vec![]); - d.judges = o.judges.clone(); - engine.validate_args(&mut d, Mode::Online, &Object::new())?; - datasets.push(d); + if let Some(o) = &d.config.online { + let mut online = d.to_dataset(Mode::Online, vec![]); + online.judges = o.judges.iter().map(|j| j.name.clone()).collect(); + datasets.push(online); } } + for d in &mut datasets { + engine.validate_args(d, &Object::new())?; + } engine.set_up_credentials(&datasets) } diff --git a/core/src/commands/catalog.rs b/core/src/commands/catalog.rs index eefd31b..734d259 100644 --- a/core/src/commands/catalog.rs +++ b/core/src/commands/catalog.rs @@ -1,59 +1,56 @@ use std::fs; -use std::path::Path; use anyhow::{Context, Result}; use serde_json::{json, Value}; use super::list::splits_of; -use crate::cli::Scope; +use crate::cli::CatalogArgs; /// Everything a client like a web UI needs to offer runs of each dataset. -pub fn catalog(scope: &Scope, output: Option<&Path>) -> Result<()> { - let mut engine = scope.project.engine()?; - let found = scope.discover_all(&mut engine)?; - let entries: Vec = found - .iter() +pub fn catalog(a: &CatalogArgs) -> Result<()> { + let mut engine = a.scope.project.engine()?; + let found = a.scope.discover(&mut engine, None)?; + let entries: Vec = (found.iter()) .map(|d| { + let enabled = d.cases.iter().filter(|c| c.enabled).count(); + let cases: Vec = d + .cases + .iter() + .map(|c| json!({"name": c.name, "splits": c.splits, "enabled": c.enabled})) + .collect(); json!({ - "name": d.name, - "file": d.file, - "offline": d.offline.as_ref().map(|o| json!({ - "runtime": o.runtime, - "agent": o.agent, - "runner": o.code.runner, - "cases_from": o.code.cases, - "cases": o.cases.iter().map(|c| json!({ - "name": c.name, - "splits": c.splits, - "enabled": c.enabled, - })).collect::>(), - "splits": splits_of(o), + "name": d.config.name, + "file": d.config.file, + "offline": d.config.offline.as_ref().map(|o| json!({ + "runtime": d.config.runtime, + "agent": d.config.agent, + "runner": o.runner, + "cases_from": o.cases, + "cases": cases, + "splits": splits_of(d), "comparisons": o.comparisons, "shard_config": o.shard_config, - "shard_count": o.shard_config.shard_count(o.cases.iter().filter(|c| c.enabled).count()), - "args_schema": o.args_schema, + "shard_count": o.shard_config.shard_count(enabled), })), - "online": d.online.as_ref().map(|o| json!({ - "runtime": o.runtime, - "agent": o.agent, - "runner": o.code.runner, - "judges": o.judges, - "args_schema": o.args_schema, + "online": d.config.online.as_ref().map(|o| json!({ + "runtime": d.config.runtime, + "agent": d.config.agent, + "runner": o.runner, + "judges": o.judges.iter().map(|j| &j.name).collect::>(), })), - "judge_args_schemas": d.judge_args_schemas, }) }) .collect(); + let text = serde_json::to_string_pretty(&entries)?; - match output { - Some(path) => { - if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { - fs::create_dir_all(dir)?; - } - fs::write(path, text + "\n").with_context(|| format!("writing {}", path.display()))?; - info!("wrote {}", path.display()); - } - None => println!("{text}"), + let Some(path) = &a.output else { + println!("{text}"); + return Ok(()); + }; + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + fs::create_dir_all(dir)?; } + fs::write(path, text + "\n").with_context(|| format!("writing {}", path.display()))?; + info!("wrote {}", path.display()); Ok(()) } diff --git a/core/src/commands/compare.rs b/core/src/commands/compare.rs index e836fa7..794ad0b 100644 --- a/core/src/commands/compare.rs +++ b/core/src/commands/compare.rs @@ -1,59 +1,40 @@ -use std::collections::HashSet; +//! `eac offline compare`: one run per arm of a dataset's comparison. + +use std::collections::{BTreeSet, HashSet}; +use std::slice; use anyhow::{bail, Context, Result}; -use super::runs::{check_judge_args, judge_run, new_manifest, seed_run, teardown_uncached}; -use crate::cli::{Concurrency, JudgedRunArgs, KeepSeeds, Scope, Select}; -use crate::eac::{ - report, select, ArmRef, Comparison, Dataset, Discovered, Engine, Manifest, Phase, Run, -}; +use super::runs::{check_judge_args, create_run, seed_collect_judge}; +use crate::cli::CompareArgs; +use crate::eac::{select, ArmRef, Comparison, Dataset, Discovered, Engine, Manifest, ALL_PHASES}; +use crate::report::{self, join_or_none}; use crate::schema::Mode; /// Runs each arm as its own run and prints them side by side. Failing cases /// don't fail the command, since a comparison reports rather than gates. -pub fn compare( - name: &str, - scope: &Scope, - sel: &Select, - run_args: &JudgedRunArgs, - concurrency: &Concurrency, - keep: &KeepSeeds, -) -> Result<()> { - let mut engine = scope.project.engine()?; - engine.set_concurrency(concurrency.concurrency); - let found = scope.discover_offline(&mut engine)?; - let with: Vec<(&Discovered, &Comparison)> = found - .iter() - .filter_map(|d| { - Some(( - d, - d.offline - .as_ref()? - .comparisons - .iter() - .find(|c| c.name == name)?, - )) - }) - .collect(); - if with.is_empty() { - let available: Vec = found - .iter() - .flat_map(|d| { - d.offline - .iter() - .flat_map(|o| &o.comparisons) - .map(move |c| format!("{}.{}", d.name, c.name)) - }) - .collect(); - let available = if available.is_empty() { - "(none)".to_string() - } else { - available.join(", ") - }; - bail!("no selected dataset has a comparison named {name:?}; available: {available}"); +pub fn compare(a: &CompareArgs) -> Result<()> { + let mut engine = a.scope.project.engine()?; + engine.set_concurrency(a.concurrency); + let found = a.scope.discover(&mut engine, Some(Mode::Offline))?; + let (mut matching, mut available) = (Vec::new(), Vec::new()); + for d in &found { + for c in d.config.offline.iter().flat_map(|o| &o.comparisons) { + available.push(format!("{}.{}", d.config.name, c.name)); + if c.name == a.comparison { + matching.push((d, c)); + } + } + } + if matching.is_empty() { + bail!( + "no selected dataset has a comparison named {:?}; available: {}", + a.comparison, + join_or_none(available) + ); } - for (d, comparison) in with { - compare_dataset(&mut engine, d, comparison, sel, run_args, keep)?; + for (d, comparison) in matching { + compare_dataset(&mut engine, d, comparison, a)?; } Ok(()) } @@ -62,113 +43,80 @@ fn compare_dataset( engine: &mut Engine, d: &Discovered, comparison: &Comparison, - sel: &Select, - run_args: &JudgedRunArgs, - keep: &KeepSeeds, + a: &CompareArgs, ) -> Result<()> { - let label = format!("{}.{}", d.name, comparison.name); - let names: Vec<&str> = comparison.arms.iter().map(|a| a.name.as_str()).collect(); - if names.len() < 2 { + let label = format!("{}.{}", d.config.name, comparison.name); + let arm_names: Vec<&str> = comparison.arms.iter().map(|arm| arm.name.as_str()).collect(); + if arm_names.len() < 2 { bail!("{label} needs at least two arms"); } - if names.iter().collect::>().len() != names.len() { - bail!("{label} has duplicate arm names: {}", names.join(", ")); - } - if let Some(arm) = comparison.arms.iter().find(|a| a.sha.is_some()) { - bail!( - "{label} arm {} pins a commit, but eac compares args locally: check the commit out and run it with --variant", - arm.name - ); + if arm_names.iter().collect::>().len() != arm_names.len() { + bail!("{label} has duplicate arm names: {}", arm_names.join(", ")); } // The comparison's split selects like --split, so disabled cases are included. - let mut selection = sel.selection(None); + let mut selection = a.select.selection(None); if let Some(split) = &comparison.split { if selection.splits.is_empty() { selection.splits.push(split.clone()); } } - let mut base = select(std::slice::from_ref(d), &selection)?.remove(0); + let mut base = select(slice::from_ref(d), &selection)?.remove(0); // The comparison's judges replace each case's own judges. if !comparison.judges.is_empty() { - let mut used: Vec<&str> = (base.cases.iter()) - .flat_map(|c| &c.judges) - .map(String::as_str) - .collect(); - used.sort_unstable(); - used.dedup(); - if let Some(unknown) = comparison.judges.iter().find(|j| !used.contains(&j.as_str())) { + let used: BTreeSet<&str> = + base.cases.iter().flat_map(|c| &c.judges).map(String::as_str).collect(); + if let Some(unknown) = comparison.judges.iter().find(|j| !used.contains(j.as_str())) { bail!( "{label} judges with {unknown}, which no case it compares uses; their judges: {}", - used.join(", ") + join_or_none(used) ); } base.judges = comparison.judges.clone(); } - base.judge_args = run_args.judge.judge_args.clone().unwrap_or_default(); - if base.judges.is_empty() { - check_judge_args(&base.judge_args, base.cases.iter().flat_map(|c| &c.judges))?; - } else { - check_judge_args(&base.judge_args, &base.judges)?; - } + base.judge_args = a.judge_args.clone().unwrap_or_default(); + check_judge_args(&base.judge_args, base.used_judges())?; if let Some(split) = &comparison.split { base.cases.retain(|c| c.splits.contains(split)); if base.cases.is_empty() { bail!( "no selected case of {} is in split {split:?}, which {label} compares", - d.name + d.config.name ); } } - info!( - "{:<24} {} cases, arms: {}", - label, - base.cases.len(), - names.join(" ") - ); + info!("{label:<24} {} cases, arms: {}", base.cases.len(), arm_names.join(" ")); // Check every arm's args before setting anything up. - let base_args = run_args.run.args.clone().unwrap_or_default(); let mut arms: Vec<(String, Dataset)> = Vec::new(); for arm in &comparison.arms { - let mut args = base_args.clone(); + let mut args = a.args.clone().unwrap_or_default(); args.extend(arm.args.clone()); let mut dataset = base.clone(); engine - .validate_args(&mut dataset, Mode::Offline, &args) + .validate_args(&mut dataset, &args) .with_context(|| format!("{label} arm {}", arm.name))?; arms.push((arm.name.clone(), dataset)); } let datasets: Vec = arms.iter().map(|(_, d)| d.clone()).collect(); - engine.check_credentials(&datasets, &[Phase::Seed, Phase::Collect, Phase::Judge])?; + engine.check_credentials(&datasets, ALL_PHASES)?; // Each arm seeds separately. Cached seeds come from the shared seed cache, // and uncached ones are fresh because the agent may change them. let mut rows = Vec::new(); for (arm, dataset) in arms { - let run = Run::create(&engine.config().artifacts)?; let m = Manifest { variant: Some(arm.clone()), - comparison: Some(ArmRef { - comparison: comparison.name.clone(), - arm: arm.clone(), - }), + comparison: Some(ArmRef { comparison: comparison.name.clone(), arm: arm.clone() }), + metadata: a.meta.iter().cloned().collect(), datasets: vec![dataset], - ..new_manifest(engine, &run, &run_args.run) + ..Default::default() }; - run.write_manifest(&m)?; + let (run, m) = create_run(engine, m)?; report::phase(&format!("arm {arm}")); info!("run {}", run.id); - let seeds = seed_run(engine, &run, &m)?; - let result = (|| { - report::phase("collect"); - engine.collect(&run, &m, &seeds)?; - judge_run(engine, &run, &m) - })(); - if !keep.keep_seeds { - let _ = teardown_uncached(engine, &seeds); - } - rows.push((arm, run.id.clone(), result?)); + let summary = seed_collect_judge(engine, &run, &m, a.keep_seeds)?; + rows.push((arm, run.id, summary)); } report::print_comparison(&format!("compare {label}"), &rows); Ok(()) diff --git a/core/src/commands/list.rs b/core/src/commands/list.rs index 8510244..20567cf 100644 --- a/core/src/commands/list.rs +++ b/core/src/commands/list.rs @@ -1,26 +1,25 @@ +use std::collections::BTreeSet; + use anyhow::Result; -use crate::cli::{Scope, Select}; -use crate::eac::{select, OfflineInfo}; +use crate::cli::ListArgs; +use crate::eac::{select, Discovered}; -pub fn list(scope: &Scope, sel: &Select) -> Result<()> { - let mut engine = scope.project.engine()?; - let found = scope.discover_all(&mut engine)?; +pub fn list(a: &ListArgs) -> Result<()> { + let mut engine = a.scope.project.engine()?; + let found = a.scope.discover(&mut engine, None)?; // With a selection, list only the cases a run would pick. - let picked = if sel.is_empty() { - None - } else { - Some(select(&found, &sel.selection(None))?) - }; + let picked = + if a.select.is_empty() { None } else { Some(select(&found, &a.select.selection(None))?) }; for d in &found { let mut about = Vec::new(); - match &d.offline { + match &d.config.offline { Some(o) => { - about.push(format!("{} cases", o.cases.len())); - let splits = splits_of(o); + about.push(format!("{} cases", d.cases.len())); + let splits = splits_of(d); if !splits.is_empty() { - about.push(format!("splits: {}", splits.join(" "))); + about.push(format!("splits: {}", Vec::from_iter(splits).join(" "))); } if !o.comparisons.is_empty() { let names: Vec<&str> = o.comparisons.iter().map(|c| c.name.as_str()).collect(); @@ -29,18 +28,17 @@ pub fn list(scope: &Scope, sel: &Select) -> Result<()> { } None => about.push("online only".to_string()), } - if let Some(online) = &d.online { - about.push(format!("online: {}", online.judges.join(" "))); + if let Some(o) = &d.config.online { + let names: Vec<&str> = o.judges.iter().map(|j| j.name.as_str()).collect(); + about.push(format!("online: {}", names.join(" "))); } - info!("{:<24} {} {}", d.name, about.join(", "), d.file); + info!("{:<24} {} {}", d.config.name, about.join(", "), d.config.file); let cases: Vec<_> = match &picked { - Some(picked) => picked - .iter() - .filter(|p| p.name == d.name) - .flat_map(|p| &p.cases) - .collect(), - None => d.offline.iter().flat_map(|o| &o.cases).collect(), + Some(picked) => { + picked.iter().filter(|p| p.name == d.config.name).flat_map(|p| &p.cases).collect() + } + None => d.cases.iter().collect(), }; for c in cases { let splits = if c.splits.is_empty() { @@ -49,21 +47,13 @@ pub fn list(scope: &Scope, sel: &Select) -> Result<()> { format!(" [{}]", c.splits.join(" ")) }; let disabled = if c.enabled { "" } else { " (disabled)" }; - detail!("{}/{}{splits}{disabled}", d.name, c.name); + detail!("{}/{}{splits}{disabled}", d.config.name, c.name); } } Ok(()) } /// Every split a dataset's cases are in, sorted. -pub fn splits_of(o: &OfflineInfo) -> Vec<&str> { - let mut splits: Vec<&str> = o - .cases - .iter() - .flat_map(|c| &c.splits) - .map(String::as_str) - .collect(); - splits.sort_unstable(); - splits.dedup(); - splits +pub fn splits_of(d: &Discovered) -> BTreeSet<&str> { + d.cases.iter().flat_map(|c| &c.splits).map(String::as_str).collect() } diff --git a/core/src/commands/mod.rs b/core/src/commands/mod.rs index 4394d85..61a7af2 100644 --- a/core/src/commands/mod.rs +++ b/core/src/commands/mod.rs @@ -1,19 +1,29 @@ -//! Command implementations, called from `cli`. +//! What each command does. `cli::dispatch` routes each command here. mod auth; mod catalog; mod compare; mod list; -mod offline; -mod online; +pub mod offline; +pub mod online; mod runs; -mod schema; -pub use self::auth::auth; -pub use self::catalog::catalog; -pub use self::compare::compare; -pub use self::list::list; -pub use self::offline::{collect, judge, prune, run, seed, shards, teardown}; -pub use self::online::{online_collect, online_judge, online_run}; -pub use self::runs::FailedRun; -pub use self::schema::schema; +use anyhow::Result; + +pub use auth::auth; +pub use catalog::catalog; +pub use compare::compare; +pub use list::list; +pub use runs::FailedRun; + +use crate::cli::SchemaKind; + +/// Prints a JSON Schema, for `make generate`. +pub fn schema(which: SchemaKind) -> Result<()> { + let schema = match which { + SchemaKind::Protocol => crate::schema::document(), + SchemaKind::Results => crate::eac::results_schema(), + }; + println!("{}", serde_json::to_string_pretty(&schema)?); + Ok(()) +} diff --git a/core/src/commands/offline.rs b/core/src/commands/offline.rs index 5c2ccbb..b03a3e9 100644 --- a/core/src/commands/offline.rs +++ b/core/src/commands/offline.rs @@ -1,26 +1,28 @@ +//! `eac offline`: run the system on your own cases and score it. + use std::collections::HashSet; use anyhow::Result; -use super::runs::{fail_on, judge_run, open_run, seed_run, start_run, teardown_uncached}; -use crate::cli::{ - Concurrency, JudgedRunArgs, KeepSeeds, Project, RunRef, Scope, Select, ShardArgs, +use super::runs::{ + check_judge_args, create_run, fail_on, judge_run, open_run, seed_collect_judge, seed_run, + teardown_uncached, +}; +use crate::cli::{ListArgs, PhaseArgs, PruneArgs, RunArgs, RunFlags, SeedArgs}; +use crate::eac::{ + seed_id, select, Discovered, Engine, Manifest, Phase, Run, Selection, ALL_PHASES, }; -use crate::eac::{report, seed_id, select, Phase, Run}; -use crate::schema::Mode; +use crate::report; +use crate::schema::{Mode, Object}; /// Creates a run and sets up its seeds, printing the run id on stdout so CI /// can pass it to the later phases. -pub fn seed( - scope: &Scope, - sel: &Select, - shard: &ShardArgs, - run_args: &JudgedRunArgs, -) -> Result<()> { - let mut engine = scope.project.engine()?; - let found = scope.discover_offline(&mut engine)?; - let selection = sel.selection(Some(shard)); - let (run, m) = start_run(&mut engine, &found, selection, run_args, &[Phase::Seed])?; +pub fn seed(a: &SeedArgs) -> Result<()> { + let mut engine = a.scope.project.engine()?; + let found = a.scope.discover(&mut engine, Some(Mode::Offline))?; + let selection = a.select.selection(Some(&a.shard)); + let (run, m) = + start_run(&mut engine, &found, selection, &a.run_flags, &a.judge_args, &[Phase::Seed])?; seed_run(&mut engine, &run, &m)?; info!("run {}", run.id); println!("{}", run.id); @@ -28,15 +30,12 @@ pub fn seed( } /// Tears down a run's uncached seeds. Cached ones are kept for later runs. -pub fn teardown(project: &Project, run_ref: &RunRef) -> Result<()> { - let mut engine = project.engine()?; - let run = Run::open(&engine.config().artifacts, &run_ref.id)?; +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().any(|e| !e.cached) { - info!( - "run {} has no uncached seeds; 'eac offline prune' tears down cached ones", - run.id - ); + 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))?; @@ -45,10 +44,10 @@ pub fn teardown(project: &Project, run_ref: &RunRef) -> Result<()> { /// Collects a seeded run's outputs by running the system under test on each /// case. -pub fn collect(project: &Project, run_ref: &RunRef, concurrency: &Concurrency) -> Result<()> { - let mut engine = project.engine()?; - engine.set_concurrency(concurrency.concurrency); - let (run, m) = open_run(&engine, run_ref, Mode::Offline, "collect")?; +pub fn collect(a: &PhaseArgs) -> Result<()> { + let mut engine = a.project.engine()?; + engine.set_concurrency(a.concurrency); + let (run, m) = open_run(&engine, &a.run, Mode::Offline, "collect")?; engine.check_credentials(&m.datasets, &[Phase::Collect])?; let seeds = run.read_seeds()?; report::phase("collect"); @@ -58,61 +57,34 @@ pub fn collect(project: &Project, run_ref: &RunRef, concurrency: &Concurrency) - } /// Re-scores a run's recorded outputs without re-running the system. -pub fn judge(project: &Project, run_ref: &RunRef, concurrency: &Concurrency) -> Result<()> { - let mut engine = project.engine()?; - engine.set_concurrency(concurrency.concurrency); - let (run, m) = open_run(&engine, run_ref, Mode::Offline, "judge")?; +pub fn judge(a: &PhaseArgs) -> Result<()> { + let mut engine = a.project.engine()?; + engine.set_concurrency(a.concurrency); + let (run, m) = open_run(&engine, &a.run, Mode::Offline, "judge")?; engine.check_credentials(&m.datasets, &[Phase::Judge])?; - let summary = judge_run(&mut engine, &run, &m)?; - fail_on(summary) + fail_on(judge_run(&mut engine, &run, &m)?) } /// Seeds, collects and judges, then tears down uncached seeds. -pub fn run( - scope: &Scope, - sel: &Select, - shard: &ShardArgs, - run_args: &JudgedRunArgs, - concurrency: &Concurrency, - keep: &KeepSeeds, -) -> Result<()> { - let mut engine = scope.project.engine()?; - engine.set_concurrency(concurrency.concurrency); - let found = scope.discover_offline(&mut engine)?; - let (run, m) = start_run( - &mut engine, - &found, - sel.selection(Some(shard)), - run_args, - &[Phase::Seed, Phase::Collect, Phase::Judge], - )?; - let seeds = seed_run(&mut engine, &run, &m)?; - - let result = (|| { - report::phase("collect"); - engine.collect(&run, &m, &seeds)?; - judge_run(&mut engine, &run, &m) - })(); - if !keep.keep_seeds { - let _ = teardown_uncached(&mut engine, &seeds); - } - fail_on(result?) +pub fn run(a: &RunArgs) -> Result<()> { + let mut engine = a.scope.project.engine()?; + engine.set_concurrency(a.concurrency); + let found = a.scope.discover(&mut engine, Some(Mode::Offline))?; + let selection = a.select.selection(Some(&a.shard)); + let (run, m) = + start_run(&mut engine, &found, selection, &a.run_flags, &a.judge_args, ALL_PHASES)?; + fail_on(seed_collect_judge(&mut engine, &run, &m, a.keep_seeds)?) } /// Prints the most shards any selected dataset plans, for CI to fan out. -pub fn shards(scope: &Scope, sel: &Select) -> Result<()> { - let mut engine = scope.project.engine()?; - let found = scope.discover_offline(&mut engine)?; - let datasets = select(&found, &sel.selection(None))?; +pub fn shards(a: &ListArgs) -> Result<()> { + let mut engine = a.scope.project.engine()?; + let found = a.scope.discover(&mut engine, Some(Mode::Offline))?; let mut most = 1; - for d in &datasets { - let sharding = found - .iter() - .find(|f| f.name == d.name) - .and_then(|f| f.offline.as_ref()) - .map(|o| o.shard_config) - .unwrap_or_default(); - let count = sharding.shard_count(d.cases.len()); + for d in select(&found, &a.select.selection(None))? { + let config = + found.iter().find(|f| f.config.name == d.name).and_then(|f| f.config.offline.as_ref()); + let count = config.map(|o| o.shard_config).unwrap_or_default().shard_count(d.cases.len()); info!("{:<24} {} cases -> {count} shards", d.name, d.cases.len()); most = most.max(count); } @@ -120,35 +92,63 @@ pub fn shards(scope: &Scope, sel: &Select) -> Result<()> { Ok(()) } -/// Tears down the cached seeds no case uses anymore, or every one with `all`. -pub fn prune(project: &Project, all: bool) -> Result<()> { - let mut engine = project.engine()?; - let used = if all { +/// Tears down the cached seeds no case uses anymore, or every one with --all. +pub fn prune(a: &PruneArgs) -> Result<()> { + let mut engine = a.project.engine()?; + let used = if a.all { None } else { // Check every dataset, not just those under -C, since a seed is only // unused if no case anywhere needs it. report::phase("discover"); - let datasets = engine.config().offline.datasets.clone(); - let found = engine.discover(&datasets, &[])?; - let used: HashSet = found - .iter() - .flat_map(|d| d.offline.iter()) - .flat_map(|o| { - (o.cases.iter()) - .flat_map(|c| &c.seeds) - .filter(|s| s.cache) - .map(|s| seed_id(&o.runtime, s)) - }) - .collect(); + let offline: Vec<_> = + engine.config().datasets.iter().filter_map(|d| d.only(Some(Mode::Offline))).collect(); + let mut used = HashSet::new(); + for d in engine.discover(&offline)? { + for seed in d.cases.iter().flat_map(|c| &c.seeds).filter(|s| s.cache) { + used.insert(seed_id(&d.config.runtime, seed)); + } + } Some(used) }; report::phase("prune"); let removed = engine.prune(used.as_ref())?; - info!( - "tore down {removed} {}cached {}", - if all { "" } else { "unused " }, - if removed == 1 { "seed" } else { "seeds" } - ); + let unused = if a.all { "" } else { "unused " }; + info!("tore down {removed} {unused}cached {}", report::plural(removed, "seed", "seeds")); Ok(()) } + +/// Picks the cases, has each dataset's SDK validate --args, and checks the +/// credentials the run's phases need, all before the run is created so +/// neither leaves anything behind. Then creates the run. +fn start_run( + engine: &mut Engine, + found: &[Discovered], + selection: Selection, + run_flags: &RunFlags, + judge_args: &Option, + phases: &[Phase], +) -> Result<(Run, Manifest)> { + let mut datasets = select(found, &selection)?; + for f in found { + let kept = datasets.iter().find(|d| d.name == f.config.name).map_or(0, |d| d.cases.len()); + info!("{:<24} {kept}/{} cases {}", f.config.name, f.cases.len(), f.config.file); + } + let judge_args = judge_args.clone().unwrap_or_default(); + check_judge_args(&judge_args, datasets.iter().flat_map(|d| d.used_judges()))?; + let args = run_flags.args.clone().unwrap_or_default(); + for d in &mut datasets { + d.judge_args = judge_args.clone(); + engine.validate_args(d, &args)?; + } + engine.check_credentials(&datasets, phases)?; + + let m = Manifest { + variant: run_flags.variant.clone(), + metadata: run_flags.meta.iter().cloned().collect(), + shard: selection.shard, + datasets, + ..Default::default() + }; + create_run(engine, m) +} diff --git a/core/src/commands/online.rs b/core/src/commands/online.rs index c62492b..34a2e3a 100644 --- a/core/src/commands/online.rs +++ b/core/src/commands/online.rs @@ -1,46 +1,37 @@ +//! `eac online`: score what the system already did in production. + use anyhow::{bail, Context, Result}; use chrono::{DateTime, SecondsFormat, Utc}; -use super::runs::{check_judge_args, judge_run, new_manifest, open_run}; -use crate::cli::{ - Concurrency, JudgeArgs, JudgedRunArgs, Project, RunArgs, RunRef, Scope, WindowArgs, -}; -use crate::eac::{report, Dataset, Discovered, Engine, Manifest, Phase, Run, Window}; +use super::runs::{check_judge_args, create_run, judge_run, open_run}; +use crate::cli::{OnlineCollectArgs, OnlineJudgeArgs, OnlineRunArgs, RunFlags, Scope, WindowFlags}; +use crate::eac::{Dataset, Engine, Manifest, Phase, Run, Window}; +use crate::report::{self, join_or_none}; use crate::schema::{Mode, Object}; -/// Collects production records from the window into a new run, printing its +/// Collects production runs from the window into a new run, printing its /// id on stdout so CI can pass it to `eac online judge`. -pub fn online_collect(scope: &Scope, window: &WindowArgs, run_args: &RunArgs) -> Result<()> { - let window = parse_window(window)?; - let mut engine = scope.project.engine()?; - let found = scope.discover_online(&mut engine)?; - let mut datasets = online_datasets(&found)?; - let args = run_args.args.clone().unwrap_or_default(); - for d in &mut datasets { - engine.validate_args(d, Mode::Online, &args)?; - } +pub fn collect(a: &OnlineCollectArgs) -> Result<()> { + let window = parse_window(&a.window)?; + let mut engine = a.scope.project.engine()?; + let mut datasets = online_datasets(&mut engine, &a.scope)?; + validate_args(&mut engine, &mut datasets, &a.run_flags)?; engine.check_credentials(&datasets, &[Phase::Collect])?; - let (run, _) = collect_run(&mut engine, datasets, window, run_args)?; + let (run, _) = collect_run(&mut engine, datasets, window, &a.run_flags)?; info!("run {}", run.id); println!("{}", run.id); Ok(()) } -/// Scores a collected run's records with the judges picked, or else the ones +/// Scores a collected run's cases with the judges picked, or else the ones /// it was last judged with. Online runs report each judge's mean and never /// fail. -pub fn online_judge( - project: &Project, - run_ref: &RunRef, - judges: &[String], - judge_args: &JudgeArgs, - concurrency: &Concurrency, -) -> Result<()> { - let mut engine = project.engine()?; - engine.set_concurrency(concurrency.concurrency); - let (run, mut m) = open_run(&engine, run_ref, Mode::Online, "judge")?; - // Every dataset in an online run is judged with the same judges. - let (judges, args) = if judges.is_empty() { +pub fn judge(a: &OnlineJudgeArgs) -> Result<()> { + let mut engine = a.project.engine()?; + engine.set_concurrency(a.concurrency); + let (run, mut m) = open_run(&engine, &a.run, Mode::Online, "judge")?; + let (judges, judge_args) = if a.judges.is_empty() { + // Every dataset in an online run is judged with the same judges. let (last, last_args) = (m.datasets.first()) .map(|d| (d.judges.clone(), d.judge_args.clone())) .unwrap_or_default(); @@ -50,15 +41,14 @@ pub fn online_judge( run.id ); } - (last, judge_args.judge_args.clone().unwrap_or(last_args)) + (last, a.judge_args.clone().unwrap_or(last_args)) } else { - let args = judge_args.judge_args.clone().unwrap_or_default(); - (judges.to_vec(), args) + (a.judges.clone(), a.judge_args.clone().unwrap_or_default()) }; - pick_judges(&mut m.datasets, &judges, &args)?; + pick_judges(&mut m.datasets, &judges, &judge_args)?; for d in &mut m.datasets { let args = d.args.clone(); - engine.validate_args(d, Mode::Online, &args)?; + engine.validate_args(d, &args)?; } // Recorded, so results and a later re-judge use these judges. run.write_manifest(&m)?; @@ -67,44 +57,33 @@ pub fn online_judge( Ok(()) } -/// Collects production records from the window and judges them, checking the +/// Collects production runs from the window and judges them, checking the /// judges before fetching anything. -pub fn online_run( - scope: &Scope, - judges: &[String], - window: &WindowArgs, - run_args: &JudgedRunArgs, - concurrency: &Concurrency, -) -> Result<()> { - let window = parse_window(window)?; - if judges.is_empty() { +pub fn run(a: &OnlineRunArgs) -> Result<()> { + let window = parse_window(&a.window)?; + if a.judges.is_empty() { bail!("--judge is required; 'eac list' shows each dataset's online judges"); } - let mut engine = scope.project.engine()?; - engine.set_concurrency(concurrency.concurrency); - let found = scope.discover_online(&mut engine)?; - let mut datasets = online_datasets(&found)?; - let judge_args = run_args.judge.judge_args.clone().unwrap_or_default(); - pick_judges(&mut datasets, judges, &judge_args)?; - let args = run_args.run.args.clone().unwrap_or_default(); - for d in &mut datasets { - engine.validate_args(d, Mode::Online, &args)?; - } + let mut engine = a.scope.project.engine()?; + engine.set_concurrency(a.concurrency); + let mut datasets = online_datasets(&mut engine, &a.scope)?; + pick_judges(&mut datasets, &a.judges, &a.judge_args.clone().unwrap_or_default())?; + validate_args(&mut engine, &mut datasets, &a.run_flags)?; engine.check_credentials(&datasets, &[Phase::Collect, Phase::Judge])?; - let (run, m) = collect_run(&mut engine, datasets, window, &run_args.run)?; + let (run, m) = collect_run(&mut engine, datasets, window, &a.run_flags)?; judge_run(&mut engine, &run, &m)?; Ok(()) } /// The window the flags give, ending now unless --window-end says otherwise. -fn parse_window(window: &WindowArgs) -> Result { - if window.since.is_zero() { +fn parse_window(flags: &WindowFlags) -> Result { + if flags.since.is_zero() { bail!("--since must be positive, e.g. 30m, 1h, 24h"); } - if window.limit < 1 { - bail!("--limit must be at least 1, got {}", window.limit); + if flags.limit < 1 { + bail!("--limit must be at least 1, got {}", flags.limit); } - let end = match &window.window_end { + let end = match &flags.window_end { Some(time) => DateTime::parse_from_rfc3339(time) .with_context(|| { format!("--window-end {time:?} isn't an RFC 3339 time, e.g. 2026-10-31T12:00:00Z") @@ -112,32 +91,33 @@ fn parse_window(window: &WindowArgs) -> Result { .with_timezone(&Utc), None => Utc::now(), }; - let start = chrono::Duration::from_std(window.since) - .ok() + let start = (chrono::Duration::from_std(flags.since).ok()) .and_then(|d| end.checked_sub_signed(d)) .context("--since is too far back")?; let rfc3339 = |t: DateTime| t.to_rfc3339_opts(SecondsFormat::Secs, true); - Ok(Window { - since: rfc3339(start), - until: rfc3339(end), - limit: window.limit as usize, - }) + Ok(Window { since: rfc3339(start), until: rfc3339(end), limit: flags.limit as usize }) } -/// The found datasets that run online, as a new run's datasets. -fn online_datasets(found: &[Discovered]) -> Result> { - let mut datasets = Vec::new(); - for d in found { - if d.online.is_none() { - detail!("{} has no online runner, skipping", d.name); - continue; - } - datasets.push(d.to_dataset(Mode::Online, vec![])); - } - if datasets.is_empty() { +/// The selected datasets that run online, as a new run's datasets. +fn online_datasets(engine: &mut Engine, scope: &Scope) -> Result> { + let found = scope.discover(engine, Some(Mode::Online))?; + if found.is_empty() { bail!("no selected dataset has an online runner"); } - Ok(datasets) + Ok(found.iter().map(|d| d.to_dataset(Mode::Online, vec![])).collect()) +} + +/// Has each dataset's SDK check --args, filling in their defaults. +fn validate_args( + engine: &mut Engine, + datasets: &mut [Dataset], + run_flags: &RunFlags, +) -> Result<()> { + let args = run_flags.args.clone().unwrap_or_default(); + for d in datasets { + engine.validate_args(d, &args)?; + } + Ok(()) } /// Sets the judges every dataset scores with, once each, after checking that @@ -152,16 +132,14 @@ fn pick_judges(datasets: &mut [Dataset], judges: &[String], judge_args: &Object) check_judge_args(judge_args, &picked)?; for d in datasets { let available: Vec<&str> = d.code.judges.iter().map(|j| j.name.as_str()).collect(); - let unknown: Vec<&str> = (picked.iter()) - .map(String::as_str) - .filter(|j| !available.contains(j)) - .collect(); + let unknown: Vec<&str> = + picked.iter().map(String::as_str).filter(|j| !available.contains(j)).collect(); if !unknown.is_empty() { bail!( "dataset {} has no online judge {}; available: {}", d.name, unknown.join(", "), - available.join(", ") + join_or_none(available) ); } d.judges = picked.clone(); @@ -170,29 +148,25 @@ fn pick_judges(datasets: &mut [Dataset], judges: &[String], judge_args: &Object) Ok(()) } -/// Fetches each dataset's records in the window into a new run. +/// Collects each dataset's production runs in the window into a new run. fn collect_run( engine: &mut Engine, mut datasets: Vec, window: Window, - run_args: &RunArgs, + run_flags: &RunFlags, ) -> Result<(Run, Manifest)> { report::phase("collect"); - detail!( - "{} -> {}, up to {} per dataset", - window.since, - window.until, - window.limit - ); - let outputs = engine.fetch(&mut datasets, &window)?; - let run = Run::create(&engine.config().artifacts)?; + detail!("{} -> {}, up to {} per dataset", window.since, window.until, window.limit); + let outputs = engine.collect_online(&mut datasets, &window)?; let m = Manifest { online: true, window: Some(window), + variant: run_flags.variant.clone(), + metadata: run_flags.meta.iter().cloned().collect(), datasets, - ..new_manifest(engine, &run, run_args) + ..Default::default() }; - run.write_manifest(&m)?; + let (run, m) = create_run(engine, m)?; for out in &outputs { run.write_output(out)?; } diff --git a/core/src/commands/runs.rs b/core/src/commands/runs.rs index ed2bb89..a2d1fdd 100644 --- a/core/src/commands/runs.rs +++ b/core/src/commands/runs.rs @@ -1,15 +1,13 @@ -//! Run steps shared by the commands, and how a run's outcome maps to the exit code. +//! Steps that several commands share: creating, opening, seeding and judging +//! runs. -use std::collections::HashSet; +use std::collections::BTreeSet; use anyhow::{bail, Result}; use chrono::Utc; -use crate::cli::{JudgedRunArgs, RunArgs, RunRef}; -use crate::eac::{ - detect_source, report, select, Discovered, Engine, Manifest, Phase, Run, Seeds, Selection, - Summary, -}; +use crate::eac::{detect_source, Engine, Manifest, Run, Seeds, Summary}; +use crate::report::{self, join_or_none}; use crate::schema::{Mode, Object}; /// The evals ran but did not all pass. @@ -27,66 +25,38 @@ impl std::fmt::Display for FailedRun { impl std::error::Error for FailedRun {} -/// Has each dataset's SDK validate --args, and checks the credentials the -/// run's phases need, before the run is created, so neither leaves anything -/// behind. -pub fn start_run( - engine: &mut Engine, - found: &[Discovered], - selection: Selection, - run_args: &JudgedRunArgs, - phases: &[Phase], -) -> Result<(Run, Manifest)> { - let mut datasets = select(found, &selection)?; - for f in found { - let Some(offline) = &f.offline else { - detail!("{} has no offline runner, skipping", f.name); - continue; - }; - let kept = datasets - .iter() - .find(|d| d.name == f.name) - .map_or(0, |d| d.cases.len()); - info!( - "{:<24} {kept}/{} cases {}", - f.name, - offline.cases.len(), - f.file - ); - } - let args = run_args.run.args.clone().unwrap_or_default(); - let judge_args = run_args.judge.judge_args.clone().unwrap_or_default(); - check_judge_args( - &judge_args, - datasets - .iter() - .flat_map(|d| d.cases.iter().flat_map(|c| &c.judges)), - )?; - for d in &mut datasets { - d.judge_args = judge_args.clone(); - engine.validate_args(d, Mode::Offline, &args)?; +/// Offline runs fail on any failure or error. Online runs never fail. +pub fn fail_on(summary: Summary) -> Result<()> { + if !summary.online && (summary.failed > 0 || summary.errors > 0) { + return Err(FailedRun { failed: summary.failed, errors: summary.errors }.into()); } - engine.check_credentials(&datasets, phases)?; + Ok(()) +} +/// Creates a run from m, filling in its id, time and source, and writes its +/// manifest. +pub fn create_run(engine: &Engine, mut m: Manifest) -> Result<(Run, Manifest)> { let run = Run::create(&engine.config().artifacts)?; - let m = Manifest { - shard: selection.shard, - datasets, - ..new_manifest(engine, &run, &run_args.run) - }; + m.id = run.id.clone(); + m.created_at = Utc::now(); + m.source = detect_source(&engine.config().root); run.write_manifest(&m)?; Ok((run, m)) } -pub fn new_manifest(engine: &Engine, run: &Run, run_args: &RunArgs) -> Manifest { - Manifest { - id: run.id.clone(), - created_at: Utc::now(), - variant: run_args.variant.clone(), - metadata: run_args.meta.iter().cloned().collect(), - source: detect_source(&engine.config().root), - ..Default::default() +/// Opens an existing run for a command of mode, which only works on runs of +/// that mode. +pub fn open_run(engine: &Engine, id: &str, mode: Mode, command: &str) -> Result<(Run, Manifest)> { + let run = Run::open(&engine.config().artifacts, id)?; + let m = run.read_manifest()?; + if m.mode() != mode { + let (theirs, ours) = (m.mode().as_str(), mode.as_str()); + bail!( + "run {} is an {theirs} run, and 'eac {ours} {command}' only works on {ours} runs", + run.id + ); } + Ok((run, m)) } pub fn seed_run(engine: &mut Engine, run: &Run, m: &Manifest) -> Result { @@ -96,6 +66,23 @@ pub fn seed_run(engine: &mut Engine, run: &Run, m: &Manifest) -> Result { Ok(seeds) } +/// Seeds, collects and judges a new run, then tears down its uncached seeds +/// unless they're kept. +pub fn seed_collect_judge( + engine: &mut Engine, + run: &Run, + m: &Manifest, + keep_seeds: bool, +) -> Result { + let seeds = seed_run(engine, run, m)?; + report::phase("collect"); + let summary = engine.collect(run, m, &seeds).and_then(|()| judge_run(engine, run, m)); + if !keep_seeds { + let _ = teardown_uncached(engine, &seeds); + } + summary +} + /// Quiet when every seed is cached. pub fn teardown_uncached(engine: &mut Engine, seeds: &Seeds) -> Result<()> { let uncached: Vec<_> = seeds.seeds.values().filter(|e| !e.cached).collect(); @@ -124,72 +111,15 @@ pub fn check_judge_args<'a>( judge_args: &Object, judges: impl IntoIterator, ) -> Result<()> { - let used: HashSet<&str> = judges.into_iter().map(String::as_str).collect(); - let unknown: Vec<&str> = judge_args - .keys() - .map(String::as_str) - .filter(|name| !used.contains(name)) - .collect(); + let used: BTreeSet<&str> = judges.into_iter().map(String::as_str).collect(); + let unknown: Vec<&str> = + judge_args.keys().map(String::as_str).filter(|name| !used.contains(name)).collect(); if !unknown.is_empty() { - let mut used: Vec<&str> = used.into_iter().collect(); - used.sort_unstable(); - let used = if used.is_empty() { - "(none)".to_string() - } else { - used.join(", ") - }; - bail!( - "--judge-args names {}, but no judge in this run is called that; its judges: {used}", - unknown.join(", ") - ); - } - Ok(()) -} - -/// Opens an existing run for a command of mode, which only works on runs of -/// that mode. -pub fn open_run( - engine: &Engine, - run_ref: &RunRef, - mode: Mode, - command: &str, -) -> Result<(Run, Manifest)> { - let (run, m) = run_ref.open(engine)?; - if mode_of(&m) != mode { bail!( - "run {} is an {} run, and 'eac {} {command}' only works on {} runs", - run.id, - mode_name(mode_of(&m)), - mode_name(mode), - mode_name(mode) + "--judge-args names {}, but no judge in this run is called that; its judges: {}", + unknown.join(", "), + join_or_none(used) ); } - Ok((run, m)) -} - -pub fn mode_name(mode: Mode) -> &'static str { - match mode { - Mode::Offline => "offline", - Mode::Online => "online", - } -} - -pub fn mode_of(m: &Manifest) -> Mode { - if m.online { - Mode::Online - } else { - Mode::Offline - } -} - -/// Offline runs fail on any failure or error. Online runs never fail. -pub fn fail_on(summary: Summary) -> Result<()> { - if !summary.online && (summary.failed > 0 || summary.errors > 0) { - return Err(FailedRun { - failed: summary.failed, - errors: summary.errors, - } - .into()); - } Ok(()) } diff --git a/core/src/commands/schema.rs b/core/src/commands/schema.rs deleted file mode 100644 index d2fa14f..0000000 --- a/core/src/commands/schema.rs +++ /dev/null @@ -1,10 +0,0 @@ -use anyhow::Result; - -/// Prints the protocol's JSON Schema, which the SDKs' types are generated from. -pub fn schema() -> Result<()> { - println!( - "{}", - serde_json::to_string_pretty(&crate::schema::document())? - ); - Ok(()) -} diff --git a/core/src/eac/config/dataset_yml.rs b/core/src/eac/config/dataset_yml.rs index 7edd4dc..32bf01b 100644 --- a/core/src/eac/config/dataset_yml.rs +++ b/core/src/eac/config/dataset_yml.rs @@ -1,92 +1,74 @@ -//! Finding and checking dataset.yml files. - use std::collections::HashSet; -use std::fs; -use std::path::{Path, PathBuf}; +use std::path::Path; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; -use super::paths::resolve_ref; -use super::runtime::{check_runtime, entry_runtime}; -use super::loader::{read_yaml, Loader}; -use super::project::DATASET_FILE; +use super::paths::{relative, resolve_ref}; +use super::runtime::check_runtime; +use super::{read_yaml, DATASET_FILE}; use crate::schema::{nullable, DatasetRef, JudgeRef, Mode, Object}; -/// Never searched for dataset files. Hidden directories are skipped too. -const SKIP_DIRS: &[&str] = &[ - "node_modules", - "__pycache__", - "site-packages", - "venv", - "target", - "dist", - "build", -]; - -/// A dataset.yml's `offline` section, plus the file's top-level fields. -#[derive(Clone, Debug)] -pub struct OfflineDataset { +/// A dataset.yml: a dataset's code and how it runs offline, online or both. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DatasetConfig { pub name: String, /// The dataset.yml, relative to root. + #[serde(skip)] pub file: String, /// The production agent it exercises, for trace attribution. + #[serde(default)] pub agent: Option, /// The SDK worker that runs it, one of RUNTIMES. pub runtime: String, - /// The OfflineRunner reference, module:attr or ./file.py:attr relative - /// to root. + #[serde(default)] + pub offline: Option, + #[serde(default)] + pub online: Option, +} + +/// A dataset.yml's `offline` section. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OfflineConfig { + /// The OfflineRunner, as a code reference. Code references are + /// module:attr or ./file.py:attr, made relative to root when loaded. pub runner: String, - /// The sequence of Cases, as a reference. + /// The sequence of Cases, as a code reference. pub cases: String, + #[serde(default)] pub shard_config: Sharding, /// How many cases run at once, each on its own worker. + #[serde(default = "default_concurrency")] pub concurrency: usize, + #[serde(default)] pub comparisons: Vec, } /// A dataset.yml's `online` section. -#[derive(Clone, Debug)] -pub struct OnlineDataset { - pub name: String, - pub file: String, - pub agent: Option, - pub runtime: String, - /// The OnlineRunner, as a reference. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OnlineConfig { + /// The OnlineRunner, as a code reference. pub runner: String, - /// What `--judge` picks from. The dataset's own judges come first, then - /// eac.yml's online.judges that none of them shadow by name. - pub judges: Vec, + /// What `--judge` picks from. + #[serde(default)] + pub judges: Vec, /// How many records are judged at once, each on its own worker. + #[serde(default = "default_concurrency")] pub concurrency: usize, } -impl OfflineDataset { - /// What workers import the dataset from. - pub fn code(&self) -> DatasetRef { - DatasetRef { - name: self.name.clone(), - mode: Mode::Offline, - runner: self.runner.clone(), - cases: Some(self.cases.clone()), - judges: vec![], - } - } -} - -impl OnlineDataset { - pub fn code(&self) -> DatasetRef { - DatasetRef { - name: self.name.clone(), - mode: Mode::Online, - runner: self.runner.clone(), - cases: None, - judges: self.judges.clone(), - } - } +/// An online judge. It runs in the dataset's worker. +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct JudgeEntry { + /// What --judge and --judge-args name it by. + pub name: String, + pub path: String, } -/// Runs a dataset's cases once per arm, each with different args. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Comparison { @@ -99,20 +81,14 @@ pub struct Comparison { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub judges: Vec, #[serde(default, deserialize_with = "nullable")] - pub arms: Vec, + pub arms: Vec, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct Arm { +pub struct ComparisonArm { pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub sha: Option, - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Object::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Object::is_empty")] pub args: Object, } @@ -127,211 +103,108 @@ pub struct Sharding { impl Default for Sharding { fn default() -> Self { - Sharding { - cases_per_shard: 20, - max_shards: 8, - } + Sharding { cases_per_shard: 20, max_shards: 8 } } } impl Sharding { pub fn shard_count(&self, cases: usize) -> usize { - cases - .div_ceil(self.cases_per_shard.max(1)) - .clamp(1, self.max_shards.max(1)) + cases.div_ceil(self.cases_per_shard.max(1)).clamp(1, self.max_shards.max(1)) } } -/// A dataset.yml as written. -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct DatasetFile { - name: String, - #[serde(default)] - agent: Option, - runtime: String, - #[serde(default)] - offline: Option, - #[serde(default)] - online: Option, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct DatasetOfflineFile { - runner: String, - cases: String, - #[serde(default)] - shard_config: Sharding, - #[serde(default)] - concurrency: Option, - #[serde(default)] - comparisons: Vec, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct DatasetOnlineFile { - runner: String, - #[serde(default)] - judges: Vec, - #[serde(default)] - concurrency: Option, -} - -/// An online judge entry, in a dataset.yml or eac.yml's online.judges. -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -pub struct JudgeFile { - /// What --judge and --judge-args name it by. - name: String, - path: String, - /// Required in eac.yml. In a dataset.yml it defaults to the dataset's runtime. - #[serde(default)] - runtime: Option, -} - -impl Loader<'_> { - /// Checks a dataset.yml into its offline and online datasets. `rel` is its - /// path relative to root, and ./file references are relative to its folder. - pub fn dataset( - &self, - path: &Path, - rel: &str, - shared_judges: &[(JudgeRef, String)], - ) -> Result<(Option, Option)> { - let Some(d) = read_yaml::(path)? else { +impl DatasetConfig { + /// Reads and checks the dataset.yml at path. Its ./file references are + /// relative to its folder, and are made relative to root, where workers + /// run. + pub fn load(root: &Path, path: &Path) -> Result { + let Some(mut d) = read_yaml::(path)? else { bail!("{DATASET_FILE} is empty; it needs a name, a runtime and an offline or online section"); }; - let dir = path.parent().expect("a dataset file has a folder"); + d.file = relative(root, path); check_name(&d.name)?; check_runtime(&d.runtime).context("runtime")?; if d.offline.is_none() && d.online.is_none() { bail!("dataset {} needs an offline or online section", d.name); } - let offline = match d.offline { - None => None, - Some(o) => { - let mut comparisons = HashSet::new(); - for c in &o.comparisons { - if !comparisons.insert(&c.name) { - bail!("offline: more than one comparison is named {:?}", c.name); - } - } - Some(OfflineDataset { - name: d.name.clone(), - file: rel.to_string(), - agent: d.agent.clone(), - runtime: d.runtime.clone(), - runner: resolve_ref(self.root, dir, &o.runner).context("offline.runner")?, - cases: resolve_ref(self.root, dir, &o.cases).context("offline.cases")?, - shard_config: o.shard_config, - concurrency: concurrency(o.concurrency).context("offline.concurrency")?, - comparisons: o.comparisons, - }) - } + let dir = path.parent().expect("a dataset file has a folder"); + let resolve = |reference: &mut String, what: &str| -> Result<()> { + *reference = resolve_ref(root, dir, reference).context(what.to_string())?; + Ok(()) }; - - let online = match d.online { - None => None, - Some(o) => { - let own = self - .judges(o.judges, dir, Some(&d.runtime)) - .context("online.judges")?; - // A dataset's own judges come first and replace shared ones of - // the same name. - let mut judges: Vec = own.iter().map(|(j, _)| j.clone()).collect(); - for (judge, runtime) in shared_judges { - if own.iter().any(|(j, _)| j.name == judge.name) { - continue; - } - if *runtime != d.runtime { - bail!( - "eac.yml's online.judges {} runs in {runtime}, but judges run in their dataset's worker, which is {}", - judge.name, - d.runtime - ); - } - judges.push(judge.clone()); - } - if judges.is_empty() { - bail!("online: no judges; give it judges, or add online.judges to eac.yml"); - } - Some(OnlineDataset { - name: d.name.clone(), - file: rel.to_string(), - agent: d.agent.clone(), - runtime: d.runtime.clone(), - runner: resolve_ref(self.root, dir, &o.runner).context("online.runner")?, - judges, - concurrency: concurrency(o.concurrency).context("online.concurrency")?, - }) + if let Some(o) = &mut d.offline { + resolve(&mut o.runner, "offline.runner")?; + resolve(&mut o.cases, "offline.cases")?; + if o.concurrency == 0 { + bail!("offline.concurrency: must be at least 1"); } - }; - Ok((offline, online)) + if let Some(name) = first_duplicate(o.comparisons.iter().map(|c| &c.name)) { + bail!("offline: more than one comparison is named {name:?}"); + } + } + if let Some(o) = &mut d.online { + resolve(&mut o.runner, "online.runner")?; + if let Some(name) = first_duplicate(o.judges.iter().map(|j| &j.name)) { + bail!("online.judges: more than one judge is named {name:?}"); + } + for j in &mut o.judges { + resolve(&mut j.path, &format!("online.judges: judge {}", j.name))?; + } + if o.judges.is_empty() { + bail!("online: no judges; give it at least one under online.judges"); + } + if o.concurrency == 0 { + bail!("online.concurrency: must be at least 1"); + } + } + Ok(d) } - /// Checks judge entries, pairing each with its runtime. `dir` is the base - /// for ./file references. - pub fn judges( - &self, - entries: Vec, - dir: &Path, - dataset_runtime: Option<&str>, - ) -> Result> { - let mut names = HashSet::new(); - let mut out = Vec::new(); - for j in entries { - if !names.insert(j.name.clone()) { - bail!("more than one judge is named {:?}", j.name); - } - let runtime = entry_runtime(j.runtime, dataset_runtime) - .with_context(|| format!("judge {}", j.name))?; - let path = - resolve_ref(self.root, dir, &j.path).with_context(|| format!("judge {}", j.name))?; - out.push((JudgeRef { name: j.name, path }, runtime)); + /// A copy with only mode's section, or None if it doesn't have one. A + /// mode of None keeps both. + pub fn only(&self, mode: Option) -> Option { + let mut d = self.clone(); + match mode { + Some(Mode::Offline) => d.online = None, + Some(Mode::Online) => d.offline = None, + None => {} } - Ok(out) + (d.offline.is_some() || d.online.is_some()).then_some(d) } -} -/// Every dataset.yml under root, sorted. Skips hidden directories, SKIP_DIRS -/// and the `skip` paths. -pub fn find_dataset_files(root: &Path, skip: &[PathBuf]) -> Result> { - let mut found = Vec::new(); - let mut dirs = vec![root.to_path_buf()]; - while let Some(dir) = dirs.pop() { - let entries = fs::read_dir(&dir).with_context(|| format!("searching {}", dir.display()))?; - for entry in entries { - let entry = entry?; - let path = entry.path(); - if skip.contains(&path) { - continue; + /// Where workers import the dataset's code from for mode. Panics if it + /// has no section for mode. + pub fn code(&self, mode: Mode) -> DatasetRef { + let (runner, cases, judges) = match mode { + Mode::Offline => { + let o = self.offline.as_ref().expect("an offline dataset"); + (o.runner.clone(), Some(o.cases.clone()), vec![]) } - let name = entry.file_name(); - let name = name.to_string_lossy(); - // Symlinks aren't followed, so the search can't loop. - let kind = entry.file_type()?; - if kind.is_dir() { - if !name.starts_with('.') && !SKIP_DIRS.contains(&name.as_ref()) { - dirs.push(path); - } - } else if kind.is_file() && name == DATASET_FILE { - found.push(path); + Mode::Online => { + let o = self.online.as_ref().expect("an online dataset"); + let judges = o + .judges + .iter() + .map(|j| JudgeRef { name: j.name.clone(), path: j.path.clone() }); + (o.runner.clone(), None, judges.collect()) } + }; + DatasetRef { name: self.name.clone(), mode, runner, cases, judges } + } + + /// The configured concurrency for mode, if it has a section for it. + pub fn concurrency(&self, mode: Mode) -> Option { + match mode { + Mode::Offline => self.offline.as_ref().map(|o| o.concurrency), + Mode::Online => self.online.as_ref().map(|o| o.concurrency), } } - found.sort(); - Ok(found) } -/// A section's concurrency, defaulting to 1. -fn concurrency(n: Option) -> Result { - match n { - Some(0) => bail!("must be at least 1"), - n => Ok(n.unwrap_or(1)), - } +/// A section that doesn't say runs one case at a time. +fn default_concurrency() -> usize { + 1 } /// Dataset names key run files, so they stay plain. @@ -342,3 +215,8 @@ fn check_name(name: &str) -> Result<()> { } Ok(()) } + +fn first_duplicate<'a>(names: impl IntoIterator) -> Option<&'a String> { + let mut seen = HashSet::new(); + names.into_iter().find(|name| !seen.insert(*name)) +} diff --git a/core/src/eac/config/eac_yml.rs b/core/src/eac/config/eac_yml.rs deleted file mode 100644 index 0587550..0000000 --- a/core/src/eac/config/eac_yml.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! eac.yml as written. `Config::load` checks it. - -use std::collections::BTreeMap; - -use serde::Deserialize; - -use super::dataset_yml::JudgeFile; -use super::runtime::Runtime; - -/// eac.yml: what every dataset shares. -#[derive(Default, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct File { - pub artifacts: Option, - /// Folders and files not searched for dataset.yml, e.g. another tool's. - #[serde(default)] - pub exclude: Vec, - #[serde(default)] - pub runtimes: BTreeMap, - #[serde(default)] - pub online: OnlineFile, -} - -#[derive(Default, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct OnlineFile { - /// Judges every online dataset offers. - #[serde(default)] - pub judges: Vec, -} diff --git a/core/src/eac/config/loader.rs b/core/src/eac/config/loader.rs deleted file mode 100644 index 02e0681..0000000 --- a/core/src/eac/config/loader.rs +++ /dev/null @@ -1,21 +0,0 @@ -use std::fs; -use std::path::Path; - -use anyhow::{Context, Result}; - -/// Checks parsed eac.yml and dataset.yml contents. Each config module adds -/// its own methods in an `impl Loader` block. -pub struct Loader<'a> { - pub root: &'a Path, -} - -/// None if the file is empty. -pub fn read_yaml(path: &Path) -> Result> { - let raw = fs::read_to_string(path).with_context(|| path.display().to_string())?; - if raw.trim().is_empty() { - return Ok(None); - } - serde_yaml::from_str(&raw) - .map(Some) - .with_context(|| path.display().to_string()) -} diff --git a/core/src/eac/config/mod.rs b/core/src/eac/config/mod.rs index fa02fbf..78908e9 100644 --- a/core/src/eac/config/mod.rs +++ b/core/src/eac/config/mod.rs @@ -1,12 +1,466 @@ -//! Project config: eac.yml at the project root, plus a dataset.yml in each -//! dataset's folder. `Config::load` reads and checks them. +//! Project config: an optional eac.yml at the project root, plus a dataset.yml +//! in each dataset's folder. `Config::load` reads and checks them. mod dataset_yml; -mod eac_yml; -mod loader; mod paths; -mod project; mod runtime; -pub use dataset_yml::{Comparison, OfflineDataset, OnlineDataset, Sharding}; -pub use project::Config; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{anyhow, bail, Context, Result}; +use serde::de::DeserializeOwned; +use serde::Deserialize; + +pub use dataset_yml::{Comparison, DatasetConfig}; +use paths::clean; +use runtime::{Runtime, RUNTIMES}; + +use crate::report::join_or_none; +use crate::schema::Mode; + +/// Optional. Marks the project root, and holds settings every dataset shares. +pub const CONFIG_FILE: &str = "eac.yml"; + +/// A dataset's definition, in the folder with its code. eac finds every one +/// under the project root. +pub const DATASET_FILE: &str = "dataset.yml"; + +/// Read next to eac.yml, for the environment of the processes eac starts. The +/// real environment wins. +pub const ENV_FILE: &str = ".env"; + +/// In the artifacts directory: what logging in to credentials returned, which +/// later commands load. Its directory has a .gitignore of its own, so nothing +/// in it is committed wherever the artifacts directory is. +pub const SAVED_CREDENTIALS: &str = "credentials/saved.json"; + +/// Never searched for dataset files. Hidden directories are skipped too. +const SKIP_DIRS: &[&str] = + &["node_modules", "__pycache__", "site-packages", "venv", "target", "dist", "build"]; + +/// eac.yml as written. +#[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct EacYml { + artifacts: Option, + /// Folders and files not searched for dataset.yml, e.g. another tool's. + #[serde(default)] + exclude: Vec, + #[serde(default)] + runtimes: BTreeMap, +} + +#[derive(Clone, Debug)] +pub struct Config { + /// Where eac.yml is, or else the git repository's root. Paths resolve + /// against it, and workers run in it. + pub root: PathBuf, + pub artifacts: PathBuf, + /// The directory eac was pointed at, if below root. Commands default to + /// the datasets under it. + pub scope: Option, + pub runtimes: BTreeMap, + /// Every dataset.yml under root, in path order. + pub datasets: Vec, + /// From ENV_FILE, for the variables the environment doesn't set. + pub env_file: BTreeMap, + /// What logging in to credentials returned, from SAVED_CREDENTIALS and + /// this command. It wins over the environment and ENV_FILE, which may hold + /// stale values, since each was checked when saved. + pub credentials_env: BTreeMap, +} + +impl Config { + /// Loads the project dir is in, and the dataset.yml files under its root. + /// The root is the nearest folder up from dir with an eac.yml, else the + /// git repository's root, else dir itself. + pub fn load(dir: &Path) -> Result { + let start = clean(&std::path::absolute(dir)?); + let has = |name: &str| start.ancestors().find(|d| d.join(name).exists()); + let root = has(CONFIG_FILE).or_else(|| has(".git")).unwrap_or(&start).to_path_buf(); + + let path = root.join(CONFIG_FILE); + let at = || path.display().to_string(); + let eac_yml: EacYml = + if path.is_file() { read_yaml(&path)?.unwrap_or_default() } else { EacYml::default() }; + let artifacts = clean(&root.join(eac_yml.artifacts.as_deref().unwrap_or(".eac"))); + let mut skip = vec![artifacts.clone()]; + for p in &eac_yml.exclude { + let excluded = clean(&root.join(p)); + if !excluded.exists() { + return Err(anyhow!("exclude: {p} doesn't exist")).with_context(at); + } + skip.push(excluded); + } + if let Some(name) = eac_yml.runtimes.keys().find(|r| !RUNTIMES.contains(&r.as_str())) { + let expected = RUNTIMES.join(", "); + return Err(anyhow!("unknown runtime {name:?}; expected one of: {expected}")) + .with_context(at); + } + + let files = find_dataset_files(&root, &skip)?; + if files.is_empty() { + bail!( + "no {DATASET_FILE} found under {}; give each dataset one in its folder, e.g.\n\n \ + name: chat\n runtime: python\n offline:\n runner: ./runner.py:ChatRunner\n \ + cases: ./cases.py:CASES", + root.display() + ); + } + let mut datasets: Vec = Vec::new(); + for file in files { + let d = + DatasetConfig::load(&root, &file).with_context(|| file.display().to_string())?; + if let Some(other) = datasets.iter().find(|o| o.name == d.name) { + bail!("{} and {} both define a dataset named {:?}", other.file, d.file, d.name); + } + datasets.push(d); + } + + Ok(Config { + scope: (start != root && start.starts_with(&root)).then_some(start), + env_file: read_env_file(&root.join(ENV_FILE))?, + credentials_env: read_saved_credentials(&artifacts.join(SAVED_CREDENTIALS))?, + runtimes: eac_yml.runtimes, + root, + artifacts, + datasets, + }) + } + + /// Picks the datasets that run in mode, with only that mode's section, or + /// every dataset with both if mode is None. With no names, picks those + /// under the scope directory, or all of them if none are. + pub fn select(&self, names: &[String], mode: Option) -> Result> { + let candidates: Vec = + self.datasets.iter().filter_map(|d| d.only(mode)).collect(); + if let Some(unknown) = names.iter().find(|n| !candidates.iter().any(|d| &d.name == *n)) { + let mode = mode.map_or(String::new(), |m| format!("{} ", m.as_str())); + let mut known: Vec<&str> = candidates.iter().map(|d| d.name.as_str()).collect(); + known.sort_unstable(); + bail!("unknown {mode}dataset {unknown:?}; try one of: {}", join_or_none(known)); + } + if !names.is_empty() { + return Ok(candidates.into_iter().filter(|d| names.contains(&d.name)).collect()); + } + let in_scope: Vec = + candidates.iter().filter(|d| self.in_scope(d)).cloned().collect(); + Ok(if in_scope.is_empty() { candidates } else { in_scope }) + } + + /// Whether d's dataset.yml is under the scope directory, if there is one. + fn in_scope(&self, d: &DatasetConfig) -> bool { + self.scope.as_ref().is_none_or(|scope| self.root.join(&d.file).starts_with(scope)) + } + + /// Adds vars to the saved credentials, which later commands load, and + /// returns the file's path. The file is readable only by its owner and + /// replaced in one step, and its directory gets a .gitignore so it can't + /// be committed. + pub fn save_credentials(&self, vars: &BTreeMap) -> Result { + let path = self.artifacts.join(SAVED_CREDENTIALS); + let at = || path.display().to_string(); + let dir = path.parent().expect("saved credentials are in a directory"); + fs::create_dir_all(dir).with_context(|| dir.display().to_string())?; + let ignore = dir.join(".gitignore"); + if !ignore.exists() { + fs::write( + &ignore, + "# Written by eac. These are credentials, so none are committed.\n*\n", + ) + .with_context(|| ignore.display().to_string())?; + } + let mut saved = read_saved_credentials(&path)?; + saved.extend(vars.clone()); + let mut file = tempfile::NamedTempFile::new_in(dir).with_context(at)?; + serde_json::to_writer_pretty(&mut file, &saved).with_context(at)?; + file.persist(&path).map_err(|e| e.error).with_context(at)?; + Ok(path) + } +} + +/// Parses a YAML file, or returns None if it's empty. +fn read_yaml(path: &Path) -> Result> { + let at = || path.display().to_string(); + let raw = fs::read_to_string(path).with_context(at)?; + if raw.trim().is_empty() { + return Ok(None); + } + serde_yaml::from_str(&raw).map(Some).with_context(at) +} + +/// Every dataset.yml under root, sorted. Skips hidden directories, SKIP_DIRS +/// and the `skip` paths. +fn find_dataset_files(root: &Path, skip: &[PathBuf]) -> Result> { + let mut found = Vec::new(); + let mut dirs = vec![root.to_path_buf()]; + while let Some(dir) = dirs.pop() { + let entries = fs::read_dir(&dir).with_context(|| format!("searching {}", dir.display()))?; + for entry in entries { + let entry = entry?; + let path = entry.path(); + if skip.contains(&path) { + continue; + } + let name = entry.file_name(); + let name = name.to_string_lossy(); + // Symlinks aren't followed, so the search can't loop. + let kind = entry.file_type()?; + if kind.is_dir() { + if !name.starts_with('.') && !SKIP_DIRS.contains(&name.as_ref()) { + dirs.push(path); + } + } else if kind.is_file() && name == DATASET_FILE { + found.push(path); + } + } + } + found.sort(); + Ok(found) +} + +/// Reads the .env file at path, and only it, not the environment. A missing +/// file is treated as empty. Values are taken as written, with no $VAR +/// expansion, so a secret or URL containing $ reaches workers intact. +fn read_env_file(path: &Path) -> Result> { + if !path.is_file() { + return Ok(BTreeMap::new()); + } + let vars = dotenvy::EnvLoader::with_path(path) + .sequence(dotenvy::EnvSequence::InputOnly) + .substitution(false) + .load() + .with_context(|| path.display().to_string())?; + Ok(vars.into_iter().collect()) +} + +/// Reads the saved credentials file at path. A missing file is treated as +/// empty. +fn read_saved_credentials(path: &Path) -> Result> { + if !path.is_file() { + return Ok(BTreeMap::new()); + } + let at = || path.display().to_string(); + serde_json::from_str(&fs::read_to_string(path).with_context(at)?).with_context(at) +} + +#[cfg(test)] +mod tests { + use std::os::unix::fs::PermissionsExt; + + use super::dataset_yml::Sharding; + use super::*; + + fn write(path: &Path, text: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + + /// Loads a temp project with the given eac.yml and dataset.yml files. + fn load(eac_yml: &str, datasets: &[(&str, &str)]) -> Result { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + write(&root.join("evals/chat/runner.py"), ""); + write(&root.join(CONFIG_FILE), eac_yml); + write(&root.join(ENV_FILE), "# for tests\nexport FROM_ENV_FILE='file value'\n"); + for (path, text) in datasets { + write(&root.join(path), text); + } + Config::load(root) + } + + fn err(eac_yml: &str, datasets: &[(&str, &str)]) -> String { + format!("{:#}", load(eac_yml, datasets).unwrap_err()) + } + + const CHAT: &str = " +name: chat +agent: chat_agent +runtime: python +offline: + runner: ./runner.py:Runner + cases: evals.chat.cases:CASES + shard_config: {cases_per_shard: 2} + concurrency: 4 + comparisons: + - name: models + judges: [matches] + arms: + - name: small + - name: big + args: {model: big} +online: + runner: ./runner.py:Prod + judges: + - {name: polite, path: \"evals.chat.judges:Polite\"} +"; + + const FILE: &str = "evals/chat/dataset.yml"; + + #[test] + fn datasets_are_defined_in_their_folders() { + let cfg = load("", &[(FILE, CHAT)]).unwrap(); + let d = &cfg.datasets[0]; + assert_eq!((d.name.as_str(), d.file.as_str()), ("chat", "evals/chat/dataset.yml")); + assert_eq!(d.agent.as_deref(), Some("chat_agent")); + let (offline, online) = (d.offline.as_ref().unwrap(), d.online.as_ref().unwrap()); + // ./ references are relative to the dataset.yml, and become relative + // to the project root, where workers run. + assert_eq!(offline.runner, "./evals/chat/runner.py:Runner"); + assert_eq!(offline.cases, "evals.chat.cases:CASES"); + assert_eq!(offline.shard_config, Sharding { cases_per_shard: 2, max_shards: 8 }); + assert_eq!(offline.concurrency, 4); + // A section that doesn't say runs one case at a time. + assert_eq!(online.concurrency, 1); + assert_eq!(offline.comparisons[0].judges, ["matches"]); + assert_eq!(online.runner, "./evals/chat/runner.py:Prod"); + + let picked = cfg.select(&["chat".into(), "chat".into()], Some(Mode::Offline)).unwrap(); + assert_eq!(picked.len(), 1); + assert!(picked[0].online.is_none(), "only the offline section"); + assert!(format!("{:#}", cfg.select(&["nope".into()], Some(Mode::Offline)).unwrap_err()) + .contains("unknown offline dataset \"nope\"; try one of: chat")); + } + + #[test] + fn hidden_and_vendored_folders_are_not_searched() { + let search = [ + (FILE, CHAT), + (".venv/lib/pkg/dataset.yml", "not: yaml we read"), + ("node_modules/pkg/dataset.yml", "not: yaml we read"), + (".eac/runs/dataset.yml", "not: yaml we read"), + ]; + let cfg = load("", &search).unwrap(); + assert_eq!(cfg.datasets.len(), 1); + } + + #[test] + fn excluded_folders_and_files_are_not_searched() { + let search = [ + (FILE, CHAT), + ("legacy/chat/dataset.yml", "name: chat\nagent: theirs\n"), + ("evals/old/dataset.yml", "not: yaml we read"), + ]; + let cfg = load("exclude: [legacy/, ./evals/old/dataset.yml]\n", &search).unwrap(); + assert_eq!(cfg.datasets.len(), 1); + assert!( + err("exclude: [legacy]\n", &[(FILE, CHAT)]).contains("exclude: legacy doesn't exist") + ); + } + + #[test] + fn the_root_has_eac_yml_or_else_is_the_repository_root() { + let dir = tempfile::tempdir().unwrap(); + let repo = dir.path(); + write(&repo.join("evals/chat/runner.py"), ""); + write(&repo.join(FILE), CHAT); + let chat = repo.join("evals/chat"); + // Outside a repository, it's the directory eac runs in. + assert_eq!(Config::load(&chat).unwrap().root, chat); + + fs::create_dir(repo.join(".git")).unwrap(); + let cfg = Config::load(&chat).unwrap(); + assert_eq!(cfg.root, repo); + assert_eq!(cfg.scope.as_deref(), Some(chat.as_path())); + assert_eq!(cfg.datasets[0].file, FILE); + + write(&repo.join("evals/eac.yml"), ""); + assert_eq!(Config::load(&chat).unwrap().root, repo.join("evals")); + } + + #[test] + fn bad_configs_are_rejected() { + assert!(err("", &[]).contains("no dataset.yml found under")); + assert!(err("datasets: []\n", &[(FILE, CHAT)]).contains("unknown field `datasets`")); + // eac.yml has no offline section: seed caches and agent traces are + // code on seeds and judges. + assert!(err("offline:\n seed_cache_provider: []\n", &[(FILE, CHAT)]) + .contains("unknown field `offline`")); + assert!(err("plugins: {}\n", &[(FILE, CHAT)]).contains("unknown field `plugins`")); + let bad = |from: &str, to: &str| err("", &[(FILE, &CHAT.replace(from, to))]); + assert!(bad("runtime: python\n", "").contains("missing field `runtime`")); + assert!(bad("runtime: python", "runtime: typescript") + .contains("\"typescript\" isn't a runtime; expected one of: python")); + assert!( + bad("name: chat", "name: Chat-1").contains("names are lowercase letters, digits and _") + ); + assert!(bad("evals.chat.cases:CASES", "evals/chat/cases.py") + .contains("isn't a reference to code")); + assert!( + bad("./runner.py:Runner", "./missing.py:Runner").contains("missing.py doesn't exist") + ); + assert!(bad("./runner.py:Runner", "../../../outside.py:Runner").contains("doesn't exist")); + assert!(bad(" shard_config:", " sandbox: true\n shard_config:") + .contains("unknown field `sandbox`")); + assert!(bad(" concurrency: 4", " concurrency: 0") + .contains("offline.concurrency: must be at least 1")); + assert!(err("", &[("evals/chat/dataset.yml", "name: chat\nruntime: python\n")]) + .contains("needs an offline or online section")); + assert!(err("", &[("evals/chat/dataset.yml", "")]).contains("dataset.yml is empty")); + let again = CHAT.replace("./runner.py", "../chat/runner.py"); + let both = [(FILE, CHAT), ("evals/chat_again/dataset.yml", &again)]; + assert!(err("", &both).contains( + "evals/chat/dataset.yml and evals/chat_again/dataset.yml both define a dataset named \"chat\"" + )); + let no_judges = CHAT + .replace(" judges:\n - {name: polite, path: \"evals.chat.judges:Polite\"}\n", ""); + assert!(err("", &[(FILE, &no_judges)]).contains("no judges")); + // Judges are only defined per dataset, and run in its worker. + assert!(err("online:\n judges: []\n", &[(FILE, CHAT)]).contains("unknown field `online`")); + assert!(bad("Polite\"}", "Polite\", runtime: python}").contains("unknown field `runtime`")); + assert!(bad(" shard_config:", " agent_trace_provider: []\n shard_config:") + .contains("unknown field `agent_trace_provider`")); + } + + #[test] + fn env_file_values_are_taken_as_written() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(ENV_FILE); + write( + &path, + "# secrets\nPASSWORD=abc$def\nexport URL=\"postgres://u:p$w0rd@h/db\"\nBRACED=x${UNSET}y\nQUOTE=\"a\\\"b\"\nLINES=\"one\ntwo\"\n", + ); + let vars = read_env_file(&path).unwrap(); + assert_eq!(vars["PASSWORD"], "abc$def"); + assert_eq!(vars["URL"], "postgres://u:p$w0rd@h/db"); + assert_eq!(vars["BRACED"], "x${UNSET}y"); + assert_eq!(vars["QUOTE"], "a\"b"); + assert_eq!(vars["LINES"], "one\ntwo"); + // Only the file's own variables, not the environment's. + assert_eq!(vars.len(), 5); + write(&path, "A=1\nnot an assignment\n"); + let err = format!("{:#}", read_env_file(&path).unwrap_err()); + assert!(err.contains("'not an assignment'"), "{err}"); + } + + #[test] + fn saved_credentials_are_merged_private_and_ignored() { + let dir = tempfile::tempdir().unwrap(); + write(&dir.path().join(CONFIG_FILE), ""); + write(&dir.path().join("evals/chat/runner.py"), ""); + write(&dir.path().join(FILE), CHAT); + let cfg = Config::load(dir.path()).unwrap(); + let tricky = "a \"quoted\" $HOME \\ # value\nsecond line"; + let first = [("A", "old"), ("B", tricky)]; + cfg.save_credentials(&first.map(|(k, v)| (k.to_string(), v.to_string())).into()).unwrap(); + let path = + cfg.save_credentials(&BTreeMap::from([("A".to_string(), "new".to_string())])).unwrap(); + + // A later command loads them, the newest value for each. + let saved = Config::load(dir.path()).unwrap().credentials_env; + assert_eq!(saved["A"], "new"); + assert_eq!(saved["B"], tricky); + assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let ignore = fs::read_to_string(path.parent().unwrap().join(".gitignore")).unwrap(); + assert!(ignore.lines().any(|l| l == "*"), "{ignore}"); + } + + #[test] + fn only_python_runtimes_can_be_configured() { + assert!(load("runtimes:\n python: {command: [python3]}\n", &[(FILE, CHAT)]).is_ok()); + assert!(err("runtimes:\n typescript: {command: [node]}\n", &[(FILE, CHAT)]) + .contains("unknown runtime \"typescript\"; expected one of: python")); + } +} diff --git a/core/src/eac/config/project.rs b/core/src/eac/config/project.rs deleted file mode 100644 index 4ed7faf..0000000 --- a/core/src/eac/config/project.rs +++ /dev/null @@ -1,490 +0,0 @@ -//! Loading the project config and selecting datasets by name or directory. - -use std::collections::{BTreeMap, HashMap}; -use std::fs; -use std::path::{Path, PathBuf}; - -use anyhow::{anyhow, bail, Context, Result}; - -use super::dataset_yml::{find_dataset_files, OfflineDataset, OnlineDataset}; -use super::eac_yml::File; -use super::loader::{read_yaml, Loader}; -use super::paths::{clean, relative}; -use super::runtime::{Runtime, RUNTIMES}; - -pub const CONFIG_FILE: &str = "eac.yml"; - -/// A dataset's definition, in the folder with its code. eac finds every one -/// under the project root. -pub const DATASET_FILE: &str = "dataset.yml"; - -/// Read next to eac.yml, for the environment of the processes eac starts. The -/// real environment wins. -pub const ENV_FILE: &str = ".env"; - -/// In the artifacts directory: what logging in to credentials returned, which -/// later commands load. Its directory has a .gitignore of its own, so nothing -/// in it is committed wherever the artifacts directory is. -pub const SAVED_CREDENTIALS: &str = "credentials/saved.json"; - -#[derive(Clone, Debug)] -pub struct Config { - /// The directory eac.yml was found in; paths resolve against it. - pub root: PathBuf, - pub artifacts: PathBuf, - /// The directory eac was pointed at, if below root. Commands default to - /// the datasets under it. - pub scope: Option, - pub runtimes: BTreeMap, - pub offline: Offline, - pub online: Online, - /// From ENV_FILE, for the variables the environment doesn't set. - pub env_file: BTreeMap, - /// What logging in to credentials returned, from SAVED_CREDENTIALS and - /// this command. It wins over the environment and ENV_FILE, which may hold - /// stale values, since each was checked when saved. - pub credentials_env: BTreeMap, -} - -/// The datasets that run offline. -#[derive(Clone, Debug, Default)] -pub struct Offline { - pub datasets: Vec, -} - -/// The datasets that run online. -#[derive(Clone, Debug, Default)] -pub struct Online { - pub datasets: Vec, -} - -impl Config { - /// Finds eac.yml in dir or the nearest parent, and the dataset.yml files - /// under it. - pub fn load(dir: &Path) -> Result { - let start = clean(&std::path::absolute(dir)?); - let mut search = start.as_path(); - let path = loop { - let candidate = search.join(CONFIG_FILE); - if candidate.is_file() { - break candidate; - } - search = search.parent().ok_or_else(|| { - anyhow!( - "no {CONFIG_FILE} found in {} or any parent directory", - dir.display() - ) - })?; - }; - let at = |e: anyhow::Error| e.context(path.display().to_string()); - - let file: File = read_yaml(&path)?.unwrap_or_default(); - let root = path.parent().expect("eac.yml has a parent").to_path_buf(); - let artifacts = clean(&root.join(file.artifacts.as_deref().unwrap_or(".eac"))); - let mut skip = vec![artifacts.clone()]; - for p in &file.exclude { - let excluded = clean(&root.join(p)); - if !excluded.exists() { - return Err(at(anyhow!("exclude: {p} doesn't exist"))); - } - skip.push(excluded); - } - - if let Some(name) = file - .runtimes - .keys() - .find(|r| !RUNTIMES.contains(&r.as_str())) - { - return Err(at(anyhow!( - "unknown runtime {name:?}; expected one of: {}", - RUNTIMES.join(", ") - ))); - } - let env_file = read_env_file(&root.join(ENV_FILE))?; - let credentials_env = read_saved_credentials(&artifacts.join(SAVED_CREDENTIALS))?; - let loader = Loader { root: &root }; - let shared_judges = loader - .judges(file.online.judges, &root, None) - .context("online.judges") - .map_err(at)?; - let mut offline = Offline::default(); - let mut online = Online::default(); - - let files = find_dataset_files(&root, &skip)?; - if files.is_empty() { - bail!( - "no {DATASET_FILE} found under {}; give each dataset one in its folder, e.g.\n\n \ - name: chat\n runtime: python\n offline:\n runner: ./runner.py:ChatRunner\n \ - cases: ./cases.py:CASES", - root.display() - ); - } - let mut defined: HashMap = HashMap::new(); - for dataset_file in files { - let rel = relative(&root, &dataset_file); - let (o, n) = loader - .dataset(&dataset_file, &rel, &shared_judges) - .with_context(|| dataset_file.display().to_string())?; - let name = o.as_ref().map(|d| &d.name).or(n.as_ref().map(|d| &d.name)); - if let Some(name) = name { - if let Some(other) = defined.insert(name.clone(), rel.clone()) { - bail!("{other} and {rel} both define a dataset named {name:?}"); - } - } - offline.datasets.extend(o); - online.datasets.extend(n); - } - let scope = (start != root && start.starts_with(&root)).then_some(start); - - Ok(Config { - root, - artifacts, - scope, - runtimes: file.runtimes, - offline, - online, - env_file, - credentials_env, - }) - } - - /// Picks offline datasets by name. With no names, picks those under the - /// scope directory, or all of them if none are. - pub fn select_offline(&self, names: &[String]) -> Result> { - let datasets = &self.offline.datasets; - self.select(datasets, names, "offline", |d| (&d.name, &d.file)) - } - - pub fn select_online(&self, names: &[String]) -> Result> { - let datasets = &self.online.datasets; - self.select(datasets, names, "online", |d| (&d.name, &d.file)) - } - - /// Both modes' datasets, for commands that show them all. A name only - /// needs to be defined in one of them. - pub fn select_all(&self, names: &[String]) -> Result<(Vec, Vec)> { - let known = |name: &String| { - self.offline.datasets.iter().any(|d| &d.name == name) - || self.online.datasets.iter().any(|d| &d.name == name) - }; - if let Some(unknown) = names.iter().find(|n| !known(n)) { - let mut all: Vec<&str> = self.offline.datasets.iter().map(|d| d.name.as_str()).collect(); - all.extend(self.online.datasets.iter().map(|d| d.name.as_str())); - all.sort_unstable(); - all.dedup(); - bail!("unknown dataset {unknown:?}; try one of: {}", all.join(", ")); - } - let pick = |name: &str| names.is_empty() || names.iter().any(|n| n == name); - let in_scope = |file: &str| self.in_scope(file); - let mut offline: Vec = (self.offline.datasets.iter()) - .filter(|d| pick(&d.name)) - .cloned() - .collect(); - let mut online: Vec = (self.online.datasets.iter()) - .filter(|d| pick(&d.name)) - .cloned() - .collect(); - if names.is_empty() && self.scope.is_some() { - let scoped = |o: &[OfflineDataset], n: &[OnlineDataset]| { - o.iter().any(|d| in_scope(&d.file)) || n.iter().any(|d| in_scope(&d.file)) - }; - if scoped(&offline, &online) { - offline.retain(|d| in_scope(&d.file)); - online.retain(|d| in_scope(&d.file)); - } - } - Ok((offline, online)) - } - - fn select( - &self, - datasets: &[D], - names: &[String], - mode: &str, - key: impl Fn(&D) -> (&String, &String), - ) -> Result> { - if names.is_empty() { - if self.scope.is_some() { - let under: Vec = (datasets.iter()) - .filter(|d| self.in_scope(key(d).1)) - .cloned() - .collect(); - if !under.is_empty() { - return Ok(under); - } - } - return Ok(datasets.to_vec()); - } - let mut out: Vec = Vec::new(); - for want in names { - let Some(d) = datasets.iter().find(|d| key(d).0 == want) else { - let known: Vec<&str> = datasets.iter().map(|d| key(d).0.as_str()).collect(); - let known = if known.is_empty() { - "(none)".to_string() - } else { - known.join(", ") - }; - bail!("unknown {mode} dataset {want:?}; try one of: {known}"); - }; - if !out.iter().any(|o| key(o).0 == want) { - out.push(d.clone()); - } - } - Ok(out) - } - - /// Whether a dataset.yml, relative to root, is under the scope directory. - fn in_scope(&self, file: &str) -> bool { - self.scope - .as_ref() - .is_none_or(|scope| self.root.join(file).starts_with(scope)) - } -} - -impl Config { - /// Adds vars to the saved credentials, which later commands load, and - /// returns the file's path. The file is readable only by its owner and - /// replaced in one step, and its directory gets a .gitignore so it can't - /// be committed. - pub fn save_credentials(&self, vars: &BTreeMap) -> Result { - let path = self.artifacts.join(SAVED_CREDENTIALS); - let at = || path.display().to_string(); - let dir = path.parent().expect("saved credentials are in a directory"); - fs::create_dir_all(dir).with_context(|| dir.display().to_string())?; - let ignore = dir.join(".gitignore"); - if !ignore.exists() { - fs::write(&ignore, "# Written by eac. These are credentials, so none are committed.\n*\n") - .with_context(|| ignore.display().to_string())?; - } - let mut saved = read_saved_credentials(&path)?; - saved.extend(vars.iter().map(|(k, v)| (k.clone(), v.clone()))); - let mut file = tempfile::NamedTempFile::new_in(dir).with_context(at)?; - serde_json::to_writer_pretty(&mut file, &saved).with_context(at)?; - file.persist(&path).map_err(|e| e.error).with_context(at)?; - Ok(path) - } -} - -/// Reads the .env file at path, and only it, not the environment. A missing -/// file is treated as empty. Values are taken as written, with no $VAR -/// expansion, so a secret or URL containing $ reaches workers intact. -fn read_env_file(path: &Path) -> Result> { - if !path.is_file() { - return Ok(BTreeMap::new()); - } - let vars = dotenvy::EnvLoader::with_path(path) - .sequence(dotenvy::EnvSequence::InputOnly) - .substitution(false) - .load() - .with_context(|| path.display().to_string())?; - Ok(vars.into_iter().collect()) -} - -/// Reads the saved credentials file at path. A missing file is treated as -/// empty. -fn read_saved_credentials(path: &Path) -> Result> { - if !path.is_file() { - return Ok(BTreeMap::new()); - } - let at = || path.display().to_string(); - serde_json::from_str(&fs::read_to_string(path).with_context(at)?).with_context(at) -} - -#[cfg(test)] -mod tests { - use std::os::unix::fs::PermissionsExt; - - use super::*; - use crate::eac::Sharding; - - fn write(path: &Path, text: &str) { - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, text).unwrap(); - } - - /// Loads a temp project with the given eac.yml and dataset.yml files. - fn load(eac_yml: &str, datasets: &[(&str, &str)]) -> Result { - let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); - write(&root.join("evals/chat/runner.py"), ""); - write(&root.join(CONFIG_FILE), eac_yml); - write(&root.join(ENV_FILE), "# for tests\nexport FROM_ENV_FILE='file value'\n"); - for (path, text) in datasets { - write(&root.join(path), text); - } - Config::load(root) - } - - fn err(eac_yml: &str, datasets: &[(&str, &str)]) -> String { - format!("{:#}", load(eac_yml, datasets).unwrap_err()) - } - - const CHAT: &str = " -name: chat -agent: chat_agent -runtime: python -offline: - runner: ./runner.py:Runner - cases: evals.chat.cases:CASES - shard_config: {cases_per_shard: 2} - concurrency: 4 - comparisons: - - name: models - judges: [matches] - arms: - - name: small - - name: big - args: {model: big} -online: - runner: ./runner.py:Prod - judges: - - {name: polite, path: \"evals.chat.judges:Polite\"} -"; - - const FILE: &str = "evals/chat/dataset.yml"; - - #[test] - fn datasets_are_defined_in_their_folders() { - let cfg = load("", &[(FILE, CHAT)]).unwrap(); - let d = &cfg.offline.datasets[0]; - assert_eq!((d.name.as_str(), d.file.as_str()), ("chat", "evals/chat/dataset.yml")); - assert_eq!(d.agent.as_deref(), Some("chat_agent")); - // ./ references are relative to the dataset.yml, and become relative - // to the project root, where workers run. - assert_eq!(d.runner, "./evals/chat/runner.py:Runner"); - assert_eq!(d.cases, "evals.chat.cases:CASES"); - assert_eq!(d.shard_config, Sharding { cases_per_shard: 2, max_shards: 8 }); - assert_eq!(d.concurrency, 4); - // A section that doesn't say runs one case at a time. - assert_eq!(cfg.online.datasets[0].concurrency, 1); - assert_eq!(d.comparisons[0].judges, ["matches"]); - assert_eq!(cfg.online.datasets[0].runner, "./evals/chat/runner.py:Prod"); - - assert_eq!(cfg.select_offline(&["chat".into(), "chat".into()]).unwrap().len(), 1); - assert!(format!("{:#}", cfg.select_offline(&["nope".into()]).unwrap_err()) - .contains("unknown offline dataset \"nope\"; try one of: chat")); - } - - #[test] - fn hidden_and_vendored_folders_are_not_searched() { - let search = [ - (FILE, CHAT), - (".venv/lib/pkg/dataset.yml", "not: yaml we read"), - ("node_modules/pkg/dataset.yml", "not: yaml we read"), - (".eac/runs/dataset.yml", "not: yaml we read"), - ]; - let cfg = load("", &search).unwrap(); - assert_eq!(cfg.offline.datasets.len(), 1); - } - - #[test] - fn excluded_folders_and_files_are_not_searched() { - let search = [ - (FILE, CHAT), - ("legacy/chat/dataset.yml", "name: chat\nagent: theirs\n"), - ("evals/old/dataset.yml", "not: yaml we read"), - ]; - let cfg = load("exclude: [legacy/, ./evals/old/dataset.yml]\n", &search).unwrap(); - assert_eq!(cfg.offline.datasets.len(), 1); - assert!(err("exclude: [legacy]\n", &[(FILE, CHAT)]).contains("exclude: legacy doesn't exist")); - } - - #[test] - fn online_datasets_offer_their_judges_then_the_shared_ones() { - let cfg = load( - "online:\n judges:\n - {name: llm_judge, path: \"eac.judges:LlmJudge\", runtime: python}\n - {name: polite, path: \"eac.judges:Polite\", runtime: python}\n", - &[(FILE, CHAT)], - ) - .unwrap(); - let judges: Vec<(&str, &str)> = (cfg.online.datasets[0].judges.iter()) - .map(|j| (j.name.as_str(), j.path.as_str())) - .collect(); - assert_eq!(judges, [("polite", "evals.chat.judges:Polite"), ("llm_judge", "eac.judges:LlmJudge")]); - } - - #[test] - fn bad_configs_are_rejected() { - assert!(err("", &[]).contains("no dataset.yml found under")); - assert!(err("datasets: []\n", &[(FILE, CHAT)]).contains("unknown field `datasets`")); - // eac.yml has no offline section: seed caches and agent traces are - // code on seeds and judges. - assert!(err("offline:\n seed_cache_provider: []\n", &[(FILE, CHAT)]).contains("unknown field `offline`")); - assert!(err("plugins: {}\n", &[(FILE, CHAT)]).contains("unknown field `plugins`")); - let bad = |from: &str, to: &str| err("", &[(FILE, &CHAT.replace(from, to))]); - assert!(bad("runtime: python\n", "").contains("missing field `runtime`")); - assert!(bad("runtime: python", "runtime: typescript") - .contains("\"typescript\" isn't a runtime; expected one of: python")); - assert!(bad("name: chat", "name: Chat-1").contains("names are lowercase letters, digits and _")); - assert!(bad("evals.chat.cases:CASES", "evals/chat/cases.py").contains("isn't a reference to code")); - assert!(bad("./runner.py:Runner", "./missing.py:Runner").contains("missing.py doesn't exist")); - assert!(bad("./runner.py:Runner", "../../../outside.py:Runner").contains("doesn't exist")); - assert!(bad(" shard_config:", " sandbox: true\n shard_config:").contains("unknown field `sandbox`")); - assert!(bad(" concurrency: 4", " concurrency: 0").contains("offline.concurrency: must be at least 1")); - assert!(err("", &[("evals/chat/dataset.yml", "name: chat\nruntime: python\n")]) - .contains("needs an offline or online section")); - assert!(err("", &[("evals/chat/dataset.yml", "")]).contains("dataset.yml is empty")); - let again = CHAT.replace("./runner.py", "../chat/runner.py"); - let both = [(FILE, CHAT), ("evals/chat_again/dataset.yml", &again)]; - assert!(err("", &both).contains( - "evals/chat/dataset.yml and evals/chat_again/dataset.yml both define a dataset named \"chat\"" - )); - let no_judges = CHAT.replace(" judges:\n - {name: polite, path: \"evals.chat.judges:Polite\"}\n", ""); - assert!(err("", &[(FILE, &no_judges)]).contains("no judges")); - assert!(err("online:\n judges:\n - {name: polite, path: \"eac.judges:Polite\"}\n", &[(FILE, CHAT)]) - .contains("runtime is required here")); - assert!(bad(" shard_config:", " agent_trace_provider: []\n shard_config:") - .contains("unknown field `agent_trace_provider`")); - } - - #[test] - fn env_file_values_are_taken_as_written() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join(ENV_FILE); - write( - &path, - "# secrets\nPASSWORD=abc$def\nexport URL=\"postgres://u:p$w0rd@h/db\"\nBRACED=x${UNSET}y\nQUOTE=\"a\\\"b\"\nLINES=\"one\ntwo\"\n", - ); - let vars = read_env_file(&path).unwrap(); - assert_eq!(vars["PASSWORD"], "abc$def"); - assert_eq!(vars["URL"], "postgres://u:p$w0rd@h/db"); - assert_eq!(vars["BRACED"], "x${UNSET}y"); - assert_eq!(vars["QUOTE"], "a\"b"); - assert_eq!(vars["LINES"], "one\ntwo"); - // Only the file's own variables, not the environment's. - assert_eq!(vars.len(), 5); - write(&path, "A=1\nnot an assignment\n"); - let err = format!("{:#}", read_env_file(&path).unwrap_err()); - assert!(err.contains("'not an assignment'"), "{err}"); - } - - #[test] - fn saved_credentials_are_merged_private_and_ignored() { - let dir = tempfile::tempdir().unwrap(); - write(&dir.path().join(CONFIG_FILE), ""); - write(&dir.path().join("evals/chat/runner.py"), ""); - write(&dir.path().join(FILE), CHAT); - let cfg = Config::load(dir.path()).unwrap(); - let tricky = "a \"quoted\" $HOME \\ # value\nsecond line"; - let first = [("A", "old"), ("B", tricky)]; - cfg.save_credentials(&first.map(|(k, v)| (k.to_string(), v.to_string())).into()) - .unwrap(); - let path = cfg - .save_credentials(&BTreeMap::from([("A".to_string(), "new".to_string())])) - .unwrap(); - - // A later command loads them, the newest value for each. - let saved = Config::load(dir.path()).unwrap().credentials_env; - assert_eq!(saved["A"], "new"); - assert_eq!(saved["B"], tricky); - assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); - let ignore = fs::read_to_string(path.parent().unwrap().join(".gitignore")).unwrap(); - assert!(ignore.lines().any(|l| l == "*"), "{ignore}"); - } - - #[test] - fn only_python_runtimes_can_be_configured() { - assert!(load("runtimes:\n python: {command: [python3]}\n", &[(FILE, CHAT)]).is_ok()); - assert!(err("runtimes:\n typescript: {command: [node]}\n", &[(FILE, CHAT)]) - .contains("unknown runtime \"typescript\"; expected one of: python")); - } -} diff --git a/core/src/eac/config/runtime.rs b/core/src/eac/config/runtime.rs index 626ce1f..2d246d9 100644 --- a/core/src/eac/config/runtime.rs +++ b/core/src/eac/config/runtime.rs @@ -1,5 +1,3 @@ -//! Runtimes and the commands that start their SDK workers. - use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::process::Command; @@ -7,7 +5,7 @@ use std::process::Command; use anyhow::{bail, Result}; use serde::Deserialize; -use super::project::Config; +use super::Config; pub const RUNTIMES: &[&str] = &["python"]; @@ -24,20 +22,22 @@ pub struct Runtime { } impl Config { - /// The interpreter comes from EAC_PYTHON, then eac.yml's runtimes, then + /// The command that starts a worker for runtime, in the project root. The + /// interpreter comes from EAC_PYTHON, then eac.yml's runtimes, then /// `python_command`. pub fn worker_command(&self, runtime: &str) -> Result { + if runtime != "python" { + bail!("no worker for runtime {runtime:?}"); + } let configured = self.runtimes.get(runtime).cloned().unwrap_or_default(); - let configured_command = Some(configured.command).filter(|c| !c.is_empty()); - let interpreter = match runtime { - "python" => env_command("EAC_PYTHON") - .or(configured_command) - .unwrap_or_else(|| python_command(&self.root)), - _ => bail!("no worker for runtime {runtime:?}"), - }; + let interpreter = + (std::env::var("EAC_PYTHON").ok().filter(|v| !v.is_empty()).map(|v| vec![v])) + .or(Some(configured.command).filter(|c| !c.is_empty())) + .unwrap_or_else(|| python_command(&self.root)); + let mut cmd = Command::new(&interpreter[0]); // -u so user prints reach us unbuffered. - cmd.args(&interpreter[1..]).args(["-u", "-m", "eac.worker"]); + cmd.args(&interpreter[1..]).args(["-u", "-m", "eac.worker"]).current_dir(&self.root); for (key, value) in &self.env_file { if std::env::var_os(key).is_none() { cmd.env(key, value); @@ -58,30 +58,9 @@ pub fn check_runtime(runtime: &str) -> Result<()> { Ok(()) } -/// An entry's own runtime, falling back to its dataset's. -pub fn entry_runtime(own: Option, dataset: Option<&str>) -> Result { - let runtime = match (own, dataset) { - (Some(own), _) => own, - (None, Some(dataset)) => dataset.to_string(), - (None, None) => bail!( - "runtime is required here, e.g. runtime: {}", - RUNTIMES[0] - ), - }; - check_runtime(&runtime)?; - Ok(runtime) -} - -fn env_command(key: &str) -> Option> { - std::env::var(key) - .ok() - .filter(|v| !v.is_empty()) - .map(|v| vec![v]) -} - /// The default Python for workers. Tries the active virtualenv, the /// project's .venv, `uv run` in a uv project, then python3. -pub fn python_command(root: &Path) -> Vec { +fn python_command(root: &Path) -> Vec { if let Some(venv) = std::env::var_os("VIRTUAL_ENV") { let python = PathBuf::from(venv).join("bin/python"); if python.is_file() { @@ -93,11 +72,7 @@ pub fn python_command(root: &Path) -> Vec { fn project_python(root: &Path, has_uv: bool) -> Vec { let dirs = project_dirs(root); - if let Some(python) = dirs - .iter() - .map(|d| d.join(".venv/bin/python")) - .find(|p| p.is_file()) - { + if let Some(python) = dirs.iter().map(|d| d.join(".venv/bin/python")).find(|p| p.is_file()) { return vec![python.to_string_lossy().into_owned()]; } if has_uv && dirs.iter().any(|d| d.join("uv.lock").is_file()) { diff --git a/core/src/eac/engine.rs b/core/src/eac/engine.rs index f152411..ad90bb4 100644 --- a/core/src/eac/engine.rs +++ b/core/src/eac/engine.rs @@ -1,47 +1,26 @@ -//! The engine owns the config and each runtime's SDK workers. Each phase -//! adds its methods in phases/. - use std::collections::{BTreeMap, HashMap}; -use std::rc::Rc; -use std::sync::atomic::AtomicBool; use std::thread; use anyhow::Result; use serde::de::DeserializeOwned; use serde::Serialize; -use super::report; use super::{Config, Dataset}; -use crate::schema::Mode; use crate::worker::Worker; -/// Starts each worker on first use and closes them on drop. +/// Runs the phases on each runtime's SDK workers, starting them on first use +/// and closing them on drop. pub struct Engine { - pub(super) cancel: &'static AtomicBool, - pub(super) cfg: Rc, - pub(super) workers: Workers, - /// From --concurrency. Overrides every dataset's setting. + pub(super) cfg: Config, + /// From --concurrency, overrides every dataset's setting. concurrency: Option, + /// Each runtime's workers, in the order they started. + workers: HashMap>, } impl Engine { - pub fn new(cfg: Config, cancel: &'static AtomicBool) -> Engine { - let cfg = Rc::new(cfg); - Engine { - cancel, - workers: Workers::new(Rc::clone(&cfg), cancel), - cfg, - concurrency: None, - } - } - - /// Gives every process started from now on what a login returned, and - /// closes the running ones so they restart with it. - pub(super) fn add_login_env(&mut self, env: BTreeMap) { - let mut cfg = (*self.cfg).clone(); - cfg.credentials_env.extend(env); - self.cfg = Rc::new(cfg); - self.workers = Workers::new(Rc::clone(&self.cfg), self.cancel); + pub fn new(cfg: Config) -> Engine { + Engine { cfg, concurrency: None, workers: HashMap::new() } } pub fn config(&self) -> &Config { @@ -56,74 +35,56 @@ impl Engine { /// How many of d's cases run at once. --concurrency wins over dataset.yml's /// setting for the run's mode, and either is capped at the case count. pub(super) fn concurrency(&self, d: &Dataset) -> usize { - let configured = match d.code.mode { - Mode::Offline => (self.cfg.offline.datasets.iter()) - .find(|o| o.name == d.name) - .map(|o| o.concurrency), - Mode::Online => (self.cfg.online.datasets.iter()) - .find(|o| o.name == d.name) - .map(|o| o.concurrency), - }; + let configured = self.cfg.datasets.iter().find(|c| c.name == d.name); + let configured = configured.and_then(|c| c.concurrency(d.code.mode)); let n = self.concurrency.or(configured).unwrap_or(1); n.min(d.cases.len()).max(1) } - /// Calls the runtime's first worker. Used for everything except running - /// and judging cases. - pub(super) fn call( - &mut self, - runtime: &str, - method: &str, - params: impl Serialize, - ) -> Result { - let cancel = self.cancel; - self.workers.first(runtime, 1)?[0].call(cancel, method, params) - } -} - -/// Each runtime's SDK workers. The first answers most calls, and phases run -/// cases on as many as the dataset's concurrency. -pub struct Workers { - cancel: &'static AtomicBool, - cfg: Rc, - /// In the order they started. - by_runtime: HashMap>, -} - -impl Workers { - fn new(cfg: Rc, cancel: &'static AtomicBool) -> Workers { - Workers { - cancel, - cfg, - by_runtime: HashMap::new(), - } - } - /// The runtime's first n workers, starting the ones it doesn't have yet. - pub(super) fn first(&mut self, runtime: &str, n: usize) -> Result<&mut [Worker]> { - let workers = self.by_runtime.entry(runtime.to_string()).or_default(); + pub(super) fn workers(&mut self, runtime: &str, n: usize) -> Result<&mut [Worker]> { + let workers = self.workers.entry(runtime.to_string()).or_default(); while workers.len() < n { let label = match workers.len() { 0 => format!("{runtime} worker"), i => format!("{runtime} worker {}", i + 1), }; - let cmd = self.cfg.worker_command(runtime)?; detail!("starting {label}"); - let worker = - Worker::spawn(&label, cmd, &self.cfg.root, report::worker_log, self.cancel)?; - workers.push(worker); + workers.push(Worker::spawn(&label, self.cfg.worker_command(runtime)?)?); } Ok(&mut workers[..n]) } -} -impl Drop for Workers { + /// Calls the runtime's first worker. Used for everything except running + /// and judging cases, which spread over several. + pub(super) fn call( + &mut self, + runtime: &str, + method: &str, + params: impl Serialize, + ) -> Result { + self.workers(runtime, 1)?[0].call(method, params) + } + + /// Gives every process started from now on what a login returned, and + /// closes the running ones so they restart with it. + pub(super) fn add_login_env(&mut self, env: BTreeMap) { + self.cfg.credentials_env.extend(env); + self.close_workers(); + } + /// Closes workers in parallel so slow exits don't add up. - fn drop(&mut self) { + fn close_workers(&mut self) { thread::scope(|s| { - for worker in self.by_runtime.drain().flat_map(|(_, workers)| workers) { + for worker in self.workers.drain().flat_map(|(_, workers)| workers) { s.spawn(move || drop(worker)); } }); } } + +impl Drop for Engine { + fn drop(&mut self) { + self.close_workers(); + } +} diff --git a/core/src/eac/mod.rs b/core/src/eac/mod.rs index cdba300..0367a11 100644 --- a/core/src/eac/mod.rs +++ b/core/src/eac/mod.rs @@ -1,5 +1,5 @@ -#[macro_use] -pub mod report; +//! The framework: config, the phases a run goes through, and the run +//! directory they share. mod config; mod engine; diff --git a/core/src/eac/phases/collect.rs b/core/src/eac/phases/collect.rs index 2c84d8b..9a82e75 100644 --- a/core/src/eac/phases/collect.rs +++ b/core/src/eac/phases/collect.rs @@ -1,108 +1,112 @@ -//! Collects each case's output by running the system under test offline, or -//! by fetching production records online. - +use std::collections::BTreeMap; use std::time::Instant; use anyhow::{Context, Result}; use chrono::Utc; use super::seed::handles_for; -use crate::eac::report::first_line; use crate::eac::{Dataset, Engine, Manifest, Output, Run, Seeds, Window}; -use crate::schema::{Case, CaseExecuteParams, CaseExecuteResult, OnlineFetchParams, OnlineFetchResult}; -use crate::worker::{each, Interrupted}; +use crate::report::first_line; +use crate::schema::{ + Case, CaseRunParams, CaseRunResult, Handle, OnlineCollectParams, OnlineCollectResult, +}; +use crate::worker::{each, Interrupted, Worker}; impl Engine { /// Runs the system under test on each case and records its raw output, /// up to the dataset's concurrency at a time. pub fn collect(&mut self, run: &Run, m: &Manifest, seeds: &Seeds) -> Result<()> { - let cancel = self.cancel; for d in &m.datasets { let n = self.concurrency(d); - let workers = self.workers.first(&d.runtime, n)?; - let jobs = d.cases.iter().map(|c| handles_for(seeds, d, c, true).map(|h| (c, h))); - each(workers, cancel, jobs, |worker, (c, handles)| { - let conversation_id = new_conversation_id(); - - let started_at = Utc::now(); - let start = Instant::now(); - let params = CaseExecuteParams { - dataset: &d.code, - case: c, - seeds: handles, - args: &d.args, - conversation_id: &conversation_id, - }; - let res: Result = worker.call(cancel, "case.execute", params); - let mut out = Output { - dataset: d.name.clone(), - case: c.name.clone(), - input: c.input.clone(), - conversation_id: Some(conversation_id), - started_at: Some(started_at), - ended_at: Some(Utc::now()), - duration_seconds: start.elapsed().as_secs_f64(), - ..Default::default() - }; - match res { - Ok(res) => { - out.output = res.output; - out.metrics = res.metrics; - if res.conversation_id.is_some() { - out.conversation_id = res.conversation_id; - } - detail!("{}/{} ran in {:.2}s", d.name, c.name, out.duration_seconds); - } - Err(e) if e.is::() => return Err(e), - Err(e) => { - // Recorded as an error output so one bad case doesn't - // stop the run. - out.error = format!("{e:#}"); - warning!("{}/{} errored: {}", d.name, c.name, first_line(&out.error)); - } - } - run.write_output(&out) + 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)?) })?; } Ok(()) } - /// Pulls each dataset's production records in window and returns them as - /// outputs, so an online run is judged like any other. - pub fn fetch(&mut self, datasets: &mut [Dataset], window: &Window) -> Result> { + /// Collects each dataset's production runs in window as its cases, and + /// returns their outputs, so an online run is judged like any other. + pub fn collect_online( + &mut self, + datasets: &mut [Dataset], + window: &Window, + ) -> Result> { let mut outputs = Vec::new(); - for d in datasets.iter_mut() { - let params = OnlineFetchParams { + for d in datasets { + let params = OnlineCollectParams { dataset: &d.code, since: &window.since, until: &window.until, limit: window.limit, args: &d.args, }; - let res: OnlineFetchResult = self - .call(&d.runtime, "online.fetch", params) - .with_context(|| format!("fetching {}", d.name))?; - info!("{:<24} {} records", d.name, res.records.len()); + let res: OnlineCollectResult = self + .call(&d.runtime, "online.collect", params) + .with_context(|| format!("collecting {}", d.name))?; + info!("{:<24} {} cases", d.name, res.cases.len()); - d.cases = res - .records - .iter() - .map(|r| Case::named(r.id.clone(), r.input.clone())) - .collect(); - outputs.extend(res.records.into_iter().map(|r| Output { - dataset: d.name.clone(), - case: r.id, - input: r.input, - output: r.output, - conversation_id: r.conversation_id, - ..Default::default() - })); + for c in res.cases { + outputs.push(Output { + dataset: d.name.clone(), + case: c.name.clone(), + input: c.input.clone(), + output: c.output.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 }); + } } Ok(outputs) } } -/// Tags the agent run so its trace can be found later. -fn new_conversation_id() -> String { - format!("eval-{}", &uuid::Uuid::new_v4().simple().to_string()[..12]) +/// Runs one case. Its failure is recorded in the output rather than +/// returned, so one bad case doesn't stop the run. +fn run_case( + worker: &mut Worker, + d: &Dataset, + c: &Case, + seeds: BTreeMap<&str, &Handle>, +) -> 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]); + let started_at = Utc::now(); + let start = Instant::now(); + let params = CaseRunParams { + dataset: &d.code, + case: c, + seeds, + args: &d.args, + conversation_id: &conversation_id, + }; + let res = worker.call::("case.run", params); + + let mut out = Output { + dataset: d.name.clone(), + case: c.name.clone(), + input: c.input.clone(), + conversation_id: Some(conversation_id), + started_at: Some(started_at), + ended_at: Some(Utc::now()), + duration_seconds: start.elapsed().as_secs_f64(), + ..Default::default() + }; + match res { + Ok(res) => { + out.output = res.output; + 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); + } + Err(e) if e.is::() => return Err(e), + Err(e) => { + out.error = format!("{e:#}"); + warning!("{}/{} errored: {}", d.name, c.name, first_line(&out.error)); + } + } + Ok(out) } diff --git a/core/src/eac/phases/credentials.rs b/core/src/eac/phases/credentials.rs index 8d82175..ab17ab2 100644 --- a/core/src/eac/phases/credentials.rs +++ b/core/src/eac/phases/credentials.rs @@ -1,18 +1,15 @@ -//! Checks the credentials a command's phases need before any of them starts, -//! and logs in to the ones that aren't set up. - -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet}; use std::io::{self, BufRead, IsTerminal, Write}; -use std::sync::atomic::Ordering; use anyhow::{bail, Context, Result}; -use crate::eac::{report, Dataset, Engine, SeedEntry}; +use crate::eac::{in_ci, Dataset, Engine, SeedEntry}; +use crate::report; use crate::schema::{ Credential, CredentialsCheckParams, CredentialsCheckResult, CredentialsLoginParams, CredentialsLoginResult, Error, }; -use crate::worker::{Interrupted, Worker}; +use crate::worker::{check_interrupted, Interrupted, Worker}; /// The phases of a run whose credentials a command checks. #[derive(Clone, Copy, PartialEq, Eq)] @@ -22,35 +19,24 @@ pub enum Phase { Judge, } -/// Whether a credential that isn't set up gets logged in to. +pub const ALL_PHASES: &[Phase] = &[Phase::Seed, Phase::Collect, Phase::Judge]; + +/// A credential to check, with the runtime whose SDK checks it. +type Needed = (String, Credential); + +/// Whether to log in to the credentials that aren't set up. #[derive(Clone, Copy, PartialEq, Eq)] enum Login { - /// After asking, when eac runs on a terminal. + /// Only on a terminal, after asking. Ask, - /// Without asking, as `eac auth` does. Always, } -/// Each credential to check once, with the runtime whose SDK checks it. -#[derive(Default)] -struct Needed { - seen: HashSet, - list: Vec<(String, Credential)>, -} - -impl Needed { - fn add<'a>(&mut self, runtime: &str, credentials: impl IntoIterator) { - for c in credentials { - if self.seen.insert(format!("{runtime}:{}", c.key())) { - self.list.push((runtime.to_string(), c.clone())); - } - } - } -} - 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. + /// terminal, offers to log in to the credentials that aren't set up. CI + /// sets credentials up itself, and checking them takes time, so they + /// aren't checked there. pub fn check_credentials(&mut self, datasets: &[Dataset], phases: &[Phase]) -> Result<()> { if in_ci() { return Ok(()); @@ -66,9 +52,9 @@ impl Engine { if in_ci() { return Ok(()); } - let mut needed = Needed::default(); + let mut needed = Vec::new(); for e in entries { - needed.add(&e.runtime, &e.seed.credentials); + add(&mut needed, &e.runtime, &e.seed.credentials); } self.ensure(needed, Login::Ask) } @@ -76,8 +62,8 @@ impl Engine { /// Checks everything the datasets need in any phase, and logs in to the /// credentials that aren't set up without asking. pub fn set_up_credentials(&mut self, datasets: &[Dataset]) -> Result<()> { - let needed = needed(datasets, &[Phase::Seed, Phase::Collect, Phase::Judge]); - if needed.list.is_empty() { + let needed = needed(datasets, ALL_PHASES); + if needed.is_empty() { info!("no dataset needs credentials"); return Ok(()); } @@ -85,9 +71,8 @@ impl Engine { } /// Checks each credential and logs in to the ones that aren't set up as - /// login allows. Fails listing the ones that still aren't. - fn ensure(&mut self, needed: Needed, login: Login) -> Result<()> { - let needed = needed.list; + /// `login` allows. Fails listing the ones that still aren't. + fn ensure(&mut self, needed: Vec, login: Login) -> Result<()> { if needed.is_empty() { return Ok(()); } @@ -98,49 +83,44 @@ impl Engine { } let mut failures = Vec::new(); - let mut logged_in = Vec::new(); - let mut env = BTreeMap::new(); - for ((runtime, c), ok) in needed.iter().zip(checked) { + // Each credential logged in to, with the variables its login set. + let mut logins: Vec<(Needed, BTreeMap)> = Vec::new(); + for ((runtime, c), ok) in needed.into_iter().zip(checked) { if ok { continue; } - let attempt = !c.manual - && match login { - Login::Always => true, - Login::Ask => on_terminal() && confirm(&format!("Set up {} now?", c.name))?, - }; - if self.cancel.load(Ordering::Relaxed) { - return Err(Interrupted.into()); - } - if !attempt { - failures.push(failure(c, "missing or invalid")); + let log_in = !c.manual + && (login == Login::Always + || (on_terminal() && confirm(&format!("Set up {} now?", c.name))?)); + check_interrupted()?; + if !log_in { + failures.push(failure(&c, "missing or invalid")); continue; } - match self.log_in(runtime, c) { - Ok(returned) => { - env.extend(returned.clone()); - logged_in.push(((runtime.clone(), c.clone()), returned)); - } + match self.log_in(&runtime, &c) { + Ok(env) => logins.push(((runtime, c), env)), Err(e) if e.is::() => return Err(e), - Err(e) => failures.push(failure(c, &reason(&e))), + Err(e) => failures.push(failure(&c, &reason(&e))), } } - if !logged_in.is_empty() { - // Restarted once, after every login, since imports can be slow. - self.add_login_env(env); - let (credentials, returned): (Vec<_>, Vec<_>) = logged_in.into_iter().unzip(); - let rechecked = self.check(&credentials)?; + + 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 rechecked = self.check(&logged_in)?; let mut working = BTreeMap::new(); - for (((_, c), env), ok) in credentials.iter().zip(returned).zip(rechecked) { + for (((_, c), env), ok) in logins.into_iter().zip(rechecked) { report::checked(ok, &c.name); if ok { working.extend(env); } else { - failures.push(failure(c, "still not set up after logging in")); + failures.push(failure(&c, "still not set up after logging in")); } } self.save(&working); } + if !failures.is_empty() { bail!("credentials aren't set up:\n{}", failures.join("\n")); } @@ -148,25 +128,17 @@ impl Engine { } /// Whether each credential works, asking the SDK of each one's runtime. - fn check(&mut self, needed: &[(String, Credential)]) -> Result> { + fn check(&mut self, needed: &[Needed]) -> Result> { let mut ok = vec![false; needed.len()]; - let mut runtimes: Vec<&str> = needed.iter().map(|(r, _)| r.as_str()).collect(); - runtimes.sort_unstable(); - runtimes.dedup(); + let runtimes: BTreeSet<&str> = needed.iter().map(|(r, _)| r.as_str()).collect(); for runtime in runtimes { - let (indices, credentials): (Vec, Vec) = (needed.iter().enumerate()) - .filter(|(_, (r, _))| r == runtime) - .map(|(i, (_, c))| (i, c.clone())) - .unzip(); - let res: CredentialsCheckResult = self - .call( - runtime, - "credentials.check", - CredentialsCheckParams { - credentials: &credentials, - }, - ) - .context("checking credentials")?; + let indices: Vec = + (0..needed.len()).filter(|&i| needed[i].0 == runtime).collect(); + let credentials: Vec = + indices.iter().map(|&i| needed[i].1.clone()).collect(); + let params = CredentialsCheckParams { credentials: &credentials }; + let res: CredentialsCheckResult = + self.call(runtime, "credentials.check", params).context("checking credentials")?; if res.authenticated.len() != credentials.len() { bail!( "the {runtime} worker checked {} credentials, but eac sent {}", @@ -184,16 +156,10 @@ impl Engine { /// Logs in on a worker started on the terminal, and returns the variables /// it sets. fn log_in(&mut self, runtime: &str, c: &Credential) -> Result> { - let cmd = self.cfg.worker_command(runtime)?; - let label = format!("{runtime} login"); - let res: CredentialsLoginResult = { - let mut worker = Worker::spawn_attached(&label, cmd, &self.cfg.root, self.cancel)?; - worker.call( - self.cancel, - "credentials.login", - CredentialsLoginParams { credential: c }, - )? - }; + let mut worker = + Worker::spawn_attached(&format!("{runtime} login"), self.cfg.worker_command(runtime)?)?; + let res: CredentialsLoginResult = + worker.call("credentials.login", CredentialsLoginParams { credential: c })?; if let Some(bad) = res.env.keys().find(|k| !is_var_name(k)) { bail!("login returned {bad:?}, which isn't an environment variable name"); } @@ -217,47 +183,45 @@ impl Engine { } } -/// What the datasets need for phases. -fn needed(datasets: &[Dataset], phases: &[Phase]) -> Needed { - let mut needed = Needed::default(); +/// What the datasets need for phases, each credential once. +fn needed(datasets: &[Dataset], phases: &[Phase]) -> Vec { + let mut needed = Vec::new(); for d in datasets { if phases.contains(&Phase::Seed) { let seeds = d.cases.iter().flat_map(|c| &c.seeds); - needed.add(&d.runtime, seeds.flat_map(|s| &s.credentials)); + add(&mut needed, &d.runtime, seeds.flat_map(|s| &s.credentials)); } if phases.contains(&Phase::Collect) { - needed.add(&d.runtime, &d.runner_credentials); + add(&mut needed, &d.runtime, &d.runner_credentials); } if phases.contains(&Phase::Judge) { - // A run's own judges replace each case's. - let judges: Vec<&String> = if d.judges.is_empty() { - d.cases.iter().flat_map(|c| &c.judges).collect() - } else { - d.judges.iter().collect() - }; - let credentials = judges - .into_iter() - .filter_map(|j| d.judge_credentials.get(j)); - needed.add(&d.runtime, credentials.flatten()); + let judges = d.used_judges().into_iter().filter_map(|j| d.judge_credentials.get(j)); + add(&mut needed, &d.runtime, judges.flatten()); } } needed } +/// 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, + runtime: &str, + credentials: impl IntoIterator, +) { + for c in credentials { + if !needed.iter().any(|(r, n)| r == runtime && n.key() == c.key()) { + needed.push((runtime.to_string(), c.clone())); + } + } +} + fn is_var_name(s: &str) -> bool { let mut chars = s.chars(); - chars - .next() - .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') } -/// CI sets credentials up itself, and checking them takes time, so they're -/// only checked outside it. Most CI services set CI. -fn in_ci() -> bool { - std::env::var("CI").is_ok_and(|v| !v.is_empty() && v != "false" && v != "0") -} - fn on_terminal() -> bool { io::stdin().is_terminal() && io::stderr().is_terminal() } diff --git a/core/src/eac/phases/discover.rs b/core/src/eac/phases/discover.rs index 57286da..80679cf 100644 --- a/core/src/eac/phases/discover.rs +++ b/core/src/eac/phases/discover.rs @@ -1,71 +1,31 @@ -//! Imports each dataset's code to learn its cases, and has its SDK check a -//! run's args. - use std::collections::BTreeMap; use anyhow::{Context, Result}; -use serde_json::Value; -use crate::eac::{Comparison, Dataset, Engine, OfflineDataset, OnlineDataset, Sharding}; +use crate::eac::{Dataset, DatasetConfig, Engine}; use crate::schema::{ - ArgsValidateParams, ArgsValidateResult, Case, DatasetRef, DiscoverParams, DiscoverResult, - Mode, Object, + ArgsValidateParams, ArgsValidateResult, Case, DiscoverParams, DiscoverResult, Mode, Object, }; /// A dataset as its dataset.yml defines it and its code describes it, before -/// any case selection. A dataset defined in both modes has both. +/// any case selection. #[derive(Clone, Debug)] pub struct Discovered { - pub name: String, - /// Its dataset.yml, relative to the project root. - pub file: String, - pub offline: Option, - pub online: Option, - /// JSON Schema of each judge's --judge-args, by judge name. - pub judge_args_schemas: BTreeMap, -} - -#[derive(Clone, Debug)] -pub struct OfflineInfo { - pub runtime: String, - pub agent: Option, - pub code: DatasetRef, + /// With only the sections of the modes discovered. + pub config: DatasetConfig, + /// Every offline case, enabled or not. pub cases: Vec, - pub comparisons: Vec, - pub shard_config: Sharding, - /// JSON Schema of the runner's --args. - pub args_schema: Option, -} - -#[derive(Clone, Debug)] -pub struct OnlineInfo { - pub runtime: String, - pub agent: Option, - pub code: DatasetRef, - /// Judges `eac online judge --judge` can pick from. - pub judges: Vec, - pub args_schema: Option, } impl Discovered { /// The dataset for a run in mode, with the cases it picked. Panics if /// the dataset isn't defined in mode. pub fn to_dataset(&self, mode: Mode, cases: Vec) -> Dataset { - let (runtime, agent, code) = match mode { - Mode::Offline => { - let o = self.offline.as_ref().expect("an offline dataset"); - (&o.runtime, &o.agent, &o.code) - } - Mode::Online => { - let o = self.online.as_ref().expect("an online dataset"); - (&o.runtime, &o.agent, &o.code) - } - }; Dataset { - code: code.clone(), - runtime: runtime.clone(), - name: self.name.clone(), - agent: agent.clone(), + code: self.config.code(mode), + runtime: self.config.runtime.clone(), + name: self.config.name.clone(), + agent: self.config.agent.clone(), args: Object::new(), judges: vec![], judge_args: Object::new(), @@ -74,93 +34,47 @@ impl Discovered { cases, } } - } impl Engine { - /// Imports each dataset's code. This is the only call that asks a worker - /// what a dataset has, and later phases work from the manifest. Datasets - /// come back in the order given, offline ones first. - pub fn discover( - &mut self, - offline: &[OfflineDataset], - online: &[OnlineDataset], - ) -> Result> { - let mut found: Vec = Vec::new(); - for d in offline { - let code = d.code(); - let res = self.discover_one(&d.runtime, &code)?; - found.push(Discovered { - name: d.name.clone(), - file: d.file.clone(), - offline: Some(OfflineInfo { - runtime: d.runtime.clone(), - agent: d.agent.clone(), - code, - cases: res.cases, - comparisons: d.comparisons.clone(), - shard_config: d.shard_config, - args_schema: res.args_schema, - }), - online: None, - judge_args_schemas: res.judge_args_schemas, - }); - } - for d in online { - let code = d.code(); - let res = self.discover_one(&d.runtime, &code)?; - let info = OnlineInfo { - runtime: d.runtime.clone(), - agent: d.agent.clone(), - code, - judges: d.judges.iter().map(|j| j.name.clone()).collect(), - args_schema: res.args_schema, - }; - match found.iter_mut().find(|f| f.name == d.name) { - Some(f) => { - f.online = Some(info); - f.judge_args_schemas.extend(res.judge_args_schemas); - } - None => found.push(Discovered { - name: d.name.clone(), - file: d.file.clone(), - offline: None, - online: Some(info), - judge_args_schemas: res.judge_args_schemas, - }), + /// Imports each section of each dataset's code, so broken code fails + /// early, and gets the offline cases. This is the only call that asks a + /// worker what a dataset has; later phases work from the manifest. + pub fn discover(&mut self, datasets: &[DatasetConfig]) -> Result> { + let mut found = Vec::new(); + for config in datasets { + let mut cases = vec![]; + if config.offline.is_some() { + cases = self.discover_one(config, Mode::Offline)?.cases; + } + if config.online.is_some() { + self.discover_one(config, Mode::Online)?; } + found.push(Discovered { config: config.clone(), cases }); } Ok(found) } - fn discover_one(&mut self, runtime: &str, code: &DatasetRef) -> Result { - let mode = match code.mode { - Mode::Offline => "offline", - Mode::Online => "online", - }; - self.call( - runtime, - "discover", - DiscoverParams { dataset: code }, - ) - .with_context(|| format!("discovering {mode} dataset {}", code.name)) + fn discover_one(&mut self, config: &DatasetConfig, mode: Mode) -> Result { + let params = DiscoverParams { dataset: &config.code(mode) }; + (self.call(&config.runtime, "discover", params)) + .with_context(|| format!("discovering {} dataset {}", mode.as_str(), config.name)) } - /// Has the dataset's SDK check args and judge args before any work - /// starts, and stores the args with the runner's defaults filled in, - /// along with what the runner and judges need. - pub fn validate_args(&mut self, d: &mut Dataset, mode: Mode, args: &Object) -> Result<()> { + /// Stores the run's args on d, along with what its runner and judges + /// need, which the dataset's SDK reports. The SDK may reject the args + /// before any work starts. + pub fn validate_args(&mut self, d: &mut Dataset, args: &Object) -> Result<()> { let params = ArgsValidateParams { dataset: &d.code, - mode, + mode: d.code.mode, args, judges: &d.judges, judge_args: &d.judge_args, }; - let res: ArgsValidateResult = self - .call(&d.runtime, "args.validate", params) + let res: ArgsValidateResult = (self.call(&d.runtime, "args.validate", params)) .with_context(|| format!("invalid --args or --judge-args for {}", d.name))?; - d.args = res.args.unwrap_or_else(|| args.clone()); + d.args = args.clone(); d.runner_credentials = res.runner_credentials; d.judge_credentials = res.judge_credentials; Ok(()) diff --git a/core/src/eac/phases/judge.rs b/core/src/eac/phases/judge.rs index 27961a5..1dd45a3 100644 --- a/core/src/eac/phases/judge.rs +++ b/core/src/eac/phases/judge.rs @@ -6,11 +6,11 @@ use anyhow::{anyhow, Result}; use super::seed::handles_for; use crate::eac::{ - aggregate, case_result, run_result, status_for, Engine, Manifest, Run, RunResult, Scored, - Seeds, Status, Summary, TraceFile, + aggregate, case_result, run_result, status_for, CaseResult, Dataset, Engine, Manifest, Output, + Run, RunResult, Scored, Seeds, Status, Summary, TraceFile, }; -use crate::schema::{CaseJudgeParams, CaseJudgeResult, OnlineJudgeParams, Record}; -use crate::worker::{each, Interrupted}; +use crate::schema::{Case, CaseJudgeParams, CaseJudgeResult, OnlineJudgeParams}; +use crate::worker::{each, Interrupted, Worker}; impl Engine { /// Scores every recorded output, passing judges the case's seeds and the @@ -18,11 +18,7 @@ impl Engine { /// saved for the next one. Judges up to the dataset's concurrency at a /// 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 seeds = if m.online { Seeds::default() } else { run.read_seeds()? }; let mut summary = Summary { run_id: run.id.clone(), created_at: m.created_at, @@ -31,12 +27,10 @@ impl Engine { }; let mut results = Vec::new(); let start = Instant::now(); - let cancel = self.cancel; for d in &m.datasets { let dataset_start = Instant::now(); let n = self.concurrency(d); - let workers = self.workers.first(&d.runtime, n)?; let jobs = d.cases.iter().map(|c| { let out = run.read_output(&d.name, &c.name).map_err(|_| { anyhow!( @@ -47,99 +41,17 @@ impl Engine { })?; Ok((c, out, run.read_trace(&d.name, &c.name))) }); - let judged = each(workers, cancel, jobs, |worker, (c, out, mut trace)| { - let saved = trace.as_ref().map(|t| &t.trace); - let agent = d.agent.as_deref(); - - let res: Result = if m.online { - let record = Record { - id: c.name.clone(), - conversation_id: out.conversation_id.clone(), - input: out.input.clone(), - output: out.output.clone(), - }; - let params = OnlineJudgeParams { - dataset: &d.code, - record, - judges: &d.judges, - judge_args: &d.judge_args, - trace: saved, - agent, - }; - worker.call(cancel, "online.judge", params) - } else { - let params = CaseJudgeParams { - dataset: &d.code, - case: c, - judges: &d.judges, - output: &out.output, - error: Some(out.error.as_str()).filter(|e| !e.is_empty()), - seeds: handles_for(&seeds, d, c, false)?, - judge_args: &d.judge_args, - trace: saved, - conversation_id: out.conversation_id.as_deref(), - agent, - started_at: out.started_at, - ended_at: out.ended_at, - }; - worker.call(cancel, "case.judge", params) - }; - - let mut scored = Scored { - dataset: d.name.clone(), - case: c.name.clone(), - status: Status::Error, - scores: vec![], - error: out.error.clone(), - duration_seconds: out.duration_seconds, - }; - match res { - Ok(res) => { - // Saved, so judging again doesn't fetch it again. - if !res.trace.is_null() { - let fetched = TraceFile { - conversation_id: out.conversation_id.clone().unwrap_or_default(), - trace: res.trace, - metrics: res.trace_metrics, - }; - run.write_trace(&d.name, &c.name, &fetched)?; - trace = Some(fetched); - } - scored.status = status_for(&res.scores, &out.error); - scored.scores = res.scores; - } - Err(e) if e.is::() => return Err(e), - Err(e) => { - if scored.error.is_empty() { - scored.error = format!("judge failed: {e:#}"); - } - } - } - run.write_scored(&scored)?; - if !m.online { - detail!("{}/{} judged", d.name, c.name); - } - let row = case_result(c, &out, &scored, trace.and_then(|t| t.metrics)); - Ok((scored, row)) + 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 mut rows = Vec::new(); - for (scored, row) in judged { - summary.total += 1; - match scored.status { - Status::Passed => summary.passed += 1, - Status::Error => summary.errors += 1, - Status::Failed => summary.failed += 1, - } - rows.push(row); - summary.results.push(scored); + let mut cases = Vec::new(); + for (scored, case) in judged { + summary.add(scored); + cases.push(case); } - results.push(run_result( - m, - d, - rows, - dataset_start.elapsed().as_secs_f64(), - )); + results.push(run_result(m, d, cases, dataset_start.elapsed().as_secs_f64())); } summary.duration_seconds = start.elapsed().as_secs_f64(); @@ -149,3 +61,101 @@ impl Engine { Ok((summary, results)) } } + +/// What judging a dataset's cases needs, shared by every worker's thread. +struct Judging<'a> { + run: &'a Run, + online: bool, + d: &'a Dataset, + seeds: &'a Seeds, +} + +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)> { + let (run, d) = (self.run, self.d); + 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![], + error: out.error.clone(), + duration_seconds: out.duration_seconds, + }; + match res { + Ok(res) => { + // Saved, so judging again doesn't fetch it again. + if !res.trace.is_null() { + let fetched = TraceFile { + conversation_id: out.conversation_id.clone().unwrap_or_default(), + trace: res.trace, + metrics: res.trace_metrics, + }; + run.write_trace(&d.name, &c.name, &fetched)?; + trace = Some(fetched); + } + scored.status = status_for(&res.scores, &out.error); + scored.scores = res.scores; + } + 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); + } + let case = case_result(c, &out, &scored, trace.and_then(|t| t.metrics)); + Ok((scored, case)) + } + + /// Asks the worker to judge the case with its recorded output, along with + /// its seeds offline. + fn call( + &self, + worker: &mut Worker, + c: &Case, + out: &Output, + saved_trace: Option<&serde_json::Value>, + ) -> Result { + let d = self.d; + let case = Case { + output: out.output.clone(), + conversation_id: out.conversation_id.clone(), + ..c.clone() + }; + if self.online { + let params = OnlineJudgeParams { + dataset: &d.code, + case, + judges: &d.judges, + judge_args: &d.judge_args, + trace: saved_trace, + agent: d.agent.as_deref(), + }; + return worker.call("online.judge", params); + } + let params = CaseJudgeParams { + dataset: &d.code, + case, + judges: &d.judges, + error: Some(out.error.as_str()).filter(|e| !e.is_empty()), + seeds: handles_for(self.seeds, d, c, false)?, + judge_args: &d.judge_args, + trace: saved_trace, + agent: d.agent.as_deref(), + started_at: out.started_at, + ended_at: out.ended_at, + }; + worker.call("case.judge", params) + } +} diff --git a/core/src/eac/phases/mod.rs b/core/src/eac/phases/mod.rs index f63b562..66254a0 100644 --- a/core/src/eac/phases/mod.rs +++ b/core/src/eac/phases/mod.rs @@ -1,6 +1,5 @@ -//! The engine's phases, each adding methods to `Engine`. A run discovers -//! datasets, checks the credentials its phases need, seeds, collects outputs -//! by running cases or fetching online records, then judges. +//! The phases a run goes through, each a method on Engine: discover, seed, +//! collect and judge, plus the credential checks that come before them. mod collect; mod credentials; @@ -8,5 +7,5 @@ mod discover; mod judge; mod seed; -pub use credentials::Phase; -pub use discover::{Discovered, OfflineInfo}; +pub use credentials::{Phase, ALL_PHASES}; +pub use discover::Discovered; diff --git a/core/src/eac/phases/seed.rs b/core/src/eac/phases/seed.rs index 84e7f55..656eb90 100644 --- a/core/src/eac/phases/seed.rs +++ b/core/src/eac/phases/seed.rs @@ -1,22 +1,22 @@ -//! Sets up each fixture once, reuses cached ones, and tears down and prunes -//! them. - use std::collections::{BTreeMap, HashSet}; use anyhow::{bail, Result}; 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, Seed, SeedSetupParams, SeedSetupResult, SeedTeardownParams}; +use crate::eac::{ + read_seed_cache, seed_id, write_seed_cache, Dataset, Engine, Manifest, SeedEntry, Seeds, +}; +use crate::schema::{Case, Handle, SeedSetupParams, SeedSetupResult, SeedTeardownParams}; impl Engine { - /// Sets up each distinct fixture once. Cached seeds come from the local - /// seed cache before being set up afresh, and the worker may load them - /// from the seed's own cache instead of setting them up. + /// Sets up every seed the run's cases need, once per seed id. Cached seeds + /// come from the seed cache when it has them, and are added to it when + /// it doesn't. pub fn seed(&mut self, m: &Manifest) -> Result { let artifacts = self.cfg.artifacts.clone(); let mut cache = read_seed_cache(&artifacts)?; let mut out = Seeds::default(); + for d in &m.datasets { for seed in d.cases.iter().flat_map(|c| &c.seeds) { let id = seed_id(&d.runtime, seed); @@ -24,39 +24,33 @@ impl Engine { continue; } let short: String = seed.key.chars().take(8).collect(); - if seed.cache { - if let Some(entry) = cache.seeds.get(&id) { - info!("{} ({short}) cached", seed.name); - out.seeds.insert(id, entry.clone()); - continue; - } + if let Some(entry) = cache.seeds.get(&id).filter(|_| seed.cache) { + info!("{} ({short}) cached", seed.name); + out.seeds.insert(id, entry.clone()); + continue; } - info!( - "{} ({short}){}", - seed.name, - if seed.cache { "" } else { " uncached" } - ); - let params = SeedSetupParams { - dataset: &d.code, - seed, - }; - let res = - self.call::(&d.runtime, "seed.setup", params); - let res = match res { + info!("{} ({short}){}", seed.name, if seed.cache { "" } else { " uncached" }); + let params = SeedSetupParams { dataset: &d.code, seed }; + let res: SeedSetupResult = match self.call(&d.runtime, "seed.setup", params) { Ok(res) => res, Err(e) => { // Don't leak the uncached seeds this run already set up. - let fresh: Vec = - out.seeds.values().filter(|e| !e.cached).cloned().collect(); - let _ = self.teardown(&fresh); + let _ = self.teardown(out.seeds.values().filter(|e| !e.cached)); return Err(e.context(format!("seeding {}", seed.name))); } }; if res.from_cache { detail!("{} came from its own cache", seed.name); } - let entry = new_entry(d, seed, res.handle); + let entry = SeedEntry { + seed: seed.clone(), + runtime: d.runtime.clone(), + dataset: d.name.clone(), + code: d.code.clone(), + handle: res.handle, + cached: seed.cache, + }; if seed.cache { // Saved straight away, so a later failure can't lose track of it. cache.seeds.insert(id.clone(), entry.clone()); @@ -71,65 +65,55 @@ impl Engine { Ok(out) } - /// Best effort. One failure doesn't stop the rest. + /// Tears down each seed, best effort: one failure doesn't stop the rest, + /// and the first is returned. pub fn teardown<'a>(&mut self, entries: impl IntoIterator) -> Result<()> { let mut first_err = None; for entry in entries { - match self.teardown_one(entry) { - Ok(()) => detail!("tore down {}", entry.seed.name), - Err(e) => { - warning!("tearing down {}: {e:#}", entry.seed.name); - first_err.get_or_insert(e); - } + if let Err(e) = self.teardown_one(entry) { + first_err.get_or_insert(e); } } first_err.map_or(Ok(()), Err) } - fn teardown_one(&mut self, entry: &SeedEntry) -> Result<()> { - let params = SeedTeardownParams { - dataset: &entry.code, - seed: &entry.seed, - handle: &entry.handle, - }; - self.call::(&entry.runtime, "seed.teardown", params)?; - Ok(()) - } - /// Tears down the locally cached seeds whose ids aren't in `used`, or all /// of them if `used` is None. Seeds that fail to tear down stay cached. /// Returns how many were removed. pub fn prune(&mut self, used: Option<&HashSet>) -> Result { let artifacts = self.cfg.artifacts.clone(); let mut cache = read_seed_cache(&artifacts)?; - let mut candidates = cache.seeds.clone(); - candidates.retain(|id, _| used.is_none_or(|used| !used.contains(id))); - self.check_seed_credentials(candidates.values())?; - let mut first_err = None; - let mut removed = 0; - for (id, entry) in candidates { - if let Err(e) = self.teardown_one(&entry) { - warning!("tearing down {}: {e:#}", entry.seed.name); - first_err.get_or_insert(e); - continue; + let mut unused = cache.seeds.clone(); + unused.retain(|id, _| used.is_none_or(|used| !used.contains(id))); + self.check_seed_credentials(unused.values())?; + + let (mut removed, mut first_err) = (0, None); + for (id, entry) in unused { + match self.teardown_one(&entry) { + Ok(()) => { + cache.seeds.remove(&id); + removed += 1; + } + Err(e) => { + first_err.get_or_insert(e); + } } - detail!("tore down {} ({})", entry.seed.name, entry.dataset); - cache.seeds.remove(&id); - removed += 1; } write_seed_cache(&artifacts, &cache)?; first_err.map_or(Ok(removed), Err) } -} -fn new_entry(d: &Dataset, seed: &Seed, handle: Handle) -> SeedEntry { - SeedEntry { - seed: seed.clone(), - runtime: d.runtime.clone(), - dataset: d.name.clone(), - code: d.code.clone(), - handle, - cached: seed.cache, + fn teardown_one(&mut self, entry: &SeedEntry) -> Result<()> { + let params = + SeedTeardownParams { dataset: &entry.code, seed: &entry.seed, handle: &entry.handle }; + match self.call::(&entry.runtime, "seed.teardown", params) { + Ok(_) => detail!("tore down {} ({})", entry.seed.name, entry.dataset), + Err(e) => { + warning!("tearing down {}: {e:#}", entry.seed.name); + return Err(e); + } + } + Ok(()) } } diff --git a/core/src/eac/report/color.rs b/core/src/eac/report/color.rs deleted file mode 100644 index 9097964..0000000 --- a/core/src/eac/report/color.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! Colors are only used on a terminal and when NO_COLOR is unset. - -use std::io::IsTerminal; -use std::sync::LazyLock; - -static COLOR: LazyLock = LazyLock::new(|| { - std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty()) && std::io::stderr().is_terminal() -}); - -pub const RESET: &str = "\x1b[0m"; -pub const DIM: &str = "\x1b[2m"; -pub const BOLD: &str = "\x1b[1m"; -pub const GREEN: &str = "\x1b[32m"; -pub const RED: &str = "\x1b[31m"; -pub const YELLOW: &str = "\x1b[33m"; - -pub fn paint(color: &str, s: &str) -> String { - if *COLOR { - format!("{color}{s}{RESET}") - } else { - s.to_string() - } -} diff --git a/core/src/eac/report/lines.rs b/core/src/eac/report/lines.rs deleted file mode 100644 index 32d133d..0000000 --- a/core/src/eac/report/lines.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! One-line output, such as phase headings, the info!, detail! and warning! -//! macros, and worker output. - -use std::fmt; - -use super::color::{paint, BOLD, DIM, GREEN, RED, YELLOW}; - -macro_rules! info { - ($($arg:tt)*) => { $crate::eac::report::info(format_args!($($arg)*)) }; -} - -macro_rules! detail { - ($($arg:tt)*) => { $crate::eac::report::detail(format_args!($($arg)*)) }; -} - -macro_rules! warning { - ($($arg:tt)*) => { $crate::eac::report::warning(format_args!($($arg)*)) }; -} - -pub fn phase(name: &str) { - eprintln!("\n{}", paint(BOLD, &name.to_uppercase())); -} - -pub fn info(args: fmt::Arguments) { - eprintln!(" {args}"); -} - -pub fn detail(args: fmt::Arguments) { - eprintln!(" {}", paint(DIM, &args.to_string())); -} - -pub fn warning(args: fmt::Arguments) { - eprintln!(" {}", paint(YELLOW, &args.to_string())); -} - -/// A check's result, such as whether a credential is set up. -pub fn checked(ok: bool, what: &str) { - let mark = if ok { paint(GREEN, "✓") } else { paint(RED, "✗") }; - eprintln!(" {mark} {what}"); -} - -pub fn worker_log(level: &str, line: &str) { - let color = if level == "warn" { YELLOW } else { DIM }; - eprintln!(" {}", paint(color, line)); -} - -pub fn first_line(s: &str) -> &str { - s.split('\n').next().unwrap_or_default() -} diff --git a/core/src/eac/report/mod.rs b/core/src/eac/report/mod.rs deleted file mode 100644 index 93846fc..0000000 --- a/core/src/eac/report/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! Terminal output goes to stderr so stdout stays clean for piping. - -#[macro_use] -mod lines; -mod color; -mod format; -mod tables; - -pub use lines::{checked, detail, first_line, info, phase, warning, worker_log}; -pub use tables::{print_comparison, print_summary}; diff --git a/core/src/eac/run/cases.rs b/core/src/eac/run/cases.rs index 0d4d5b2..259a9f8 100644 --- a/core/src/eac/run/cases.rs +++ b/core/src/eac/run/cases.rs @@ -1,19 +1,22 @@ //! The output, agent trace, scores and status a run records for each case. +use chrono::{DateTime, Utc}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::Value; -use chrono::{DateTime, Utc}; - use crate::schema::{is_empty, nullable, Metrics, Object, Score}; +/// `passed` when every score is 1, `failed` when any is lower, `error` when +/// the runner or a judge failed, and `skipped` when there are no scores. Null +/// scores don't count. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "lowercase")] pub enum Status { Passed, Failed, Error, + Skipped, } impl Status { @@ -22,6 +25,7 @@ impl Status { Status::Passed => "passed", Status::Failed => "failed", Status::Error => "error", + Status::Skipped => "skipped", } } } @@ -34,17 +38,13 @@ pub struct Output { pub input: Option, #[serde(default)] pub output: Option, - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "String::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "String::is_empty")] pub error: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub conversation_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub metrics: Option, - /// Absent for fetched production records. + /// Absent for collected production runs. #[serde(default, skip_serializing_if = "Option::is_none")] pub started_at: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -69,33 +69,25 @@ pub struct Scored { pub status: Status, #[serde(default, deserialize_with = "nullable")] pub scores: Vec, - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "String::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "String::is_empty")] pub error: String, #[serde(default)] pub duration_seconds: f64, } -/// An error always wins, otherwise there must be at least one non-null score -/// and all of them must be 1.0. +/// 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() { - return Status::Error; + Status::Error + } else if scores.is_empty() { + Status::Skipped + } else if scores.iter().all(|&s| s == 1.0) { + Status::Passed + } else { + Status::Failed } - let mut scored = 0; - for score in scores.iter().filter_map(|s| s.score) { - scored += 1; - if score != 1.0 { - return Status::Failed; - } - } - if scored == 0 { - return Status::Failed; - } - Status::Passed } #[cfg(test)] @@ -103,23 +95,17 @@ mod tests { use super::*; fn score(value: Option) -> Score { - Score { - name: "j".into(), - score: value, - ..Default::default() - } + Score { name: "j".into(), score: value, ..Default::default() } } #[test] fn status() { assert_eq!(status_for(&[score(Some(1.0))], ""), Status::Passed); - assert_eq!( - status_for(&[score(Some(1.0)), score(None)], ""), - Status::Passed - ); + assert_eq!(status_for(&[score(Some(1.0)), score(None)], ""), Status::Passed); assert_eq!(status_for(&[score(Some(0.5))], ""), Status::Failed); - assert_eq!(status_for(&[score(None)], ""), Status::Failed); - assert_eq!(status_for(&[], ""), Status::Failed); + assert_eq!(status_for(&[score(None)], ""), Status::Skipped); + assert_eq!(status_for(&[], ""), Status::Skipped); + assert_eq!(status_for(&[], "boom"), Status::Error); assert_eq!(status_for(&[score(Some(1.0))], "boom"), Status::Error); } } diff --git a/core/src/eac/run/dir.rs b/core/src/eac/run/dir.rs index 5509df4..3762ea3 100644 --- a/core/src/eac/run/dir.rs +++ b/core/src/eac/run/dir.rs @@ -19,6 +19,7 @@ pub struct Run { pub dir: PathBuf, } +/// The run id that opens the most recent run. pub const LATEST: &str = "latest"; impl Run { @@ -33,11 +34,7 @@ impl Run { i += 1; } fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; - let id = dir - .file_name() - .expect("run dir has a name") - .to_string_lossy() - .into_owned(); + let id = dir.file_name().expect("run dir has a name").to_string_lossy().into_owned(); Ok(Run { id, dir }) } @@ -45,16 +42,11 @@ impl Run { pub fn open(artifacts: &Path, id: &str) -> Result { let root = artifacts.join("runs"); let id = if id.is_empty() || id == LATEST { - let mut ids: Vec = fs::read_dir(&root) - .into_iter() - .flatten() - .flatten() - .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) - .map(|e| e.file_name().to_string_lossy().into_owned()) - .collect(); + let entries = fs::read_dir(&root).into_iter().flatten().flatten(); + let dirs = entries.filter(|e| e.file_type().is_ok_and(|t| t.is_dir())); // Ids are timestamps, so the last in order is the latest. - ids.sort(); - ids.pop().ok_or_else(|| { + let latest = dirs.map(|e| e.file_name().to_string_lossy().into_owned()).max(); + latest.ok_or_else(|| { anyhow!( "no runs yet in {}: start one with 'eac offline run' or 'eac online run'", root.display() @@ -70,24 +62,21 @@ impl Run { Ok(Run { id, dir }) } - fn path(&self, parts: &[&str]) -> PathBuf { - parts.iter().fold(self.dir.clone(), |p, part| p.join(part)) - } - + /// //.json, e.g. outputs/chat/greets.json. fn case_path(&self, kind: &str, dataset: &str, case: &str) -> PathBuf { - self.path(&[kind, dataset, &format!("{case}.json")]) + self.dir.join(kind).join(dataset).join(format!("{case}.json")) } pub fn write_manifest(&self, m: &Manifest) -> Result<()> { - write_json(&self.path(&["manifest.json"]), m) + write_json(&self.dir.join("manifest.json"), m) } pub fn write_seeds(&self, s: &Seeds) -> Result<()> { - write_json(&self.path(&["seeds.json"]), s) + write_json(&self.dir.join("seeds.json"), s) } pub fn write_summary(&self, s: &Summary) -> Result<()> { - write_json(&self.path(&["summary.json"]), s) + write_json(&self.dir.join("summary.json"), s) } pub fn write_output(&self, o: &Output) -> Result<()> { @@ -104,26 +93,19 @@ impl Run { pub fn write_results(&self, results: &[RunResult]) -> Result<()> { for r in results { - write_json( - &self.path(&["results", &format!("{}.json", r.dataset_name)]), - r, - )?; + write_json(&self.dir.join("results").join(format!("{}.json", r.dataset_name)), r)?; } Ok(()) } pub fn read_manifest(&self) -> Result { - read_json(&self.path(&["manifest.json"])) + read_json(&self.dir.join("manifest.json")) .with_context(|| format!("run {} has no manifest", self.id)) } /// Returns no seeds if the run was never seeded. pub fn read_seeds(&self) -> Result { - let path = self.path(&["seeds.json"]); - if !path.exists() { - return Ok(Seeds::default()); - } - read_json(&path) + read_json_or_default(&self.dir.join("seeds.json")) } pub fn read_output(&self, dataset: &str, case: &str) -> Result { @@ -136,7 +118,7 @@ impl Run { } pub fn read_scores(&self) -> Result> { - let mut out = read_all::(&self.path(&["scores"]))?; + 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) } @@ -176,3 +158,11 @@ pub(super) fn read_json(path: &Path) -> Result { let raw = fs::read(path).with_context(|| path.display().to_string())?; serde_json::from_slice(&raw).with_context(|| path.display().to_string()) } + +/// Like read_json, but a missing file reads as the default. +pub(super) fn read_json_or_default(path: &Path) -> Result { + if !path.exists() { + return Ok(T::default()); + } + read_json(path) +} diff --git a/core/src/eac/run/manifest.rs b/core/src/eac/run/manifest.rs index 42d297c..8cf70fd 100644 --- a/core/src/eac/run/manifest.rs +++ b/core/src/eac/run/manifest.rs @@ -7,14 +7,14 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::eac::{Shard, Source}; -use crate::schema::{nullable, Case, Credential, DatasetRef, Object}; +use crate::schema::{nullable, Case, Credential, DatasetRef, Mode, Object}; #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] pub struct Manifest { #[serde(default)] pub id: String, pub created_at: DateTime, - /// Judges production records instead of running cases. + /// Judges collected production runs instead of running cases. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub online: bool, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -35,7 +35,17 @@ pub struct Manifest { pub datasets: Vec, } -/// The production records an online run fetched. +impl Manifest { + pub fn mode(&self) -> Mode { + if self.online { + Mode::Online + } else { + Mode::Offline + } + } +} + +/// The window of production runs an online run collected. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct Window { pub since: String, @@ -58,42 +68,34 @@ pub struct Dataset { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub agent: Option, - /// Validated --args, with the runner's defaults filled in. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Object::is_empty" - )] + /// --args, as given. + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Object::is_empty")] pub args: Object, /// The online judges this run picked, or a comparison's judges, which /// replace each offline case's own. Kept so a re-judge uses the same ones. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Vec::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub judges: Vec, /// --judge-args by judge name, kept so a re-judge uses the same ones. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Object::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Object::is_empty")] pub judge_args: Object, /// What the runner needs with these args, checked before collecting. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Vec::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub runner_credentials: Vec, /// What each judge needs, by judge name, checked before judging. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "BTreeMap::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "BTreeMap::is_empty")] pub judge_credentials: BTreeMap>, #[serde(default, deserialize_with = "nullable")] pub cases: Vec, } + +impl Dataset { + /// The judges the run scores with: its own, which replace each case's, or + /// else every case's. + pub fn used_judges(&self) -> Vec<&String> { + if self.judges.is_empty() { + self.cases.iter().flat_map(|c| &c.judges).collect() + } else { + self.judges.iter().collect() + } + } +} diff --git a/core/src/eac/run/results.rs b/core/src/eac/run/results.rs index 7f7b7db..dda27e6 100644 --- a/core/src/eac/run/results.rs +++ b/core/src/eac/run/results.rs @@ -1,7 +1,7 @@ -//! Each dataset's results in the shape of seer's RunResult, so a script can -//! send them to the evals platform as they are. - -use std::collections::BTreeSet; +//! results/.json: each dataset's results, the one file in a run's +//! directory meant for other tools. `make generate` writes its JSON Schema to +//! schemas/results.schema.json, which seer's evals and the evals platform +//! follow too. The run's other files are eac's own and may change. use chrono::{DateTime, Utc}; use schemars::JsonSchema; @@ -11,49 +11,60 @@ use serde_json::{json, Value}; use super::cases::{Output, Scored, Status}; use super::manifest::{Dataset, Manifest}; use crate::eac::Source; -use crate::schema::{Case, Metrics, Object, Score}; +use crate::schema::{schema_settings, Case, Metrics, Object, Score}; + +/// 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 = 2; +/// The results of judging one dataset in one run, saved as +/// results/.json in the run's directory. #[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. + #[schemars(extend("const" = RESULTS_VERSION))] + pub schema_version: u32, pub dataset_name: String, + /// When the run started. pub created_at: DateTime, - /// The cases. Seer's API calls them scenarios. - pub scenarios: Vec, + /// Every case judged, in the dataset's order. + pub cases: Vec, + /// How long judging the dataset took. pub duration_seconds: f64, + /// What sets this run apart from others of the same dataset, like the + /// variant, args and --meta values. pub metadata: Object, pub source: Source, - pub summary: RunSummary, } +/// One case: what the runner returned and how the judges scored it. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct CaseResult { pub name: String, pub status: Status, pub input: Object, + /// Null if the runner failed. pub output: 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 conversation_id: Option, - /// The output's "attributes" object, plus the case's splits. + /// The output's `attributes` object, plus the case's `splits`. pub attributes: Object, + /// When the runner started. Null for online runs. pub start_time: Option>, + /// When the runner finished. Null for online runs. pub end_time: Option>, - pub cost_usd: f64, + /// How long the runner took. 0 for online runs. pub duration_seconds: f64, } -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] -pub struct RunSummary { - pub total: usize, - pub passed: usize, - pub failed: usize, - pub errors: usize, - /// Judges that produced at least one score. - pub evaluators: Vec, -} - /// Metrics from the case's trace win over what the runner reported. pub fn case_result( case: &Case, @@ -61,9 +72,7 @@ pub fn case_result( scored: &Scored, trace_metrics: Option, ) -> CaseResult { - let metrics = trace_metrics - .or_else(|| out.metrics.clone()) - .unwrap_or_default(); + let metrics = trace_metrics.or_else(|| out.metrics.clone()).unwrap_or_default(); let mut attributes = out .output .as_ref() @@ -82,7 +91,6 @@ pub fn case_result( expected_output: case.expected_output.clone(), error: Some(scored.error.clone()).filter(|e| !e.is_empty()), scores: scored.scores.clone(), - cost_usd: metrics.cost_usd, otel_metrics: metrics, conversation_id: out.conversation_id.clone(), attributes, @@ -95,36 +103,22 @@ pub fn case_result( pub fn run_result( m: &Manifest, d: &Dataset, - scenarios: Vec, + cases: Vec, duration_seconds: f64, ) -> RunResult { - let count = |status| scenarios.iter().filter(|c| c.status == status).count(); - let evaluators: BTreeSet<&str> = scenarios - .iter() - .flat_map(|c| &c.scores) - .filter(|s| s.score.is_some()) - .map(|s| s.name.as_str()) - .collect(); - let summary = RunSummary { - total: scenarios.len(), - passed: count(Status::Passed), - failed: count(Status::Failed), - errors: count(Status::Error), - evaluators: evaluators.into_iter().map(String::from).collect(), - }; RunResult { + schema_version: RESULTS_VERSION, dataset_name: d.name.clone(), created_at: m.created_at, duration_seconds, metadata: metadata(m, d), source: m.source.clone(), - summary, - scenarios, + cases, } } /// What distinguishes this run from others of the same dataset, using seer's -/// metadata keys where it has them. +/// metadata keys where it has them. Where the run came from is in `source`. fn metadata(m: &Manifest, d: &Dataset) -> Object { let mut meta = Object::new(); let mut put = |key: &str, value: Value| { @@ -158,13 +152,17 @@ fn metadata(m: &Manifest, d: &Dataset) -> Object { if !d.judge_args.is_empty() { put("judge_args", Value::Object(d.judge_args.clone())); } - let source = &m.source; - put("branch_name", json!(source.branch)); - put("sha", json!(source.sha)); - put("pr_number", json!(source.pr_number.map(|n| n.to_string()))); - put("ci_run_url", json!(source.run_url)); for (key, value) in &m.metadata { put(key, json!(value)); } meta } + +/// The JSON Schema of results/.json, as eac writes it. +pub fn results_schema() -> Value { + schema_settings() + .for_serialize() + .into_generator() + .into_root_schema_for::() + .to_value() +} diff --git a/core/src/eac/run/seeds.rs b/core/src/eac/run/seeds.rs index cb01ef4..7806f89 100644 --- a/core/src/eac/run/seeds.rs +++ b/core/src/eac/run/seeds.rs @@ -7,7 +7,7 @@ use std::path::Path; use anyhow::Result; use serde::{Deserialize, Serialize}; -use super::dir::{read_json, write_json}; +use super::dir::{read_json_or_default, write_json}; use crate::schema::{nullable, DatasetRef, Handle, Seed}; /// Keyed by seed_id, so cases needing the same fixture share one entry. @@ -42,11 +42,7 @@ pub fn seed_id(runtime: &str, seed: &Seed) -> String { const SEED_CACHE: &str = "seed-cache.json"; pub fn read_seed_cache(artifacts: &Path) -> Result { - let path = artifacts.join(SEED_CACHE); - if !path.exists() { - return Ok(Seeds::default()); - } - read_json(&path) + read_json_or_default(&artifacts.join(SEED_CACHE)) } pub fn write_seed_cache(artifacts: &Path, seeds: &Seeds) -> Result<()> { diff --git a/core/src/eac/run/summary.rs b/core/src/eac/run/summary.rs index fc60d2f..0a5da96 100644 --- a/core/src/eac/run/summary.rs +++ b/core/src/eac/run/summary.rs @@ -1,12 +1,10 @@ //! summary.json: a judged run's totals, and each judge's mean for online runs. -use std::collections::HashMap; - use chrono::{DateTime, Utc}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use super::cases::Scored; +use super::cases::{Scored, Status}; #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] pub struct Summary { @@ -15,6 +13,9 @@ pub struct Summary { pub passed: usize, 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. @@ -28,14 +29,22 @@ pub struct Summary { } impl Summary { + /// Counts a judged case. + pub fn add(&mut self, scored: Scored) { + self.total += 1; + match scored.status { + Status::Passed => self.passed += 1, + Status::Failed => self.failed += 1, + Status::Error => self.errors += 1, + Status::Skipped => self.skipped += 1, + } + self.results.push(scored); + } + /// 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(); + let scores: Vec = + self.results.iter().flat_map(|r| &r.scores).filter_map(|s| s.score).collect(); (!scores.is_empty()).then(|| scores.iter().sum::() / scores.len() as f64) } } @@ -47,23 +56,20 @@ pub struct JudgeStat { pub count: usize, } +/// 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(); - let mut index: HashMap<&str, usize> = HashMap::new(); - for s in scored { - for sc in &s.scores { - let Some(score) = sc.score else { continue }; - let i = *index.entry(&sc.name).or_insert_with(|| { - stats.push(JudgeStat { - name: sc.name.clone(), - mean: 0.0, - count: 0, - }); + for sc in scored.iter().flat_map(|s| &s.scores) { + let Some(score) = sc.score else { continue }; + let i = match stats.iter().position(|s| s.name == sc.name) { + Some(i) => i, + None => { + stats.push(JudgeStat { name: sc.name.clone(), mean: 0.0, count: 0 }); stats.len() - 1 - }); - stats[i].mean += score; - stats[i].count += 1; - } + } + }; + stats[i].mean += score; + stats[i].count += 1; } for stat in &mut stats { stat.mean /= stat.count as f64; @@ -74,15 +80,10 @@ pub fn aggregate(scored: &[Scored]) -> Vec { #[cfg(test)] mod tests { use super::*; - use crate::eac::Status; use crate::schema::Score; fn score(value: Option) -> Score { - Score { - name: "j".into(), - score: value, - ..Default::default() - } + Score { name: "j".into(), score: value, ..Default::default() } } #[test] diff --git a/core/src/eac/select.rs b/core/src/eac/select.rs index 82e81c1..9943bf8 100644 --- a/core/src/eac/select.rs +++ b/core/src/eac/select.rs @@ -5,8 +5,10 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use super::{Dataset, Discovered}; +use crate::report::join_or_none; use crate::schema::{Case, Mode}; +/// Which offline cases a command runs, from --case, --split and the shard flags. #[derive(Clone, Debug, Default)] pub struct Selection { pub cases: Vec, @@ -27,29 +29,21 @@ pub struct Shard { /// one of its splits opts it in. A shard takes every count-th case, except /// that an explicit --case list is never sharded. pub fn select(found: &[Discovered], sel: &Selection) -> Result> { - let offline: Vec<_> = found - .iter() - .filter_map(|d| Some((d, d.offline.as_ref()?))) - .collect(); + let offline: Vec<_> = + found.iter().filter_map(|d| Some((d, d.config.offline.as_ref()?))).collect(); if offline.is_empty() { bail!("no selected dataset has offline cases"); } - let cases = || offline.iter().flat_map(|(_, o)| &o.cases); + let cases = || offline.iter().flat_map(|(d, _)| &d.cases); let known_cases: BTreeSet<&str> = cases().map(|c| c.name.as_str()).collect(); - let known_splits: BTreeSet<&str> = cases() - .flat_map(|c| &c.splits) - .map(String::as_str) - .collect(); + let known_splits: BTreeSet<&str> = + cases().flat_map(|c| &c.splits).map(String::as_str).collect(); check_known("case", &sel.cases, &known_cases)?; check_known("split", &sel.splits, &known_splits)?; let shard = sel.shard.filter(|_| sel.cases.is_empty()); - if let Some(Shard { - index, - count: Some(count), - }) = shard - { + if let Some(Shard { index, count: Some(count) }) = shard { if count == 0 || index >= count { bail!("--shard-index {index} is out of range for {count} shards"); } @@ -59,9 +53,7 @@ pub fn select(found: &[Discovered], sel: &Selection) -> Result> { let mut out = Vec::new(); let mut most_shards = 0; for (d, o) in offline { - let picked: Vec = o - .cases - .iter() + let picked: Vec = (d.cases.iter()) .filter(|c| sel.cases.is_empty() || sel.cases.contains(&c.name)) .filter(|c| sel.splits.is_empty() || c.splits.iter().any(|s| sel.splits.contains(s))) .filter(|c| c.enabled || explicit) @@ -69,9 +61,7 @@ pub fn select(found: &[Discovered], sel: &Selection) -> Result> { .collect(); let picked = match shard { Some(s) => { - let count = s - .count - .unwrap_or_else(|| o.shard_config.shard_count(picked.len())); + let count = s.count.unwrap_or_else(|| o.shard_config.shard_count(picked.len())); most_shards = most_shards.max(count); picked.into_iter().skip(s.index).step_by(count).collect() } @@ -94,22 +84,10 @@ pub fn select(found: &[Discovered], sel: &Selection) -> Result> { } fn check_known(what: &str, wanted: &[String], known: &BTreeSet<&str>) -> Result<()> { - let unknown: Vec<&str> = wanted - .iter() - .map(String::as_str) - .filter(|w| !known.contains(w)) - .collect(); + let unknown: Vec<&str> = + wanted.iter().map(String::as_str).filter(|w| !known.contains(w)).collect(); if !unknown.is_empty() { - let available = known.iter().copied().collect::>().join(", "); - let available = if available.is_empty() { - "(none)".to_string() - } else { - available - }; - bail!( - "unknown {what} {}; available: {available}", - unknown.join(", ") - ); + bail!("unknown {what} {}; available: {}", unknown.join(", "), join_or_none(known)); } Ok(()) } @@ -117,50 +95,28 @@ fn check_known(what: &str, wanted: &[String], known: &BTreeSet<&str>) -> Result< #[cfg(test)] mod tests { use super::*; - use crate::eac::{OfflineInfo, Sharding}; - use crate::schema::DatasetRef; + use crate::eac::DatasetConfig; fn case(name: &str, splits: &[&str], enabled: bool) -> Case { Case { + name: name.to_string(), splits: splits.iter().map(|s| s.to_string()).collect(), enabled, - ..Case::named(name.to_string(), None) + ..Default::default() } } fn found(cases: Vec, cases_per_shard: usize) -> Vec { - vec![Discovered { - name: "chat".into(), - file: "evals/chat/dataset.yml".into(), - offline: Some(OfflineInfo { - runtime: "python".into(), - agent: None, - code: DatasetRef { - name: "chat".into(), - mode: Mode::Offline, - runner: "evals.chat:Runner".into(), - cases: Some("evals.chat:CASES".into()), - judges: vec![], - }, - cases, - comparisons: vec![], - shard_config: Sharding { - cases_per_shard, - max_shards: 8, - }, - args_schema: None, - }), - online: None, - judge_args_schemas: Default::default(), - }] + let yaml = format!( + "{{name: chat, runtime: python, offline: {{runner: 'evals.chat:Runner', cases: 'evals.chat:CASES', \ + shard_config: {{cases_per_shard: {cases_per_shard}}}}}}}" + ); + let config: DatasetConfig = serde_yaml::from_str(&yaml).unwrap(); + vec![Discovered { config, cases }] } fn names(found: &[Discovered], sel: Selection) -> Vec { - select(found, &sel).unwrap()[0] - .cases - .iter() - .map(|c| c.name.clone()) - .collect() + select(found, &sel).unwrap()[0].cases.iter().map(|c| c.name.clone()).collect() } fn strings(v: &[&str]) -> Vec { @@ -170,42 +126,20 @@ mod tests { #[test] fn disabled_cases_need_opting_in() { let f = found( - vec![ - case("a", &["smoke"], true), - case("b", &["smoke"], false), - case("c", &[], true), - ], + vec![case("a", &["smoke"], true), case("b", &["smoke"], false), case("c", &[], true)], 20, ); assert_eq!(names(&f, Selection::default()), ["a", "c"]); assert_eq!( - names( - &f, - Selection { - splits: strings(&["smoke"]), - ..Default::default() - } - ), + names(&f, Selection { splits: strings(&["smoke"]), ..Default::default() }), ["a", "b"] ); - assert_eq!( - names( - &f, - Selection { - cases: strings(&["b"]), - ..Default::default() - } - ), - ["b"] - ); + assert_eq!(names(&f, Selection { cases: strings(&["b"]), ..Default::default() }), ["b"]); } #[test] fn cases_and_splits_intersect() { - let f = found( - vec![case("a", &["smoke"], true), case("c", &["slow"], true)], - 20, - ); + let f = found(vec![case("a", &["smoke"], true), case("c", &["slow"], true)], 20); let both = |cases, splits| Selection { cases: strings(cases), splits: strings(splits), @@ -213,22 +147,14 @@ mod tests { }; assert_eq!(names(&f, both(&["a"], &["smoke"])), ["a"]); assert!(select(&f, &both(&["a"], &["slow"])).is_err()); - assert!( - select(&f, &both(&["smoke"], &[])).is_err(), - "a split is not a case" - ); + assert!(select(&f, &both(&["smoke"], &[])).is_err(), "a split is not a case"); } #[test] fn shards_round_robin_by_planned_count() { - let f = found( - (0..5).map(|i| case(&format!("c{i}"), &[], true)).collect(), - 2, - ); - let shard = |index, count| Selection { - shard: Some(Shard { index, count }), - ..Default::default() - }; + let f = found((0..5).map(|i| case(&format!("c{i}"), &[], true)).collect(), 2); + let shard = + |index, count| Selection { shard: Some(Shard { index, count }), ..Default::default() }; // 5 cases at 2 per shard plan 3 shards. assert_eq!(names(&f, shard(0, None)), ["c0", "c3"]); assert_eq!(names(&f, shard(2, None)), ["c2"]); @@ -236,10 +162,7 @@ mod tests { assert_eq!(names(&f, shard(1, Some(2))), ["c1", "c3"]); let explicit = Selection { cases: strings(&["c4"]), - shard: Some(Shard { - index: 1, - count: None, - }), + shard: Some(Shard { index: 1, count: None }), ..Default::default() }; assert_eq!(names(&f, explicit), ["c4"]); diff --git a/core/src/eac/source.rs b/core/src/eac/source.rs new file mode 100644 index 0000000..e6a35fd --- /dev/null +++ b/core/src/eac/source.rs @@ -0,0 +1,126 @@ +//! Where a run came from: the commit, branch and CI job that produced it. + +use std::fs; +use std::path::Path; +use std::process::{Command, Stdio}; + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// What started the run: the workflow's event on GitHub Actions, `ci` on +/// other CI services, and `local` outside CI. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Trigger { + #[default] + Local, + Ci, + PullRequest, + Push, + WorkflowDispatch, + Schedule, +} + +/// The commit, pull request and CI job a run came from. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct Source { + pub trigger: Trigger, + /// Who started the run. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub actor: Option, + /// The commit tested. For a pull request, its head commit. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sha: Option, + /// The pull request's base commit. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base_sha: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pr_number: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pr_url: Option, + /// The pull request author's GitHub login. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pr_author: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub commit_url: Option, + /// The GitHub Actions run. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub run_url: Option, +} + +/// Reads GitHub Actions' environment there, otherwise asks git. +pub fn detect_source(root: &Path) -> Source { + from_github_actions().unwrap_or_else(|| from_git(root)) +} + +/// Whether eac is running in CI. Most CI services set $CI. +pub fn in_ci() -> bool { + std::env::var("CI").is_ok_and(|v| !v.is_empty() && v != "false" && v != "0") +} + +/// None outside GitHub Actions. +fn from_github_actions() -> Option { + if env("GITHUB_ACTIONS").as_deref() != Some("true") { + return None; + } + let event = env("GITHUB_EVENT_PATH") + .and_then(|path| fs::read(path).ok()) + .and_then(|raw| serde_json::from_slice(&raw).ok()) + .unwrap_or(Value::Null); + let pr = &event["pull_request"]; + let text = |v: &Value| v.as_str().filter(|s| !s.is_empty()).map(String::from); + let pr_number: Option = env("GITHUB_REF") + .and_then(|r| r.strip_prefix("refs/pull/")?.split('/').next()?.parse().ok()); + // On a pull request $GITHUB_SHA is a merge commit that exists only in CI, + // so the run is attributed to the pull request's head instead. + let sha = text(&pr["head"]["sha"]).or_else(|| env("GITHUB_SHA")); + let repo = env("GITHUB_SERVER_URL") + .zip(env("GITHUB_REPOSITORY")) + .map(|(server, repo)| format!("{server}/{repo}")); + let repo_url = |path: String| repo.as_ref().map(|repo| format!("{repo}/{path}")); + // An event with no trigger of its own, or none named, counts as a push. + let trigger = match env("GITHUB_EVENT_NAME").as_deref() { + Some("pull_request" | "pull_request_target") => Trigger::PullRequest, + Some("workflow_dispatch") => Trigger::WorkflowDispatch, + Some("schedule") => Trigger::Schedule, + _ => Trigger::Push, + }; + Some(Source { + trigger, + actor: env("GITHUB_ACTOR"), + branch: env("GITHUB_HEAD_REF").or_else(|| env("GITHUB_REF_NAME")), + base_sha: text(&pr["base"]["sha"]), + pr_url: pr_number.and_then(|n| repo_url(format!("pull/{n}"))), + pr_author: text(&pr["user"]["login"]), + commit_url: sha.as_ref().and_then(|sha| repo_url(format!("commit/{sha}"))), + run_url: env("GITHUB_RUN_ID").and_then(|id| repo_url(format!("actions/runs/{id}"))), + sha, + pr_number, + }) +} + +fn from_git(root: &Path) -> Source { + Source { + trigger: if in_ci() { Trigger::Ci } else { Trigger::Local }, + actor: env("USER"), + branch: git(root, &["rev-parse", "--abbrev-ref", "HEAD"]).filter(|b| b != "HEAD"), + sha: git(root, &["rev-parse", "HEAD"]), + ..Default::default() + } +} + +fn git(root: &Path, args: &[&str]) -> Option { + let mut cmd = Command::new("git"); + cmd.arg("-C").arg(root).args(args).stdin(Stdio::null()).stderr(Stdio::null()); + let out = cmd.output().ok()?; + let value = String::from_utf8(out.stdout).ok()?.trim().to_string(); + (out.status.success() && !value.is_empty()).then_some(value) +} + +/// An environment variable, or None if it is unset or empty. +fn env(key: &str) -> Option { + std::env::var(key).ok().filter(|v| !v.is_empty()) +} diff --git a/core/src/eac/source/detect.rs b/core/src/eac/source/detect.rs deleted file mode 100644 index 9b46f7f..0000000 --- a/core/src/eac/source/detect.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! A run's source and how it's detected. - -use std::path::Path; - -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -use super::{git, github}; - -/// What started a run, either a local command or a CI event. Matches seer's -/// Source.trigger. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum Trigger { - #[default] - Local, - PullRequest, - Push, - WorkflowDispatch, - Schedule, -} - -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] -pub struct Source { - pub trigger: Trigger, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub actor: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub sha: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub base_sha: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub branch: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub pr_number: Option, - // TODO - #[serde(default, skip_serializing_if = "Option::is_none")] - pub run_url: Option, -} - -/// Reads GitHub Actions' environment in CI, otherwise asks git. -pub fn detect_source(root: &Path) -> Source { - github::detect().unwrap_or_else(|| git::detect(root)) -} - -/// An environment variable, or None if it is unset or empty. -pub(super) fn env(key: &str) -> Option { - std::env::var(key).ok().filter(|v| !v.is_empty()) -} diff --git a/core/src/eac/source/git.rs b/core/src/eac/source/git.rs deleted file mode 100644 index 871d40b..0000000 --- a/core/src/eac/source/git.rs +++ /dev/null @@ -1,31 +0,0 @@ -use std::path::Path; -use std::process::{Command, Stdio}; - -use super::detect::{env, Source, Trigger}; - -// TODO: Don't assume local -pub fn detect(root: &Path) -> Source { - Source { - trigger: Trigger::Local, - actor: env("USER"), - branch: git(root, &["rev-parse", "--abbrev-ref", "HEAD"]).filter(|b| b != "HEAD"), - sha: git(root, &["rev-parse", "HEAD"]), - base_sha: None, - pr_number: None, - run_url: None, - } -} - -fn git(root: &Path, args: &[&str]) -> Option { - let out = Command::new("git") - .arg("-C") - .arg(root) - .args(args) - .stdin(Stdio::null()) - .stderr(Stdio::null()) - .output() - .ok()?; - - let value = String::from_utf8(out.stdout).ok()?.trim().to_string(); - (out.status.success() && !value.is_empty()).then_some(value) -} diff --git a/core/src/eac/source/github.rs b/core/src/eac/source/github.rs deleted file mode 100644 index cdb3a3c..0000000 --- a/core/src/eac/source/github.rs +++ /dev/null @@ -1,42 +0,0 @@ -//! Reads the event, ref and run of a GitHub Actions job. - -use super::detect::{env, Source, Trigger}; - -/// None outside GitHub Actions. -pub fn detect() -> Option { - if env("GITHUB_ACTIONS").as_deref() != Some("true") { - return None; - } - let pr_number = env("GITHUB_REF").and_then(|r| { - r.strip_prefix("refs/pull/")? - .split('/') - .next()? - .parse() - .ok() - }); - let run_url = match ( - env("GITHUB_SERVER_URL"), - env("GITHUB_REPOSITORY"), - env("GITHUB_RUN_ID"), - ) { - (Some(server), Some(repo), Some(id)) => Some(format!("{server}/{repo}/actions/runs/{id}")), - _ => None, - }; - // An event with no trigger of its own, or none named, counts as a push. - let trigger = match env("GITHUB_EVENT_NAME").as_deref() { - Some("pull_request" | "pull_request_target") => Trigger::PullRequest, - Some("workflow_dispatch") => Trigger::WorkflowDispatch, - Some("schedule") => Trigger::Schedule, - _ => Trigger::Push, - }; - Some(Source { - trigger, - actor: env("GITHUB_ACTOR"), - branch: env("GITHUB_HEAD_REF").or_else(|| env("GITHUB_REF_NAME")), - sha: env("GITHUB_SHA"), - // TODO: the pull request's base, from $GITHUB_EVENT_PATH - base_sha: None, - pr_number, - run_url, - }) -} diff --git a/core/src/eac/source/mod.rs b/core/src/eac/source/mod.rs deleted file mode 100644 index a0d2a2b..0000000 --- a/core/src/eac/source/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Where a run came from: the commit, branch and CI job that produced it. - -mod detect; -mod git; -mod github; - -pub use detect::{detect_source, Source}; diff --git a/core/src/main.rs b/core/src/main.rs index 185b600..6bbb3b8 100644 --- a/core/src/main.rs +++ b/core/src/main.rs @@ -1,24 +1,22 @@ +// First, so its macros are visible in the modules after it. #[macro_use] -mod eac; +mod report; mod cli; mod commands; +mod eac; mod schema; mod worker; use std::process::ExitCode; -use std::sync::atomic::{AtomicBool, Ordering}; use clap::Parser; use cli::Cli; use commands::FailedRun; -/// Set on Ctrl-C or SIGTERM. In-flight worker calls give up once it's set. -static INTERRUPTED: AtomicBool = AtomicBool::new(false); - fn main() -> ExitCode { let args = Cli::parse(); - let _ = ctrlc::set_handler(|| INTERRUPTED.store(true, Ordering::Relaxed)); + let _ = ctrlc::set_handler(worker::interrupt); match cli::dispatch(args.command) { Ok(()) => ExitCode::SUCCESS, Err(e) if e.is::() => ExitCode::from(1), diff --git a/core/src/eac/report/format.rs b/core/src/report/format.rs similarity index 86% rename from core/src/eac/report/format.rs rename to core/src/report/format.rs index 03001c6..6ff6274 100644 --- a/core/src/eac/report/format.rs +++ b/core/src/report/format.rs @@ -46,6 +46,15 @@ pub fn plural<'a>(n: usize, one: &'a str, many: &'a str) -> &'a str { } } +/// "a, b, c", or "(none)" for no items, for listing what's available. +pub fn join_or_none>(items: impl IntoIterator) -> String { + let items: Vec = items.into_iter().collect(); + if items.is_empty() { + return "(none)".to_string(); + } + items.iter().map(AsRef::as_ref).collect::>().join(", ") +} + #[cfg(test)] mod tests { use super::*; diff --git a/core/src/report/mod.rs b/core/src/report/mod.rs new file mode 100644 index 0000000..cd08db1 --- /dev/null +++ b/core/src/report/mod.rs @@ -0,0 +1,77 @@ +//! What eac prints on stderr: phase headers, status lines and result tables. +//! stdout is kept for output meant to be piped, like run ids. + +use std::fmt; +use std::io::IsTerminal; +use std::sync::LazyLock; + +// Before the submodules, so they can use them too. +macro_rules! info { + ($($arg:tt)*) => { $crate::report::info(format_args!($($arg)*)) }; +} + +macro_rules! detail { + ($($arg:tt)*) => { $crate::report::detail(format_args!($($arg)*)) }; +} + +macro_rules! warning { + ($($arg:tt)*) => { $crate::report::warning(format_args!($($arg)*)) }; +} + +mod format; +mod tables; + +pub use format::{join_or_none, plural}; +pub use tables::{print_comparison, print_summary}; + +pub fn phase(name: &str) { + eprintln!("\n{}", paint(BOLD, &name.to_uppercase())); +} + +pub fn info(args: fmt::Arguments) { + eprintln!(" {args}"); +} + +pub fn detail(args: fmt::Arguments) { + eprintln!(" {}", paint(DIM, &args.to_string())); +} + +pub fn warning(args: fmt::Arguments) { + eprintln!(" {}", paint(YELLOW, &args.to_string())); +} + +/// A check's result, such as whether a credential is set up. +pub fn checked(ok: bool, what: &str) { + let mark = if ok { paint(GREEN, "✓") } else { paint(RED, "✗") }; + eprintln!(" {mark} {what}"); +} + +/// A line a worker printed: stdout is "info", stderr is "warn". +pub fn worker_log(level: &str, line: &str) { + let color = if level == "warn" { YELLOW } else { DIM }; + eprintln!(" {}", paint(color, line)); +} + +pub fn first_line(s: &str) -> &str { + s.lines().next().unwrap_or_default() +} + +const RESET: &str = "\x1b[0m"; +const DIM: &str = "\x1b[2m"; +const BOLD: &str = "\x1b[1m"; +const GREEN: &str = "\x1b[32m"; +const RED: &str = "\x1b[31m"; +const YELLOW: &str = "\x1b[33m"; + +/// Colors are on for a terminal, unless NO_COLOR is set. +static COLOR: LazyLock = LazyLock::new(|| { + std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty()) && std::io::stderr().is_terminal() +}); + +fn paint(color: &str, s: &str) -> String { + if *COLOR { + format!("{color}{s}{RESET}") + } else { + s.to_string() + } +} diff --git a/core/src/eac/report/tables.rs b/core/src/report/tables.rs similarity index 55% rename from core/src/eac/report/tables.rs rename to core/src/report/tables.rs index 8b9b90c..476ef9e 100644 --- a/core/src/eac/report/tables.rs +++ b/core/src/report/tables.rs @@ -1,17 +1,7 @@ -use super::color::{paint, BOLD, DIM, GREEN, RED, YELLOW}; use super::format::{format_duration, format_score, plural}; -use super::lines::{first_line, phase}; +use super::{first_line, paint, phase, BOLD, DIM, GREEN, RED, YELLOW}; use crate::eac::Summary; -fn status_color(cell: &str) -> Option<&'static str> { - match cell { - "PASSED" => Some(GREEN), - "FAILED" => Some(RED), - "ERROR" => Some(YELLOW), - _ => None, - } -} - /// Prints the results table, then any errors and the explanations for /// scores below 1. pub fn print_summary(s: &Summary) { @@ -29,25 +19,13 @@ fn print_offline(s: &Summary) { info!("no cases judged"); return; } - let mut rows = Vec::new(); - let (mut errors, mut misses) = (Vec::new(), Vec::new()); + let (mut rows, mut errors, mut misses) = (Vec::new(), Vec::new(), Vec::new()); for r in &s.results { let name = format!("{}/{}", r.dataset, r.case); - rows.push(vec![ - name.clone(), - r.status.as_str().to_uppercase(), - format_duration(r.duration_seconds), - ]); + let status = r.status.as_str().to_uppercase(); + rows.push(vec![name.clone(), status, format_duration(r.duration_seconds)]); for sc in &r.scores { - let judge = match sc.label.as_deref().filter(|l| !l.is_empty()) { - Some(label) => format!("{} ({label})", sc.name), - None => sc.name.clone(), - }; - rows.push(vec![ - format!(" └ {judge}"), - format_score(sc.score), - String::new(), - ]); + rows.push(vec![format!(" └ {}", sc.name), format_score(sc.score), String::new()]); 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))); @@ -61,76 +39,72 @@ fn print_offline(s: &Summary) { print_list("Errors", RED, &errors); print_list("Below 1", DIM, &misses); - eprintln!( - "\n {} {} {} {}", - paint( - BOLD, - &format!("{} {}", s.total, plural(s.total, "case", "cases")) - ), + let mut totals = vec![ + paint(BOLD, &format!("{} {}", s.total, plural(s.total, "case", "cases"))), paint(GREEN, &format!("{} passed", s.passed)), paint(RED, &format!("{} failed", s.failed)), paint(YELLOW, &format!("{} errored", s.errors)), - ); + ]; + if s.skipped > 0 { + totals.push(paint(DIM, &format!("{} skipped", s.skipped))); + } + eprintln!("\n {}", totals.join(" ")); detail!("judged in {}", format_duration(s.duration_seconds)); } fn print_online(s: &Summary) { if s.judges.is_empty() { - info!("no records scored"); + info!("no cases scored"); return; } - let rows: Vec> = s - .judges - .iter() - .map(|j| { + let rows: Vec> = (s.judges.iter()) + .map(|j| vec![j.name.clone(), format_score(Some(j.mean)), j.count.to_string()]) + .collect(); + 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)); + eprintln!("\n {cases} {below}"); + detail!("judged in {}", format_duration(s.duration_seconds)); +} + +/// One row per arm of a comparison. +pub fn print_comparison(title: &str, arms: &[(String, String, Summary)]) { + phase(title); + let rows: Vec> = (arms.iter()) + .map(|(arm, run_id, s)| { vec![ - j.name.clone(), - format_score(Some(j.mean)), - j.count.to_string(), + arm.clone(), + format!("{}/{}", s.passed, s.total), + s.failed.to_string(), + s.errors.to_string(), + format_score(s.mean_score()), + run_id.clone(), ] }) .collect(); - print_table(&["Judge", "Mean score", "Records"], &rows, None); - - let below = s.failed + s.errors; - eprintln!( - "\n {} {}", - paint( - BOLD, - &format!("{} {}", s.total, plural(s.total, "record", "records")) - ), - paint(DIM, &format!("{below} below 1 or errored; see scores/")), - ); - detail!("judged in {}", format_duration(s.duration_seconds)); + print_table(&["Arm", "Passed", "Failed", "Errored", "Mean score", "Run"], &rows, None); } -/// Renders a bordered table. Cells in status_col that name a status are -/// colored. +/// Prints a bordered table. Cells in `status_col` that hold a status, like +/// PASSED, are colored by it. fn print_table(headers: &[&str], rows: &[Vec], status_col: Option) { let width = |s: &str| s.chars().count(); - let widths: Vec = headers - .iter() - .enumerate() - .map(|(i, h)| { - rows.iter() - .map(|row| width(&row[i])) - .fold(width(h), usize::max) - }) + let widths: Vec = (0..headers.len()) + .map(|i| rows.iter().map(|row| width(&row[i])).fold(width(headers[i]), usize::max)) .collect(); let separator = |fill: &str| { let parts: Vec = widths.iter().map(|w| fill.repeat(w + 2)).collect(); format!(" +{}+", parts.join("+")) }; let render = |row: &[&str]| { - let cells: Vec = row - .iter() - .enumerate() + let cells: Vec = (row.iter().enumerate()) .map(|(i, v)| { - let mut cell = format!("{v}{}", " ".repeat(widths[i] - width(v))); - if let Some(color) = status_color(v).filter(|_| Some(i) == status_col) { - cell = paint(color, &cell); + let cell = format!("{v: format!(" {} ", paint(color, &cell)), + None => format!(" {cell} "), } - format!(" {cell} ") }) .collect(); format!(" |{}|", cells.join("|")) @@ -138,34 +112,20 @@ fn print_table(headers: &[&str], rows: &[Vec], status_col: Option let mut lines = vec![separator("-"), render(headers), separator("=")]; for row in rows { - let row: Vec<&str> = row.iter().map(String::as_str).collect(); - lines.push(render(&row)); + lines.push(render(&row.iter().map(String::as_str).collect::>())); } lines.push(separator("-")); eprintln!("{}", lines.join("\n")); } -/// Prints one row per comparison arm. -pub fn print_comparison(title: &str, arms: &[(String, String, Summary)]) { - phase(title); - let rows: Vec> = arms - .iter() - .map(|(arm, run_id, s)| { - vec![ - arm.clone(), - format!("{}/{}", s.passed, s.total), - s.failed.to_string(), - s.errors.to_string(), - format_score(s.mean_score()), - run_id.clone(), - ] - }) - .collect(); - print_table( - &["Arm", "Passed", "Failed", "Errored", "Mean score", "Run"], - &rows, - None, - ); +fn status_color(cell: &str) -> Option<&'static str> { + match cell { + "PASSED" => Some(GREEN), + "FAILED" => Some(RED), + "ERROR" => Some(YELLOW), + "SKIPPED" => Some(DIM), + _ => None, + } } fn print_list(title: &str, color: &str, items: &[String]) { diff --git a/core/src/schema/document.rs b/core/src/schema/document.rs index 3739159..1b67629 100644 --- a/core/src/schema/document.rs +++ b/core/src/schema/document.rs @@ -1,114 +1,82 @@ -use schemars::generate::SchemaSettings; use schemars::{JsonSchema, SchemaGenerator}; use serde_json::{json, Map, Value}; -use super::{ - ArgsValidateParams, ArgsValidateResult, CaseExecuteParams, CaseExecuteResult, - CaseJudgeParams, CaseJudgeResult, CredentialsCheckParams, CredentialsCheckResult, - CredentialsLoginParams, CredentialsLoginResult, DiscoverParams, DiscoverResult, Object, - OnlineFetchParams, OnlineFetchResult, OnlineJudgeParams, Ready, Request, Response, - SeedSetupParams, SeedSetupResult, SeedTeardownParams, VERSION, -}; +use super::*; /// The protocol as one JSON Schema document. Every type is under `$defs`, /// along with `WorkerMethods`, which gives each method's params and result. pub fn document() -> Value { - let mut s = Generators { - params: SchemaSettings::draft2020_12() - .for_serialize() - .into_generator(), - results: SchemaSettings::draft2020_12() - .for_deserialize() - .into_generator(), + let mut m = Methods { + params: schema_settings().for_serialize().into_generator(), + results: schema_settings().for_deserialize().into_generator(), + methods: Map::new(), }; - s.params.subschema_for::>(); - s.results.subschema_for::(); - s.results.subschema_for::(); + m.params.subschema_for::>(); + m.results.subschema_for::(); + m.results.subschema_for::(); - let worker = table( - "The methods an SDK worker answers.", - [ - ( - "discover", - s.method::( - "Imports the dataset's code and describes it, with no side effects beyond the import.", - ), - ), - ( - "args.validate", - s.method::( - "Checks --args and --judge-args before anything is set up. Return an error to reject them.", - ), - ), - ( - "seed.setup", - s.method::( - "Sets up a seed, or loads a cached one from its own cache. eac sends each seed key once.", - ), - ), - ( - "seed.teardown", - s.method::("Tears down a seed that seed.setup returned."), - ), - ( - "case.execute", - s.method::( - "Runs the system under test on a case and returns its raw output, unscored.", - ), - ), - ( - "case.judge", - s.method::( - "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.", - ), - ), - ( - "online.fetch", - s.method::( - "Returns at most limit production records from the window.", - ), - ), - ( - "online.judge", - s.method::( - "Scores a production record with the named online judges.", - ), - ), - ( - "credentials.check", - s.method::( - "Checks whether each credential is set up and works.", - ), - ), - ( - "credentials.login", - s.method::( - "Logs in to a credential. Sent to a worker started on the terminal, so login can prompt.", - ), - ), - ], + m.add::( + "discover", + "Imports the dataset's code and describes it, with no side effects beyond the import.", + ); + 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.", + ); + m.add::( + "seed.setup", + "Sets up a seed, or loads a cached one from its own cache. eac sends each seed key once.", + ); + m.add::( + "seed.teardown", + "Tears down a seed that seed.setup returned.", + ); + m.add::( + "case.run", + "Runs the system under test on a case and returns its raw output, unscored.", + ); + 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.", + ); + m.add::( + "online.collect", + "Returns at most limit production runs from the window, as cases with their outputs.", + ); + m.add::( + "online.judge", + "Scores a collected case with the named online judges.", + ); + m.add::( + "credentials.check", + "Checks whether each credential is set up and works.", + ); + m.add::( + "credentials.login", + "Logs in to a credential. Sent to a worker started on the terminal, so login can prompt.", ); - let mut defs = s.definitions(); - defs.insert("WorkerMethods".into(), worker); json!({ "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Worker protocol", - "description": format!("Protocol v{VERSION}. core/PROTOCOL.md describes each method."), - "$defs": defs, + "description": format!("The messages between eac and an SDK worker, protocol version {VERSION}. core/PROTOCOL.md describes each method."), + "$defs": m.definitions(), }) } -/// Params are described as eac serializes them and results as it deserializes -/// them, so the schema says exactly what a worker gets and what it may send. -struct Generators { +/// Collects each method's schema. Params are described as eac serializes +/// them and results as it deserializes them, so the schema says exactly what +/// a worker gets and what it may send. +struct Methods { params: SchemaGenerator, results: SchemaGenerator, + methods: Map, } -impl Generators { - fn method(&mut self, description: &str) -> Value { - json!({ +impl Methods { + fn add(&mut self, name: &str, description: &str) { + let method = json!({ "description": description, "type": "object", "properties": { @@ -117,30 +85,26 @@ impl Generators { }, "required": ["params", "result"], "additionalProperties": false, - }) + }); + self.methods.insert(name.to_string(), method); } - /// Types used in both directions, like Case, keep their result schema - /// because it's looser and allows the nulls and missing fields eac accepts. + /// Every type's schema, plus `WorkerMethods`: an object with a property + /// per method. Types used in both directions, like Case, keep their result + /// schema because it's looser and allows the nulls and missing fields eac + /// accepts. fn definitions(mut self) -> Map { + let required: Vec<&String> = self.methods.keys().collect(); + let worker_methods = json!({ + "description": "The methods an SDK worker answers.", + "type": "object", + "properties": self.methods, + "required": required, + "additionalProperties": false, + }); let mut defs = self.params.take_definitions(true); defs.extend(self.results.take_definitions(true)); + defs.insert("WorkerMethods".into(), worker_methods); defs } } - -/// An object with a property per method, each holding its params and result. -fn table(description: &str, methods: [(&str, Value); N]) -> Value { - let properties: Map = methods - .into_iter() - .map(|(name, method)| (name.to_string(), method)) - .collect(); - let required: Vec<&String> = properties.keys().collect(); - json!({ - "description": description, - "type": "object", - "properties": properties, - "required": required, - "additionalProperties": false, - }) -} diff --git a/core/src/schema/mod.rs b/core/src/schema/mod.rs index 7e968fc..89a7f45 100644 --- a/core/src/schema/mod.rs +++ b/core/src/schema/mod.rs @@ -1,17 +1,13 @@ -//! The protocol SDK workers speak. PROTOCOL.md describes each method. -//! -//! These types are the protocol's only definition. `make generate` writes -//! `document()` to protocol.schema.json and generates the Python SDK's -//! protocol types from it. - mod document; mod fields; mod framing; +mod settings; mod types; mod worker_methods; pub use document::document; pub use fields::{is_empty, nullable}; pub use framing::*; +pub use settings::schema_settings; pub use types::*; pub use worker_methods::*; diff --git a/core/src/schema/protocol.schema.json b/core/src/schema/protocol.schema.json index ded8f7a..8023e6f 100644 --- a/core/src/schema/protocol.schema.json +++ b/core/src/schema/protocol.schema.json @@ -3,19 +3,17 @@ "ArgsValidateParams": { "properties": { "args": { - "additionalProperties": true, "type": "object" }, "dataset": { "$ref": "#/$defs/DatasetRef" }, "judge_args": { - "additionalProperties": true, "description": "--judge-args, by judge name.", "type": "object" }, "judges": { - "description": "Online: the judges picked. Offline: judges that replace every case's\nown, as in a comparison. Empty keeps each case's 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.", "items": { "type": "string" }, @@ -34,15 +32,6 @@ }, "ArgsValidateResult": { "properties": { - "args": { - "additionalProperties": true, - "default": null, - "description": "The args with defaults filled in. Absent keeps them as sent.", - "type": [ - "object", - "null" - ] - }, "judge_credentials": { "additionalProperties": { "items": { @@ -50,13 +39,11 @@ }, "type": "array" }, - "default": {}, - "description": "What each of the run's judges needs, by the name cases and --judge use.", + "description": "The credentials each of the run's judges needs, by judge name.", "type": "object" }, "runner_credentials": { - "default": [], - "description": "What the runner needs with these args.", + "description": "The credentials the runner needs.", "items": { "$ref": "#/$defs/Credential" }, @@ -66,35 +53,49 @@ "type": "object" }, "Case": { + "description": "An offline case, or a production run collected for online judging.", "properties": { + "conversation_id": { + "description": "The ID the agent's run was tagged with, for judges to fetch its trace by. Set like `output`.", + "type": [ + "string", + "null" + ] + }, "enabled": { "description": "A disabled case runs only when picked by name or by one of its splits.", "type": "boolean" }, "expected_output": { - "additionalProperties": true, "type": [ "object", "null" ] }, "input": { - "additionalProperties": true, "type": [ "object", "null" ] }, "judges": { - "description": "Names, for display only. Judges run inside the worker.", + "description": "The judges' names, for display. The worker runs the judges itself.", "items": { "type": "string" }, "type": "array" }, "name": { + "description": "Unique in its dataset. An online case's id.", "type": "string" }, + "output": { + "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", + "null" + ] + }, "seeds": { "items": { "$ref": "#/$defs/Seed" @@ -113,88 +114,18 @@ ], "type": "object" }, - "CaseExecuteParams": { - "properties": { - "args": { - "additionalProperties": true, - "type": "object" - }, - "case": { - "$ref": "#/$defs/Case" - }, - "conversation_id": { - "description": "Tag the agent run with this so its trace can be fetched for judging.", - "type": "string" - }, - "dataset": { - "$ref": "#/$defs/DatasetRef" - }, - "seeds": { - "additionalProperties": { - "$ref": "#/$defs/Handle" - }, - "description": "Handles by seed name.", - "type": "object" - } - }, - "required": [ - "dataset", - "case", - "conversation_id" - ], - "type": "object" - }, - "CaseExecuteResult": { - "properties": { - "conversation_id": { - "default": null, - "description": "Overrides the conversation id eac sent, if the agent used another.", - "type": [ - "string", - "null" - ] - }, - "metrics": { - "anyOf": [ - { - "$ref": "#/$defs/Metrics" - }, - { - "type": "null" - } - ], - "default": null - }, - "output": { - "additionalProperties": true, - "default": null, - "description": "Must be JSON-serializable, since it's saved for the judge phase.", - "type": [ - "object", - "null" - ] - } - }, - "type": "object" - }, "CaseJudgeParams": { "properties": { "agent": { - "description": "The production agent, from dataset.yml.", + "description": "The agent named in dataset.yml.", "type": [ "string", "null" ] }, "case": { - "$ref": "#/$defs/Case" - }, - "conversation_id": { - "description": "The id the agent run was tagged with.", - "type": [ - "string", - "null" - ] + "$ref": "#/$defs/Case", + "description": "With the runner's `output` and `conversation_id`." }, "dataset": { "$ref": "#/$defs/DatasetRef" @@ -207,30 +138,23 @@ ] }, "error": { + "description": "Why the runner failed, in which case there's no output.", "type": [ "string", "null" ] }, "judge_args": { - "additionalProperties": true, "description": "--judge-args, by judge name.", "type": "object" }, "judges": { - "description": "Judges by name that replace the case's own, as in a comparison. Empty\nkeeps the case's own.", + "description": "Judges to use instead of the case's own, as in a comparison. Empty keeps the case's judges.", "items": { "type": "string" }, "type": "array" }, - "output": { - "additionalProperties": true, - "type": [ - "object", - "null" - ] - }, "seeds": { "additionalProperties": { "$ref": "#/$defs/Handle" @@ -238,7 +162,7 @@ "type": "object" }, "started_at": { - "description": "When the case ran.", + "description": "When the runner started.", "format": "date-time", "type": [ "string", @@ -246,29 +170,26 @@ ] }, "trace": { - "description": "The agent trace an earlier judge phase saved. Without one, the judges\nmay fetch it by conversation_id." + "description": "The agent trace an earlier judge phase saved. Without one, the judges may fetch it by the case's conversation_id." } }, "required": [ "dataset", - "case", - "output" + "case" ], "type": "object" }, "CaseJudgeResult": { - "description": "Also what online.judge returns.", + "description": "What case.judge and online.judge return.", "properties": { "scores": { - "default": [], "items": { "$ref": "#/$defs/Score" }, "type": "array" }, "trace": { - "default": null, - "description": "The agent trace a judge fetched, if eac didn't send one. eac saves it,\nso judging again doesn't fetch it again." + "description": "The agent trace a judge fetched, if eac didn't send one. eac saves it for later judge runs." }, "trace_metrics": { "anyOf": [ @@ -279,30 +200,87 @@ "type": "null" } ], - "default": null, - "description": "The LLM usage the fetched trace records. It replaces what the runner\nreported." + "description": "The LLM usage recorded in the fetched trace. It replaces what the runner reported." + } + }, + "type": "object" + }, + "CaseRunParams": { + "properties": { + "args": { + "type": "object" + }, + "case": { + "$ref": "#/$defs/Case" + }, + "conversation_id": { + "description": "Tag the agent's run with this so judges can fetch its trace.", + "type": "string" + }, + "dataset": { + "$ref": "#/$defs/DatasetRef" + }, + "seeds": { + "additionalProperties": { + "$ref": "#/$defs/Handle" + }, + "description": "Each seed's handle, by seed name.", + "type": "object" + } + }, + "required": [ + "dataset", + "case", + "conversation_id" + ], + "type": "object" + }, + "CaseRunResult": { + "properties": { + "conversation_id": { + "description": "The conversation ID the agent used, if it isn't the one eac sent.", + "type": [ + "string", + "null" + ] + }, + "metrics": { + "anyOf": [ + { + "$ref": "#/$defs/Metrics" + }, + { + "type": "null" + } + ] + }, + "output": { + "description": "Saved for the judge phase, so it must be JSON.", + "type": [ + "object", + "null" + ] } }, "type": "object" }, "Credential": { - "description": "Credentials a seed, runner or judge needs, such as a token or a CLI\nlogin. The SDK rebuilds it from `path` and `fields` to check it or log\nin, so eac can check each distinct one once, before the phases that need\nit.", + "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.", "properties": { "fields": { - "additionalProperties": true, - "description": "What its class is built with.", + "description": "The arguments its class is built with.", "type": "object" }, "manual": { - "description": "It can only be set up by hand, so eac shows how instead of offering\nto log in.", + "description": "Can only be set up by hand, so eac shows the instructions instead of offering to log in.", "type": "boolean" }, "name": { - "description": "Shown in status lines and prompts, e.g. \"github\".", + "description": "Shown in status lines and prompts, like \"github\".", "type": "string" }, "path": { - "description": "Its class.", + "description": "The credential's class, as a code reference.", "type": "string" }, "setup_instructions": { @@ -333,7 +311,6 @@ "CredentialsCheckResult": { "properties": { "authenticated": { - "default": [], "description": "Whether each credential is set up and works, in the order sent.", "items": { "type": "boolean" @@ -360,25 +337,24 @@ "additionalProperties": { "type": "string" }, - "default": {}, - "description": "Environment variables the credential needs. eac gives them to every\nprocess it starts, and saves them for later commands once the\ncredential checks out.", + "description": "Environment variables the credential sets. eac passes them to every process it starts and saves them once the credential checks out.", "type": "object" } }, "type": "object" }, "DatasetRef": { - "description": "Where a dataset's code is, per its dataset.yml. Every worker method that\nneeds the dataset gets this, so a worker can import it in any phase.", + "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.", "properties": { "cases": { - "description": "Offline: the sequence of Cases.", + "description": "The dataset's cases. Offline only.", "type": [ "string", "null" ] }, "judges": { - "description": "Online: the judges `eac online judge --judge` picks from.", + "description": "The judges --judge picks from. Online only.", "items": { "$ref": "#/$defs/JudgeRef" }, @@ -415,25 +391,14 @@ "type": "object" }, "DiscoverResult": { - "description": "What only the dataset's code knows. Its dataset.yml says the rest.", + "description": "What eac learns by importing the dataset's code. Its dataset.yml covers the rest.", "properties": { - "args_schema": { - "default": null, - "description": "JSON Schema of the runner's --args." - }, "cases": { - "default": [], - "description": "Offline: every case.", + "description": "Every case. Offline only.", "items": { "$ref": "#/$defs/Case" }, "type": "array" - }, - "judge_args_schemas": { - "additionalProperties": true, - "default": {}, - "description": "JSON Schema of each judge's --judge-args, by judge name, for the\njudges that take any.", - "type": "object" } }, "type": "object" @@ -444,7 +409,6 @@ "type": "string" }, "traceback": { - "default": "", "type": "string" } }, @@ -454,15 +418,14 @@ "type": "object" }, "Handle": { - "additionalProperties": true, - "description": "What a seed's setup returned. It must be JSON-serializable because it's\nwritten to seeds.json and read back by a later phase.", + "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 or in eac.yml's online.judges.", + "description": "A judge named in a dataset.yml's online.judges.", "properties": { "name": { - "description": "The name --judge and --judge-args use. Its scores keep the judge's own\nname.", + "description": "The name --judge and --judge-args use. Scores still carry the judge's own name.", "type": "string" }, "path": { @@ -477,58 +440,36 @@ "type": "object" }, "Metrics": { - "description": "LLM usage for one case, reported by the runner or derived from its trace.", + "description": "LLM usage: tokens, calls, time and cost.", "properties": { "cache_read_tokens": { - "default": 0.0, - "format": "double", "type": "number" }, "cache_write_tokens": { - "default": 0.0, - "format": "double", "type": "number" }, "cost_usd": { - "default": 0.0, - "format": "double", "type": "number" }, "input_tokens": { - "default": 0.0, - "format": "double", "type": "number" }, "llm_calls": { - "default": 0, - "format": "uint64", - "minimum": 0, "type": "integer" }, "llm_duration_seconds": { - "default": 0.0, - "format": "double", "type": "number" }, "output_tokens": { - "default": 0.0, - "format": "double", "type": "number" }, "reasoning_tokens": { - "default": 0.0, - "format": "double", "type": "number" }, "tool_calls": { - "default": 0, - "format": "uint64", - "minimum": 0, "type": "integer" }, "total_tokens": { - "default": 0.0, - "format": "double", "type": "number" } }, @@ -541,22 +482,19 @@ ], "type": "string" }, - "OnlineFetchParams": { + "OnlineCollectParams": { "properties": { "args": { - "additionalProperties": true, "type": "object" }, "dataset": { "$ref": "#/$defs/DatasetRef" }, "limit": { - "format": "uint", - "minimum": 0, "type": "integer" }, "since": { - "description": "RFC 3339. Only records in [since, until) are returned.", + "description": "RFC 3339. Return runs from since up to, but not including, until.", "type": "string" }, "until": { @@ -571,12 +509,12 @@ ], "type": "object" }, - "OnlineFetchResult": { + "OnlineCollectResult": { "properties": { - "records": { - "default": [], + "cases": { + "description": "One case per production run, each with its `output` and, if it has one, its `conversation_id`.", "items": { - "$ref": "#/$defs/Record" + "$ref": "#/$defs/Case" }, "type": "array" } @@ -591,31 +529,31 @@ "null" ] }, + "case": { + "$ref": "#/$defs/Case", + "description": "A collected case, with its `output` and `conversation_id`." + }, "dataset": { "$ref": "#/$defs/DatasetRef" }, "judge_args": { - "additionalProperties": true, "description": "--judge-args, by judge name.", "type": "object" }, "judges": { - "description": "The judges picked, by the names their YAML gives them.", + "description": "The judges picked, by their YAML names.", "items": { "type": "string" }, "type": "array" }, - "record": { - "$ref": "#/$defs/Record" - }, "trace": { - "description": "As in case.judge. The record's conversation_id identifies its trace." + "description": "As in case.judge. The case's conversation_id identifies the trace." } }, "required": [ "dataset", - "record", + "case", "judges" ], "type": "object" @@ -624,9 +562,7 @@ "description": "The first line a worker sends.", "properties": { "protocol": { - "const": 1, - "format": "int64", - "type": "integer" + "const": 1 } }, "required": [ @@ -634,51 +570,15 @@ ], "type": "object" }, - "Record": { - "description": "One thing the system already did, observed in production.", - "properties": { - "conversation_id": { - "description": "Identifies the production run's agent trace, for judges to fetch.", - "type": [ - "string", - "null" - ] - }, - "id": { - "type": "string" - }, - "input": { - "additionalProperties": true, - "type": [ - "object", - "null" - ] - }, - "output": { - "additionalProperties": true, - "type": [ - "object", - "null" - ] - } - }, - "required": [ - "id" - ], - "type": "object" - }, "Request": { "properties": { "id": { - "format": "uint64", - "minimum": 0, "type": "integer" }, "method": { "type": "string" }, "params": { - "additionalProperties": true, "type": "object" } }, @@ -702,13 +602,9 @@ ] }, "id": { - "format": "uint64", - "minimum": 0, "type": "integer" }, - "result": { - "default": null - } + "result": {} }, "required": [ "id" @@ -716,15 +612,10 @@ "type": "object" }, "Score": { - "description": "A score from 0 to 1. A null score is diagnostic and doesn't affect the\nverdict.", + "description": "A judge's score from 0 to 1. A null score is recorded but doesn't count toward pass or fail.", "properties": { "explanation": { - "type": [ - "string", - "null" - ] - }, - "label": { + "description": "Why the judge gave this score.", "type": [ "string", "null" @@ -739,21 +630,20 @@ "type": "null" } ], - "description": "What an LLM judge spent producing this score." + "description": "The judge's own LLM usage." }, "metadata": { - "additionalProperties": true, + "description": "Anything else the judge recorded.", "type": [ "object", "null" ] }, "name": { + "description": "The judge's name.", "type": "string" }, "score": { - "default": null, - "format": "double", "type": [ "number", "null" @@ -766,14 +656,14 @@ "type": "object" }, "Seed": { - "description": "A fixture. `key` is a content hash, and seeds with the same key are set up\nonce and shared.", + "description": "A fixture. Seeds with the same `key`, a content hash, are set up once and shared.", "properties": { "cache": { - "description": "Cached seeds are reused across runs while their key matches. Uncached\nones are torn down after the run, e.g. because the agent mutates them.", + "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.", "type": "boolean" }, "credentials": { - "description": "What setting it up or tearing it down needs, its children's included.", + "description": "The credentials setting it up or tearing it down needs, including its children's.", "items": { "$ref": "#/$defs/Credential" }, @@ -810,19 +700,17 @@ "SeedSetupResult": { "properties": { "from_cache": { - "default": false, "description": "The seed's own cache had it, so nothing was set up.", "type": "boolean" }, "handle": { - "$ref": "#/$defs/Handle", - "default": {} + "$ref": "#/$defs/Handle" } }, "type": "object" }, "SeedTeardownParams": { - "description": "A cached seed is also removed from its own cache, before it's torn down.", + "description": "A cached seed is also removed from its own cache before it's torn down.", "properties": { "dataset": { "$ref": "#/$defs/DatasetRef" @@ -847,7 +735,7 @@ "properties": { "args.validate": { "additionalProperties": false, - "description": "Checks --args and --judge-args before anything is set up. Return an error to reject them.", + "description": "Returns what the run's runner and judges need, before anything is set up. Return an error to reject the args.", "properties": { "params": { "$ref": "#/$defs/ArgsValidateParams" @@ -862,15 +750,15 @@ ], "type": "object" }, - "case.execute": { + "case.judge": { "additionalProperties": false, - "description": "Runs the system under test on a case and returns its raw output, unscored.", + "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.", "properties": { "params": { - "$ref": "#/$defs/CaseExecuteParams" + "$ref": "#/$defs/CaseJudgeParams" }, "result": { - "$ref": "#/$defs/CaseExecuteResult" + "$ref": "#/$defs/CaseJudgeResult" } }, "required": [ @@ -879,15 +767,15 @@ ], "type": "object" }, - "case.judge": { + "case.run": { "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": "Runs the system under test on a case and returns its raw output, unscored.", "properties": { "params": { - "$ref": "#/$defs/CaseJudgeParams" + "$ref": "#/$defs/CaseRunParams" }, "result": { - "$ref": "#/$defs/CaseJudgeResult" + "$ref": "#/$defs/CaseRunResult" } }, "required": [ @@ -947,15 +835,15 @@ ], "type": "object" }, - "online.fetch": { + "online.collect": { "additionalProperties": false, - "description": "Returns at most limit production records from the window.", + "description": "Returns at most limit production runs from the window, as cases with their outputs.", "properties": { "params": { - "$ref": "#/$defs/OnlineFetchParams" + "$ref": "#/$defs/OnlineCollectParams" }, "result": { - "$ref": "#/$defs/OnlineFetchResult" + "$ref": "#/$defs/OnlineCollectResult" } }, "required": [ @@ -966,7 +854,7 @@ }, "online.judge": { "additionalProperties": false, - "description": "Scores a production record with the named online judges.", + "description": "Scores a collected case with the named online judges.", "properties": { "params": { "$ref": "#/$defs/OnlineJudgeParams" @@ -1016,12 +904,12 @@ }, "required": [ "args.validate", - "case.execute", "case.judge", + "case.run", "credentials.check", "credentials.login", "discover", - "online.fetch", + "online.collect", "online.judge", "seed.setup", "seed.teardown" @@ -1030,6 +918,6 @@ } }, "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "Protocol v1. core/PROTOCOL.md describes each method.", + "description": "The messages between eac and an SDK worker, protocol version 1. core/PROTOCOL.md describes each method.", "title": "Worker protocol" } diff --git a/core/src/schema/settings.rs b/core/src/schema/settings.rs new file mode 100644 index 0000000..f26b181 --- /dev/null +++ b/core/src/schema/settings.rs @@ -0,0 +1,41 @@ +use schemars::generate::SchemaSettings; +use schemars::transform::RecursiveTransform; +use schemars::Schema; +use serde_json::{json, Value}; + +/// Settings for the JSON Schemas eac publishes: draft 2020-12, without the +/// keywords schemars adds that tell a reader nothing. +pub fn schema_settings() -> SchemaSettings { + SchemaSettings::draft2020_12().with_transform(RecursiveTransform(tidy)) +} + +/// Drops Rust number formats like "double" and the `minimum: 0` of unsigned +/// ints, defaults, `additionalProperties: true`, which is the default anyway, +/// and anything beside a `const`. Rejoins descriptions, which keep the doc +/// comments' line breaks, into one line per paragraph. +fn tidy(schema: &mut Schema) { + let Some(obj) = schema.as_object_mut() else { + return; + }; + if obj.contains_key("const") { + obj.remove("type"); + obj.remove("minimum"); + } + if obj.get("minimum") == Some(&json!(0)) { + obj.remove("minimum"); + } + if obj.get("format").and_then(Value::as_str).is_some_and(|f| f != "date-time") { + obj.remove("format"); + } + if obj.get("additionalProperties") == Some(&Value::Bool(true)) { + obj.remove("additionalProperties"); + } + obj.remove("default"); + if let Some(Value::String(text)) = obj.get_mut("description") { + *text = text + .split("\n\n") + .map(|p| p.lines().map(str::trim).collect::>().join(" ")) + .collect::>() + .join("\n\n"); + } +} diff --git a/core/src/schema/types.rs b/core/src/schema/types.rs index d2a8572..f509253 100644 --- a/core/src/schema/types.rs +++ b/core/src/schema/types.rs @@ -8,43 +8,44 @@ use super::fields::{is_empty, is_true, nullable, yes}; pub type Object = Map; +/// An offline case, or a production run collected for online judging. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct Case { + /// Unique in its dataset. An online case's id. pub name: String, #[serde(default, skip_serializing_if = "is_empty")] pub input: Option, #[serde(default, skip_serializing_if = "is_empty")] pub expected_output: Option, - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Vec::is_empty" - )] + /// 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. + #[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`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub splits: Vec, /// A disabled case runs only when picked by name or by one of its splits. #[serde(default = "yes", skip_serializing_if = "is_true")] pub enabled: bool, - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Vec::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub seeds: Vec, - /// Names, for display only. Judges run inside the worker. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Vec::is_empty" - )] + /// 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, } -impl Case { - pub fn named(name: String, input: Option) -> Case { +impl Default for Case { + fn default() -> Case { Case { - name, - input, + name: String::new(), + input: None, expected_output: None, + output: None, + conversation_id: None, splits: vec![], enabled: true, seeds: vec![], @@ -53,51 +54,39 @@ impl Case { } } -/// A fixture. `key` is a content hash, and seeds with the same key are set up -/// once and shared. +/// A fixture. Seeds with the same `key`, a content hash, are set up once and +/// shared. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct Seed { pub name: String, pub key: String, - /// Cached seeds are reused across runs while their key matches. Uncached - /// ones are torn down after the run, e.g. because the agent mutates them. + /// 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. #[serde(default = "yes", skip_serializing_if = "is_true")] pub cache: bool, - /// What setting it up or tearing it down needs, its children's included. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Vec::is_empty" - )] + /// The credentials setting it up or tearing it down needs, including its + /// children's. + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub credentials: Vec, } -/// Credentials a seed, runner or judge needs, such as a token or a CLI -/// login. The SDK rebuilds it from `path` and `fields` to check it or log -/// in, so eac can check each distinct one once, before the phases that need -/// it. +/// 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. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct Credential { - /// Its class. + /// The credential's class, as a code reference. pub path: CodeRef, - /// What its class is built with. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Object::is_empty" - )] + /// The arguments its class is built with. + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Object::is_empty")] pub fields: Object, - /// Shown in status lines and prompts, e.g. "github". + /// Shown in status lines and prompts, like "github". pub name: String, /// How to set it up by hand, shown when it isn't set up. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "String::is_empty" - )] + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "String::is_empty")] pub setup_instructions: String, - /// It can only be set up by hand, so eac shows how instead of offering - /// to log in. + /// Can only be set up by hand, so eac shows the instructions instead of + /// offering to log in. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub manual: bool, } @@ -109,50 +98,38 @@ impl Credential { } } -/// What a seed's setup returned. It must be JSON-serializable because it's -/// written to seeds.json and read back by a later phase. +/// 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. It must be JSON-serializable because it's -/// written to seeds.json and read back by a later phase. +/// 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); -/// One thing the system already did, observed in production. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -pub struct Record { - pub id: String, - /// Identifies the production run's agent trace, for judges to fetch. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub conversation_id: Option, - #[serde(default, skip_serializing_if = "is_empty")] - pub input: Option, - #[serde(default, skip_serializing_if = "is_empty")] - pub output: Option, -} - -/// A score from 0 to 1. A null score is diagnostic and doesn't affect the -/// verdict. +/// A judge's score from 0 to 1. A null score is recorded but 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, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub label: 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, - /// What an LLM judge spent producing this score. + /// The judge's own LLM usage. #[serde(default, skip_serializing_if = "Option::is_none")] pub llm_judge_metrics: Option, } -/// LLM usage for one case, reported by the runner or derived from its trace. +/// LLM usage: tokens, calls, time and cost. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(default)] pub struct Metrics { @@ -172,8 +149,8 @@ pub struct Metrics { /// to the project root. pub type CodeRef = String; -/// Where a dataset's code is, per its dataset.yml. Every worker method that -/// needs the dataset gets this, so a worker can import it in any phase. +/// Where a dataset's code is, from its dataset.yml. Sent with every method that +/// needs the dataset, so any worker can import it. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct DatasetRef { /// The dataset's name, from its dataset.yml. @@ -181,23 +158,19 @@ pub struct DatasetRef { pub mode: Mode, /// The OfflineRunner or OnlineRunner, as a class or a configured instance. pub runner: CodeRef, - /// Offline: the sequence of Cases. + /// The dataset's cases. Offline only. #[serde(default, skip_serializing_if = "Option::is_none")] pub cases: Option, - /// Online: the judges `eac online judge --judge` picks from. - #[serde( - default, - deserialize_with = "nullable", - skip_serializing_if = "Vec::is_empty" - )] + /// The judges --judge picks from. Online only. + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Vec::is_empty")] pub judges: Vec, } -/// A judge named in a dataset.yml or in eac.yml's online.judges. +/// 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. Its scores keep the judge's own - /// name. + /// The name --judge and --judge-args use. Scores still carry the judge's + /// own name. pub name: String, /// A Judge class, built with no arguments, or a configured instance. pub path: CodeRef, @@ -209,3 +182,12 @@ pub enum Mode { Offline, Online, } + +impl Mode { + pub fn as_str(self) -> &'static str { + match self { + Mode::Offline => "offline", + Mode::Online => "online", + } + } +} diff --git a/core/src/schema/worker_methods.rs b/core/src/schema/worker_methods.rs index 233446e..948bb54 100644 --- a/core/src/schema/worker_methods.rs +++ b/core/src/schema/worker_methods.rs @@ -9,8 +9,7 @@ use serde_json::Value; use super::fields::{no_object, no_strings, nullable}; use super::types::{ - Case, Credential, DatasetRef, Handle, HandleSchema, Metrics, Mode, Object, Record, Score, - Seed, + Case, Credential, DatasetRef, Handle, HandleSchema, Metrics, Mode, Object, Score, Seed, }; #[derive(Serialize, JsonSchema)] @@ -18,19 +17,13 @@ pub struct DiscoverParams<'a> { pub dataset: &'a DatasetRef, } -/// What only the dataset's code knows. Its dataset.yml says the rest. +/// What eac learns by importing the dataset's code. Its dataset.yml covers the +/// rest. #[derive(Default, Deserialize, JsonSchema)] pub struct DiscoverResult { - /// Offline: every case. + /// Every case. Offline only. #[serde(default, deserialize_with = "nullable")] pub cases: Vec, - /// JSON Schema of the runner's --args. - #[serde(default)] - pub args_schema: Option, - /// JSON Schema of each judge's --judge-args, by judge name, for the - /// judges that take any. - #[serde(default, deserialize_with = "nullable")] - pub judge_args_schemas: BTreeMap, } #[derive(Serialize, JsonSchema)] @@ -38,8 +31,9 @@ pub struct ArgsValidateParams<'a> { pub dataset: &'a DatasetRef, pub mode: Mode, pub args: &'a Object, - /// Online: the judges picked. Offline: judges that replace every case's - /// own, as in a comparison. Empty keeps each case's judges. + /// 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. #[serde(skip_serializing_if = "no_strings")] pub judges: &'a [String], /// --judge-args, by judge name. @@ -49,13 +43,10 @@ pub struct ArgsValidateParams<'a> { #[derive(Default, Deserialize, JsonSchema)] pub struct ArgsValidateResult { - /// The args with defaults filled in. Absent keeps them as sent. - #[serde(default)] - pub args: Option, - /// What the runner needs with these args. + /// The credentials the runner needs. #[serde(default, deserialize_with = "nullable")] pub runner_credentials: Vec, - /// What each of the run's judges needs, by the name cases and --judge use. + /// The credentials each of the run's judges needs, by judge name. #[serde(default, deserialize_with = "nullable")] pub judge_credentials: BTreeMap>, } @@ -79,9 +70,8 @@ pub struct CredentialsLoginParams<'a> { #[derive(Default, Deserialize, JsonSchema)] pub struct CredentialsLoginResult { - /// Environment variables the credential needs. eac gives them to every - /// process it starts, and saves them for later commands once the - /// credential checks out. + /// Environment variables the credential sets. eac passes them to every + /// process it starts and saves them once the credential checks out. #[serde(default, deserialize_with = "nullable")] pub env: BTreeMap, } @@ -102,7 +92,7 @@ pub struct SeedSetupResult { pub from_cache: bool, } -/// A cached seed is also removed from its own cache, before it's torn down. +/// 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, @@ -112,25 +102,25 @@ pub struct SeedTeardownParams<'a> { } #[derive(Serialize, JsonSchema)] -pub struct CaseExecuteParams<'a> { +pub struct CaseRunParams<'a> { pub dataset: &'a DatasetRef, pub case: &'a Case, - /// Handles by seed name. + /// Each seed's handle, by seed name. #[serde(skip_serializing_if = "BTreeMap::is_empty")] #[schemars(with = "BTreeMap")] pub seeds: BTreeMap<&'a str, &'a Handle>, #[serde(skip_serializing_if = "no_object")] pub args: &'a Object, - /// Tag the agent run with this so its trace can be fetched for judging. + /// Tag the agent's run with this so judges can fetch its trace. pub conversation_id: &'a str, } #[derive(Default, Deserialize, JsonSchema)] -pub struct CaseExecuteResult { - /// Must be JSON-serializable, since it's saved for the judge phase. +pub struct CaseRunResult { + /// Saved for the judge phase, so it must be JSON. #[serde(default)] pub output: Option, - /// Overrides the conversation id eac sent, if the agent used another. + /// The conversation ID the agent used, if it isn't the one eac sent. #[serde(default)] pub conversation_id: Option, #[serde(default)] @@ -140,12 +130,13 @@ pub struct CaseExecuteResult { #[derive(Serialize, JsonSchema)] pub struct CaseJudgeParams<'a> { pub dataset: &'a DatasetRef, - pub case: &'a Case, - /// Judges by name that replace the case's own, as in a comparison. Empty - /// keeps the case's own. + /// 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. #[serde(skip_serializing_if = "no_strings")] pub judges: &'a [String], - pub output: &'a Option, + /// 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")] @@ -155,41 +146,38 @@ pub struct CaseJudgeParams<'a> { #[serde(skip_serializing_if = "no_object")] pub judge_args: &'a Object, /// The agent trace an earlier judge phase saved. Without one, the judges - /// may fetch it by conversation_id. + /// may fetch it by the case's conversation_id. #[serde(skip_serializing_if = "Option::is_none")] pub trace: Option<&'a Value>, - /// The id the agent run was tagged with. - #[serde(skip_serializing_if = "Option::is_none")] - pub conversation_id: Option<&'a str>, - /// The production agent, from dataset.yml. + /// The agent named in dataset.yml. #[serde(skip_serializing_if = "Option::is_none")] pub agent: Option<&'a str>, - /// When the case ran. + /// When the runner started. #[serde(skip_serializing_if = "Option::is_none")] pub started_at: Option>, #[serde(skip_serializing_if = "Option::is_none")] pub ended_at: Option>, } -/// Also what online.judge returns. +/// What case.judge and online.judge return. #[derive(Default, Deserialize, JsonSchema)] pub struct CaseJudgeResult { #[serde(default, deserialize_with = "nullable")] pub scores: Vec, - /// The agent trace a judge fetched, if eac didn't send one. eac saves it, - /// so judging again doesn't fetch it again. + /// The agent trace a judge fetched, if eac didn't send one. eac saves it + /// for later judge runs. #[serde(default)] pub trace: Value, - /// The LLM usage the fetched trace records. It replaces what the runner + /// The LLM usage recorded in the fetched trace. It replaces what the runner /// reported. #[serde(default)] pub trace_metrics: Option, } #[derive(Serialize, JsonSchema)] -pub struct OnlineFetchParams<'a> { +pub struct OnlineCollectParams<'a> { pub dataset: &'a DatasetRef, - /// RFC 3339. Only records in [since, until) are returned. + /// RFC 3339. Return runs from since up to, but not including, until. pub since: &'a str, pub until: &'a str, pub limit: usize, @@ -198,21 +186,24 @@ pub struct OnlineFetchParams<'a> { } #[derive(Default, Deserialize, JsonSchema)] -pub struct OnlineFetchResult { +pub struct OnlineCollectResult { + /// One case per production run, each with its `output` and, if it has + /// one, its `conversation_id`. #[serde(default, deserialize_with = "nullable")] - pub records: Vec, + pub cases: Vec, } #[derive(Serialize, JsonSchema)] pub struct OnlineJudgeParams<'a> { pub dataset: &'a DatasetRef, - pub record: Record, - /// The judges picked, by the names their YAML gives them. + /// A collected case, with its `output` and `conversation_id`. + pub case: Case, + /// The judges picked, by their YAML names. 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 record's conversation_id identifies its trace. + /// As in case.judge. The case's conversation_id identifies the trace. #[serde(skip_serializing_if = "Option::is_none")] pub trace: Option<&'a Value>, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/core/src/worker/interrupted.rs b/core/src/worker/interrupted.rs deleted file mode 100644 index 38383af..0000000 --- a/core/src/worker/interrupted.rs +++ /dev/null @@ -1,11 +0,0 @@ -/// Returned when the user interrupts eac mid-call. -#[derive(Debug)] -pub struct Interrupted; - -impl std::fmt::Display for Interrupted { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("interrupted") - } -} - -impl std::error::Error for Interrupted {} diff --git a/core/src/worker/logs.rs b/core/src/worker/logs.rs index 674a98a..1383773 100644 --- a/core/src/worker/logs.rs +++ b/core/src/worker/logs.rs @@ -5,37 +5,23 @@ use std::io::{BufRead, BufReader, Read}; use std::process::Child; use std::thread::{self, JoinHandle}; -/// Receives one line of the worker's stdout ("info") or stderr ("warn"). -pub type LogFn = fn(level: &str, line: &str); +use crate::report; -/// Forwards the child's stdout as "info" lines and its stderr as "warn" -/// lines, each on its own thread, until they close. -pub fn forward_output(child: &mut Child, on_log: LogFn) -> Vec> { - vec![ - forward( - child.stdout.take().expect("stdout is piped"), - "info", - on_log, - ), - forward( - child.stderr.take().expect("stderr is piped"), - "warn", - on_log, - ), - ] +/// Forwards whichever of the child's stdout ("info") and stderr ("warn") are +/// piped, each on its own thread, until they close. +pub fn forward_output(child: &mut Child) -> Vec> { + let stdout = child.stdout.take().map(|s| forward(s, "info")); + let stderr = child.stderr.take().map(|s| forward(s, "warn")); + stdout.into_iter().chain(stderr).collect() } -fn forward( - stream: impl Read + Send + 'static, - level: &'static str, - on_log: LogFn, -) -> JoinHandle<()> { +fn forward(stream: impl Read + Send + 'static, level: &'static str) -> JoinHandle<()> { thread::spawn(move || { let mut reader = BufReader::new(stream); let mut buf = Vec::new(); while matches!(reader.read_until(b'\n', &mut buf), Ok(n) if n > 0) { let line = String::from_utf8_lossy(&buf); - on_log(level, line.trim_end_matches(&['\n', '\r'][..])); + report::worker_log(level, line.trim_end_matches(['\n', '\r'])); buf.clear(); } }) diff --git a/core/src/worker/mod.rs b/core/src/worker/mod.rs index 37e513a..2dafbfa 100644 --- a/core/src/worker/mod.rs +++ b/core/src/worker/mod.rs @@ -5,13 +5,44 @@ //! JSON object per line. stdout and stderr stay free for user code and are //! forwarded as logs. Closing fd 3 tells the process to exit. -mod interrupted; mod logs; mod pipes; mod pool; mod process; mod responses; -pub use interrupted::Interrupted; +use std::sync::atomic::{AtomicBool, Ordering}; + pub use pool::each; pub use process::Worker; + +static INTERRUPTED: AtomicBool = AtomicBool::new(false); + +/// Called on Ctrl-C/SIGTERM. In-flight worker calls give up once it's set. +pub fn interrupt() { + INTERRUPTED.store(true, Ordering::Relaxed); +} + +pub fn interrupted() -> bool { + INTERRUPTED.load(Ordering::Relaxed) +} + +/// Returned when the user interrupts eac mid-call. +#[derive(Debug)] +pub struct Interrupted; + +impl std::fmt::Display for Interrupted { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("interrupted") + } +} + +impl std::error::Error for Interrupted {} + +/// Fails with Interrupted once the user has interrupted eac. +pub fn check_interrupted() -> anyhow::Result<()> { + if interrupted() { + return Err(Interrupted.into()); + } + Ok(()) +} diff --git a/core/src/worker/pool.rs b/core/src/worker/pool.rs index 50898cf..6d7d4e8 100644 --- a/core/src/worker/pool.rs +++ b/core/src/worker/pool.rs @@ -8,8 +8,7 @@ use std::thread; use anyhow::{anyhow, Result}; -use super::interrupted::Interrupted; -use super::process::Worker; +use super::{check_interrupted, 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 @@ -18,29 +17,22 @@ use super::process::Worker; /// /// 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. -pub fn each( +pub fn each( workers: &mut [Worker], - cancel: &AtomicBool, jobs: impl IntoIterator>, call: impl Fn(&mut Worker, J) -> Result + Sync, -) -> Result> -where - J: Send, - R: Send, -{ +) -> Result> { if let [worker] = workers { let mut out = Vec::new(); for job in jobs { - if cancel.load(Ordering::Relaxed) { - return Err(Interrupted.into()); - } + check_interrupted()?; out.push(call(worker, job?)?); } return Ok(out); } let failed = AtomicBool::new(false); - let stopped = || failed.load(Ordering::Relaxed) || cancel.load(Ordering::Relaxed); + 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); @@ -50,6 +42,7 @@ where for worker in workers.iter_mut() { let (job_rx, done_tx, call, failed) = (&job_rx, done_tx.clone(), &call, &failed); 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 { return; @@ -72,8 +65,8 @@ where let mut first_err = None; let mut made = 0; for job in jobs { - if cancel.load(Ordering::Relaxed) { - first_err = Some(Interrupted.into()); + if let Err(e) = check_interrupted() { + first_err = Some(e); break; } if failed.load(Ordering::Relaxed) { @@ -107,8 +100,6 @@ where return Err(e); } // Every job made ran unless Ctrl-C skipped some. - out.into_iter() - .map(|r| r.ok_or_else(|| Interrupted.into())) - .collect() + out.into_iter().map(|r| r.ok_or_else(|| Interrupted.into())).collect() }) } diff --git a/core/src/worker/process.rs b/core/src/worker/process.rs index 9ba63d3..fbd6ea5 100644 --- a/core/src/worker/process.rs +++ b/core/src/worker/process.rs @@ -1,19 +1,15 @@ use std::io::{self, PipeWriter, Write}; use std::os::fd::AsFd; -use std::path::Path; use std::process::{Child, Command, Stdio}; -use std::sync::atomic::AtomicBool; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; -use anyhow::{anyhow, bail, Context, Result}; +use anyhow::{bail, Context, Result}; use serde::de::DeserializeOwned; use serde::Serialize; -use super::interrupted::Interrupted; -use super::logs::{self, LogFn}; -use super::pipes; use super::responses::Responses; +use super::{logs, pipes, Interrupted}; use crate::schema::{Ready, Request, Response, VERSION}; /// How long a closing worker gets to exit before it is killed. @@ -31,92 +27,54 @@ pub struct Worker { logs: Vec>, } -/// What a worker's stdin, stdout and stderr are connected to. -#[derive(Clone, Copy)] -enum Output { - /// No stdin, and each line of output goes to the LogFn. - Logs(LogFn), - /// eac's terminal, so the process can prompt. - Terminal, -} - impl Worker { - /// Starts cmd in dir and waits for its ready line. - pub fn spawn( - label: &str, - cmd: Command, - dir: &Path, - on_log: LogFn, - cancel: &AtomicBool, - ) -> Result { - Worker::start(label, cmd, dir, Output::Logs(on_log), cancel) + /// Starts cmd and waits for its ready line. Its stdout and stderr are + /// forwarded as logs. + pub fn spawn(label: &str, mut cmd: Command) -> Result { + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + Worker::start(label, cmd) } /// Like spawn, but on eac's terminal so the process can prompt, e.g. to /// log in. Its stdout goes to eac's stderr, which keeps eac's stdout for /// output meant to be piped. - pub fn spawn_attached( - label: &str, - cmd: Command, - dir: &Path, - cancel: &AtomicBool, - ) -> Result { - Worker::start(label, cmd, dir, Output::Terminal, cancel) + pub fn spawn_attached(label: &str, mut cmd: Command) -> Result { + let stdout = io::stderr().as_fd().try_clone_to_owned()?; + cmd.stdin(Stdio::inherit()).stdout(stdout).stderr(Stdio::inherit()); + Worker::start(label, cmd) } - fn start( - label: &str, - mut cmd: Command, - dir: &Path, - output: Output, - cancel: &AtomicBool, - ) -> Result { + fn start(label: &str, mut cmd: Command) -> Result { let program = cmd.get_program().to_string_lossy().into_owned(); - cmd.current_dir(dir); - match output { - Output::Logs(_) => cmd - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()), - Output::Terminal => cmd - .stdin(Stdio::inherit()) - .stdout(io::stderr().as_fd().try_clone_to_owned()?) - .stderr(Stdio::inherit()), - }; let (mut child, requests, responses) = pipes::spawn(&mut cmd).with_context(|| format!("starting {label} ({program})"))?; - let logs = match output { - Output::Logs(on_log) => logs::forward_output(&mut child, on_log), - Output::Terminal => vec![], - }; - // From here on, an early return closes the worker via Drop. let worker = Worker { label: label.to_string(), + logs: logs::forward_output(&mut child), child, requests: Some(requests), responses: Responses::read(responses), next_id: 0, - logs, }; - worker.ready(cancel)?; + worker.ready()?; Ok(worker) } /// Waits for the ready line and checks its protocol version. - fn ready(&self, cancel: &AtomicBool) -> Result<()> { - let label = &self.label; - let ready = match self.responses.next_line(cancel) { + fn ready(&self) -> Result<()> { + let ready = match self.responses.next_line() { Ok(line) => line.and_then(|l| serde_json::from_str::(&l).ok()), Err(e) if e.is::() => return Err(e), Err(_) => None, }; let Some(ready) = ready else { - bail!("{label} exited before it was ready; see its output above"); + bail!("{} exited before it was ready; see its output above", self.label); }; if ready.protocol != VERSION { bail!( - "{label} speaks protocol v{}, CLI speaks v{VERSION}: upgrade it", + "{} speaks protocol v{}, CLI speaks v{VERSION}: upgrade it", + self.label, ready.protocol ); } @@ -129,25 +87,20 @@ impl Worker { /// Sends one request and decodes its result. A missing or null result /// decodes as T's default. - pub fn call(&mut self, cancel: &AtomicBool, method: &str, params: P) -> Result - where - T: DeserializeOwned + Default, - P: Serialize, - { + pub fn call( + &mut self, + method: &str, + params: impl Serialize, + ) -> Result { self.next_id += 1; let id = self.next_id; let mut line = serde_json::to_vec(&Request { id, method, params })?; line.push(b'\n'); - let requests = self - .requests - .as_mut() - .ok_or_else(|| anyhow!("worker is closed"))?; - requests - .write_all(&line) - .with_context(|| format!("sending {method} to {}", self.label))?; + 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(cancel) { + 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), diff --git a/core/src/worker/responses.rs b/core/src/worker/responses.rs index 51d3ceb..01a5e6d 100644 --- a/core/src/worker/responses.rs +++ b/core/src/worker/responses.rs @@ -2,14 +2,13 @@ //! notice an interrupt. use std::io::{self, BufRead, BufReader, PipeReader}; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; use std::thread; use std::time::Duration; use anyhow::Result; -use super::interrupted::Interrupted; +use super::{interrupted, Interrupted}; /// How often a blocked call checks whether the user interrupted. const POLL: Duration = Duration::from_millis(100); @@ -24,17 +23,10 @@ impl Responses { pub fn read(pipe: PipeReader) -> Responses { let (tx, lines) = mpsc::channel(); thread::spawn(move || { - let mut reader = BufReader::new(pipe); - loop { - let mut line = String::new(); - match reader.read_line(&mut line) { - Ok(0) => return, - Ok(_) if tx.send(Ok(line)).is_ok() => {} - Ok(_) => return, - Err(e) => { - let _ = tx.send(Err(e)); - return; - } + for line in BufReader::new(pipe).lines() { + let failed = line.is_err(); + if tx.send(line).is_err() || failed { + return; } } }); @@ -42,15 +34,12 @@ impl Responses { } /// Waits for the next response line. None means the worker closed fd 4. - pub fn next_line(&self, cancel: &AtomicBool) -> Result> { + pub fn next_line(&self) -> Result> { loop { match self.lines.recv_timeout(POLL) { - Ok(Ok(line)) => return Ok(Some(line)), - Ok(Err(e)) => return Err(e.into()), + Ok(line) => return Ok(Some(line?)), Err(RecvTimeoutError::Disconnected) => return Ok(None), - Err(RecvTimeoutError::Timeout) if cancel.load(Ordering::Relaxed) => { - return Err(Interrupted.into()) - } + Err(RecvTimeoutError::Timeout) if interrupted() => return Err(Interrupted.into()), Err(RecvTimeoutError::Timeout) => {} } } diff --git a/core/tests/cli.rs b/core/tests/cli.rs index 4610783..7f4fec5 100644 --- a/core/tests/cli.rs +++ b/core/tests/cli.rs @@ -31,20 +31,12 @@ struct Ran { impl Ran { fn code(&self, want: i32) -> &Ran { - assert_eq!( - self.code, want, - "stdout:\n{}\nstderr:\n{}", - self.stdout, self.stderr - ); + assert_eq!(self.code, want, "stdout:\n{}\nstderr:\n{}", self.stdout, self.stderr); self } fn says(&self, text: &str) -> &Ran { - assert!( - self.stderr.contains(text), - "{text:?} not in stderr:\n{}", - self.stderr - ); + assert!(self.stderr.contains(text), "{text:?} not in stderr:\n{}", self.stderr); self } } @@ -113,17 +105,12 @@ impl Project { let Ok(raw) = fs::read_to_string(self.path(file)) else { return vec![]; }; - raw.lines() - .map(|l| serde_json::from_str(l).unwrap()) - .collect() + raw.lines().map(|l| serde_json::from_str(l).unwrap()).collect() } /// The worker's log entries for event. fn events(&self, event: &str) -> Vec { - self.lines("worker-log.jsonl") - .into_iter() - .filter(|e| e["event"] == event) - .collect() + self.lines("worker-log.jsonl").into_iter().filter(|e| e["event"] == event).collect() } fn runs(&self) -> Vec { @@ -162,8 +149,8 @@ fn names<'a>(values: &'a [Value], key: &str) -> Vec<&'a str> { values.iter().map(|v| v[key].as_str().unwrap()).collect() } -fn scenarios(results: &Value) -> Vec<&str> { - names(results["scenarios"].as_array().unwrap(), "name") +fn case_names(results: &Value) -> Vec<&str> { + names(results["cases"].as_array().unwrap(), "name") } #[test] @@ -178,28 +165,19 @@ fn run_writes_results_and_fails_on_a_wrong_case() { let results = p.json(&p.latest().join("results/chat.json")); // Disabled cases stay out of a bare run. - assert_eq!(scenarios(&results), ["greets", "wrong"]); - let greets = &results["scenarios"][0]; + assert_eq!(case_names(&results), ["greets", "wrong"]); + let greets = &results["cases"][0]; assert_eq!(greets["status"], "passed"); - assert_eq!(results["scenarios"][1]["status"], "failed"); + assert_eq!(results["cases"][1]["status"], "failed"); assert_eq!(greets["otel_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-")); - assert_eq!( - results["metadata"]["args"], - json!({"model": "small"}), - "the SDK's defaults are recorded" - ); + assert_eq!(greets["attributes"], json!({"turns": 1, "splits": ["smoke"]})); + assert!(greets["conversation_id"].as_str().unwrap().starts_with("eval-")); + assert!(results["metadata"].get("args").is_none(), "args are recorded as given, and none were"); assert_eq!(results["metadata"]["agent"], "chat_agent"); + assert_eq!(results["schema_version"], 2); assert_eq!(results["source"]["trigger"], "local"); - assert_eq!(results["summary"]["failed"], 1); + assert!(results.get("summary").is_none(), "totals come from the cases"); // The worker got the dataset's code references from its dataset.yml, // made relative to the project root, where it runs. @@ -228,8 +206,7 @@ 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); + p.eac(&["offline", "seed", "--teardown", "--run", &id]).code(0); assert_eq!(names(&p.events("seed_teardown"), "name"), ["scratch"]); } @@ -237,19 +214,13 @@ fn phases_run_separately() { fn cached_seeds_are_reused_until_pruned() { let p = Project::new(&base()); p.eac(&["offline", "run", "--split", "smoke"]).code(0); - p.eac(&["offline", "run", "--split", "smoke"]) - .code(0) - .says("project (project-) cached"); + p.eac(&["offline", "run", "--split", "smoke"]).code(0).says("project (project-) cached"); assert_eq!(p.events("seed_setup").len(), 1); // A case still uses it, so only --all tears it down. - p.eac(&["offline", "prune"]) - .code(0) - .says("tore down 0 unused cached seeds"); + p.eac(&["offline", "prune"]).code(0).says("tore down 0 unused cached seeds"); assert!(p.events("seed_teardown").is_empty()); - p.eac(&["offline", "prune", "--all"]) - .code(0) - .says("tore down 1 cached seed"); + p.eac(&["offline", "prune", "--all"]).code(0).says("tore down 1 cached seed"); assert_eq!(names(&p.events("seed_teardown"), "name"), ["project"]); assert_eq!(p.json(&p.path(".eac/seed-cache.json"))["seeds"], json!({})); } @@ -264,9 +235,7 @@ fn prune_tears_down_cached_seeds_no_case_uses() { let source = fs::read_to_string(&dataset).unwrap(); fs::write(&dataset, source.replace("project-1", "project-2")).unwrap(); - p.eac(&["offline", "prune"]) - .code(0) - .says("tore down 1 unused cached seed"); + p.eac(&["offline", "prune"]).code(0).says("tore down 1 unused cached seed"); // It's torn down as cached and with the key it was set up with, so the // seed can forget that key in its own cache. let torn = p.events("seed_teardown"); @@ -279,10 +248,7 @@ fn prune_tears_down_cached_seeds_no_case_uses() { fn selection_checks_names_and_shards_round_robin() { let p = Project::new(&base()); let listed = p.eac(&["list", "--split", "smoke"]); - listed - .code(0) - .says("chat/greets [smoke]") - .says("chat/slow [smoke] (disabled)"); + listed.code(0).says("chat/greets [smoke]").says("chat/slow [smoke] (disabled)"); assert!(!listed.stderr.contains("chat/wrong")); p.eac(&["offline", "run", "--case", "smoke"]) @@ -295,32 +261,20 @@ fn selection_checks_names_and_shards_round_robin() { // Two enabled cases at one per shard. assert_eq!(p.eac(&["offline", "shards"]).stdout.trim(), "2"); p.eac(&["offline", "run", "--shard-index", "1"]).code(1); - assert_eq!( - scenarios(&p.json(&p.latest().join("results/chat.json"))), - ["wrong"] - ); - p.eac(&["offline", "run", "--shard-index", "2"]) - .code(2) - .says("out of range"); + assert_eq!(case_names(&p.json(&p.latest().join("results/chat.json"))), ["wrong"]); + p.eac(&["offline", "run", "--shard-index", "2"]).code(2).says("out of range"); } #[test] fn concurrency_runs_cases_at_once_on_workers_of_their_own() { let p = Project::new(&base()); - p.edit( - "evals/dataset.yml", - " shard_config:", - " concurrency: 4\n shard_config:", - ); + p.edit("evals/dataset.yml", " shard_config:", " concurrency: 4\n shard_config:"); p.write("rendezvous", "2"); let ran = p.eac(&["offline", "run"]); ran.code(1).says("starting python worker 2"); - assert!( - !ran.stderr.contains("python worker 3"), - "no more workers than cases" - ); + assert!(!ran.stderr.contains("python worker 3"), "no more workers than cases"); // Both cases ran at once, then were judged at once, each on its own worker. - for event in ["execute", "judge"] { + for event in ["run", "judge"] { let calls = p.events(event); assert_eq!(calls.len(), 2, "{event}"); assert!(calls.iter().all(|c| c["together"] == true), "{event}: {calls:?}"); @@ -328,41 +282,32 @@ fn concurrency_runs_cases_at_once_on_workers_of_their_own() { } // Results keep the cases' order. let results = p.json(&p.latest().join("results/chat.json")); - assert_eq!(scenarios(&results), ["greets", "wrong"]); - assert_eq!(results["summary"]["failed"], 1); + assert_eq!(case_names(&results), ["greets", "wrong"]); + assert_eq!(names(results["cases"].as_array().unwrap(), "status"), ["passed", "failed"]); // --concurrency overrides dataset.yml. fs::remove_file(p.path("rendezvous")).unwrap(); fs::remove_file(p.path("worker-log.jsonl")).unwrap(); p.eac(&["offline", "run", "--concurrency", "1"]).code(1); let discovered = &p.events("discover")[0]; - for call in p.events("execute").iter().chain(&p.events("judge")) { + for call in p.events("run").iter().chain(&p.events("judge")) { assert_eq!(call["pid"], discovered["pid"], "one worker for everything"); } - p.eac(&["offline", "run", "--concurrency", "0"]) - .code(2) - .says("at least 1"); + p.eac(&["offline", "run", "--concurrency", "0"]).code(2).says("at least 1"); } #[test] -fn online_records_are_judged_at_once_with_concurrency() { +fn online_cases_are_judged_at_once_with_concurrency() { let p = Project::new(&base()); p.write("rendezvous", "2"); - let args = [ - "online", - "run", - "--judge", - "nonempty", - "--concurrency", - "2", - ]; + let args = ["online", "run", "--judge", "nonempty", "--concurrency", "2"]; p.eac(&args).code(0); let calls = p.events("online_judge"); assert_eq!(calls.len(), 2); assert!(calls.iter().all(|c| c["together"] == true), "{calls:?}"); assert_ne!(calls[0]["pid"], calls[1]["pid"]); let results = p.json(&p.latest().join("results/chat.json")); - assert_eq!(scenarios(&results), ["trace_0", "trace_1"]); + assert_eq!(case_names(&results), ["trace_0", "trace_1"]); } #[test] @@ -378,27 +323,73 @@ fn invalid_args_fail_before_anything_is_set_up() { #[test] fn args_variant_and_metadata_reach_the_runner_and_results() { let p = Project::new(&base()); - let args = [ - "--args", - r#"{"model": "big"}"#, - "--variant", - "v2", - "--meta", - "team=evals", - ]; - p.eac(&[&["offline", "run", "--split", "smoke"][..], &args].concat()) - .code(0); + let args = ["--args", r#"{"model": "big"}"#, "--variant", "v2", "--meta", "team=evals"]; + p.eac(&[&["offline", "run", "--split", "smoke"][..], &args].concat()).code(0); - assert!(p - .events("execute") - .iter() - .all(|e| e["args"] == json!({"model": "big"}))); + assert!(p.events("run").iter().all(|e| e["args"] == json!({"model": "big"}))); let meta = &p.json(&p.latest().join("results/chat.json"))["metadata"]; assert_eq!(meta["variant"], "v2"); assert_eq!(meta["team"], "evals"); assert_eq!(meta["args"]["model"], "big"); } +#[test] +fn cases_without_a_score_are_skipped_and_dont_fail_the_run() { + let p = Project::new(&base()); + p.edit("evals/chat_eval.py", "\"score\": 1.0 if ok else 0.0,", "\"score\": None,"); + p.eac(&["offline", "run"]).code(0).says("2 skipped"); + + 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_pull_request_run_records_its_source_from_github_actions() { + let p = Project::new(&base()); + p.write( + "event.json", + r#"{"pull_request": {"head": {"sha": "head"}, "base": {"sha": "base"}, "user": {"login": "author"}}}"#, + ); + let event = p.path("event.json"); + let env = [ + ("GITHUB_ACTIONS", "true"), + ("GITHUB_EVENT_NAME", "pull_request"), + ("GITHUB_EVENT_PATH", event.to_str().unwrap()), + ("GITHUB_REF", "refs/pull/7/merge"), + ("GITHUB_SHA", "merge"), + ("GITHUB_HEAD_REF", "feature"), + ("GITHUB_ACTOR", "actor"), + ("GITHUB_SERVER_URL", "https://github.com"), + ("GITHUB_REPOSITORY", "getsentry/eac"), + ("GITHUB_RUN_ID", "42"), + ]; + p.eac_with(".", &env, &["offline", "run", "--case", "greets"]).code(0); + + let results = p.json(&p.latest().join("results/chat.json")); + assert_eq!( + results["source"], + json!({ + "trigger": "pull_request", + "actor": "actor", + "sha": "head", + "base_sha": "base", + "branch": "feature", + "pr_number": 7, + "pr_url": "https://github.com/getsentry/eac/pull/7", + "pr_author": "author", + "commit_url": "https://github.com/getsentry/eac/commit/head", + "run_url": "https://github.com/getsentry/eac/actions/runs/42", + }) + ); + // It isn't repeated in metadata. + let meta = results["metadata"].as_object().unwrap(); + for key in ["sha", "branch_name", "pr_number", "pr_url", "ci_run_url"] { + assert!(!meta.contains_key(key), "{key} in metadata"); + } +} + #[test] fn judges_fetch_traces_that_are_saved_for_judging_again() { let p = Project::new(&base()); @@ -416,8 +407,8 @@ fn judges_fetch_traces_that_are_saved_for_judging_again() { assert_eq!(p.json(&run.join("traces/chat/greets.json"))["trace"]["spans"], 3); let metrics = |p: &Project| { let results = p.json(&run.join("results/chat.json")); - let greets = &results["scenarios"][0]; - (greets["otel_metrics"]["total_tokens"].clone(), greets["cost_usd"].clone()) + let greets = &results["cases"][0]; + (greets["otel_metrics"]["total_tokens"].clone(), greets["otel_metrics"]["cost_usd"].clone()) }; assert_eq!(metrics(&p), (json!(99.0), json!(0.5))); @@ -432,17 +423,13 @@ fn judges_fetch_traces_that_are_saved_for_judging_again() { fn a_seed_can_come_from_its_own_cache() { let p = Project::new(&base()); p.write("shared-seeds.json", r#"{"project-1": {"id": "shared"}}"#); - p.eac(&["offline", "run", "--split", "smoke"]) - .code(0) - .says("project came 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"})); // 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"); + p.eac(&["offline", "run", "--split", "smoke"]).code(0).says("project (project-) cached"); assert_eq!(p.events("seed_load").len(), 1); } @@ -455,44 +442,32 @@ fn compare_runs_each_arm_with_its_args() { let runs = p.runs(); assert_eq!(runs.len(), 2); - let manifests: Vec = runs - .iter() - .map(|r| p.json(&r.join("manifest.json"))) - .collect(); + let manifests: Vec = runs.iter().map(|r| p.json(&r.join("manifest.json"))).collect(); assert_eq!(names(&manifests, "variant"), ["small", "big"]); - assert_eq!( - manifests[1]["comparison"], - json!({"comparison": "models", "arm": "big"}) - ); + assert_eq!(manifests[1]["comparison"], json!({"comparison": "models", "arm": "big"})); assert_eq!(manifests[1]["datasets"][0]["args"], json!({"model": "big"})); // The cached seed was set up once and shared by both arms. assert_eq!(p.events("seed_setup").len(), 1); // The comparison names no judges, so each case keeps its own. assert!(p.events("judge").iter().all(|e| e["judges"] == json!([]))); - p.eac(&["offline", "compare", "nope"]) - .code(2) - .says("available: chat.models, chat.strict"); + p.eac(&["offline", "compare", "nope"]).code(2).says("available: chat.models, chat.strict"); } #[test] fn a_comparisons_judges_score_every_case() { let p = Project::new(&base()); - p.eac(&["offline", "compare", "strict", "--split", "smoke"]) - .code(0); + p.eac(&["offline", "compare", "strict", "--split", "smoke"]).code(0); assert!(p.events("judge").iter().all(|e| e["judges"] == json!(["matches"]))); - assert!(p - .events("validate") - .iter() - .all(|e| e["judges"] == json!(["matches"]))); + assert!(p.events("validate").iter().all(|e| e["judges"] == json!(["matches"]))); let manifest = p.json(&p.latest().join("manifest.json")); assert_eq!(manifest["datasets"][0]["judges"], json!(["matches"])); let p = Project::new(&base()); p.edit("evals/dataset.yml", "judges: [matches]", "judges: [exact]"); - p.eac(&["offline", "compare", "strict"]) - .code(2) - .says("chat.strict judges with exact, which no case it compares uses; their judges: matches"); + p.eac(&["offline", "compare", "strict"]).code(2).says( + "chat.strict judges with exact, which no case it compares uses; their judges: matches", + ); } #[test] @@ -506,10 +481,7 @@ fn judge_args_must_name_a_judge_in_the_run() { "--judge-args", r#"{"politeness": {"strict": true}}"#, ]; - p.eac(&args) - .code(2) - .says("--judge-args names politeness") - .says("its judges: polite"); + p.eac(&args).code(2).says("--judge-args names politeness").says("its judges: polite"); } #[test] @@ -539,29 +511,25 @@ fn online_run_fetches_the_window_with_judge_args() { assert_eq!(discovered["mode"], "online"); assert_eq!(discovered["runner"], "./evals/chat_eval.py:Prod"); assert_eq!(names(discovered["judges"].as_array().unwrap(), "name"), ["nonempty", "polite"]); - let fetched = &p.events("fetch")[0]; + let fetched = &p.events("collect")[0]; assert_eq!(fetched["since"], "2026-10-31T10:00:00Z"); assert_eq!(fetched["until"], "2026-10-31T12:00:00Z"); assert_eq!(fetched["limit"], 5); - assert_eq!(fetched["args"], json!({"region": "us"})); + assert_eq!(fetched["args"], json!({})); assert!(p .events("online_judge") .iter() - .all(|e| e["judge_args"] == json!({"polite": {"strict": true}}) && e["agent"] == "chat_agent")); + .all(|e| e["judge_args"] == json!({"polite": {"strict": true}}) + && e["agent"] == "chat_agent")); let results = p.json(&p.latest().join("results/chat.json")); - assert_eq!(scenarios(&results), ["trace_0", "trace_1"]); + assert_eq!(case_names(&results), ["trace_0", "trace_1"]); assert_eq!(results["metadata"]["online"], true); // Only conv-0 has a trace. - assert_eq!( - results["scenarios"][0]["otel_metrics"]["total_tokens"], - 99.0 - ); - assert_eq!(results["scenarios"][1]["otel_metrics"]["total_tokens"], 0.0); + assert_eq!(results["cases"][0]["otel_metrics"]["total_tokens"], 99.0); + assert_eq!(results["cases"][1]["otel_metrics"]["total_tokens"], 0.0); - p.eac(&["online", "run", "--judge", "rude"]) - .code(2) - .says("has no online judge rude"); + p.eac(&["online", "run", "--judge", "rude"]).code(2).says("has no online judge rude"); } #[test] @@ -570,12 +538,10 @@ fn online_runs_can_collect_then_judge() { let collected = p.eac(&["online", "collect", "--limit", "5"]); collected.code(0); let id = collected.stdout.trim().to_string(); - assert_eq!(p.events("fetch").len(), 1); + assert_eq!(p.events("collect").len(), 1); assert!(p.events("online_judge").is_empty()); - p.eac(&["online", "judge", "--run", &id]) - .code(2) - .says("--judge is required, since run"); + p.eac(&["online", "judge", "--run", &id]).code(2).says("--judge is required, since run"); let judged = p.eac(&["online", "judge", "--run", &id, "--judge", "nonempty"]); judged.code(0).says("nonempty"); assert_eq!(judged.stdout.trim(), id); @@ -587,7 +553,7 @@ fn online_runs_can_collect_then_judge() { let calls = p.events("online_judge"); assert_eq!(calls.len(), 4); assert!(calls.iter().all(|c| c["judges"] == json!(["nonempty"]))); - assert_eq!(p.events("fetch").len(), 1); + assert_eq!(p.events("collect").len(), 1); // Each mode's commands only work on its runs. p.eac(&["offline", "judge", "--run", &id]) @@ -604,11 +570,7 @@ fn datasets_are_picked_by_name_or_the_directory_eac_runs_in() { p.write("more/more_eval.py", MORE); p.write("more/dataset.yml", MORE_DATASET); - p.eac(&["list"]) - .code(0) - .says("chat/greets") - .says("more/greets") - .says("evals/dataset.yml"); + p.eac(&["list"]).code(0).says("chat/greets").says("more/greets").says("evals/dataset.yml"); let scoped = p.eac_in("more", &["list"]); scoped.code(0).says("more/greets"); assert!(!scoped.stderr.contains("chat/")); @@ -662,10 +624,8 @@ fn credentials_are_checked_before_the_phases_that_need_them() { let seeded = p.eac(&["offline", "seed", "--split", "smoke"]); seeded.code(0).says("✓ token_a"); let id = seeded.stdout.trim().to_string(); - p.eac(&["offline", "collect", "--run", &id]) - .code(2) - .says("token_b: missing or invalid"); - assert!(p.events("execute").is_empty()); + p.eac(&["offline", "collect", "--run", &id]).code(2).says("token_b: missing or invalid"); + assert!(p.events("run").is_empty()); p.write(".env", "TOKEN_A=good\nTOKEN_B=good\n"); p.eac(&["offline", "collect", "--run", &id]).code(0); } @@ -674,9 +634,11 @@ fn credentials_are_checked_before_the_phases_that_need_them() { fn credentials_arent_checked_in_ci() { let p = Project::new(&base()); p.write("needs.json", r#"{"seed": ["TOKEN_A"]}"#); - p.eac_with(".", &[("CI", "true")], &["offline", "run", "--split", "smoke"]) - .code(0); + p.eac_with(".", &[("CI", "true")], &["offline", "run", "--split", "smoke"]).code(0); assert!(p.events("credentials_check").is_empty()); + // CI other than GitHub Actions is still recorded as CI. + let results = p.json(&p.latest().join("results/chat.json")); + assert_eq!(results["source"]["trigger"], "ci"); } #[test] @@ -690,18 +652,11 @@ fn auth_saves_logins_for_later_commands() { .says("✓ token_c") .says("saved TOKEN_A, TOKEN_B, TOKEN_C to .eac/credentials/saved.json"); // Login runs on the terminal, so its output isn't indented like a log. - assert!( - ran.stderr.lines().any(|l| l == "logging in to TOKEN_A"), - "{}", - ran.stderr - ); + assert!(ran.stderr.lines().any(|l| l == "logging in to TOKEN_A"), "{}", ran.stderr); let logins = p.events("credentials_login"); assert_eq!(names(&logins, "name"), ["token_a", "token_c", "token_b"]); // They're saved where they can't be committed, and .env is left alone. - assert_eq!( - fs::read_to_string(p.path(".env")).unwrap(), - "# kept\nTOKEN_B=stale\n" - ); + assert_eq!(fs::read_to_string(p.path(".env")).unwrap(), "# kept\nTOKEN_B=stale\n"); let saved = fs::metadata(p.path(".eac/credentials/saved.json")).unwrap(); assert_eq!(saved.permissions().mode() & 0o777, 0o600); let ignore = fs::read_to_string(p.path(".eac/credentials/.gitignore")).unwrap(); @@ -738,13 +693,9 @@ fn prune_checks_the_seeds_credentials_before_tearing_down() { p.eac(&["offline", "run", "--split", "smoke"]).code(0); p.write(".env", ""); - p.eac(&["offline", "prune", "--all"]) - .code(2) - .says("token_a: missing or invalid"); + p.eac(&["offline", "prune", "--all"]).code(2).says("token_a: missing or invalid"); assert!(p.events("seed_teardown").is_empty()); p.write(".env", "TOKEN_A=good\n"); - p.eac(&["offline", "prune", "--all"]) - .code(0) - .says("tore down 1 cached seed"); + p.eac(&["offline", "prune", "--all"]).code(0).says("tore down 1 cached seed"); } diff --git a/core/tests/fixtures/project/eac/worker.py b/core/tests/fixtures/project/eac/worker.py index e7f63e4..285832e 100644 --- a/core/tests/fixtures/project/eac/worker.py +++ b/core/tests/fixtures/project/eac/worker.py @@ -51,22 +51,25 @@ def handle(method, p): if method == "discover": return ds.discover(p["dataset"]) if method == "args.validate": - args = ds.validate_args(p["mode"], p.get("args", {}), p.get("judges", []), p.get("judge_args", {})) - return {"args": args, **ds.credentials(p["mode"], p.get("judges", []))} + ds.validate_args(p["mode"], p.get("args", {}), p.get("judges", []), p.get("judge_args", {})) + return ds.credentials(p["mode"], p.get("judges", [])) if method == "seed.setup": return ds.seed_setup(p["seed"]) if method == "seed.teardown": ds.seed_teardown(p["seed"], p.get("handle", {})) return {} - if method == "case.execute": - return ds.execute(p["case"], p.get("seeds", {}), p.get("args", {}), p["conversation_id"]) + if method == "case.run": + return ds.run_case(p["case"], p.get("seeds", {}), p.get("args", {}), p["conversation_id"]) if method == "case.judge": - run = {k: p[k] for k in ("conversation_id", "agent", "started_at", "ended_at") if k in p} - return ds.judge(p["case"], p.get("output"), p.get("judges", []), p.get("seeds", {}), p.get("trace"), run) - if method == "online.fetch": - return {"records": ds.fetch(p["since"], p["until"], p["limit"], p.get("args", {}))} + case = p["case"] + run = {k: p[k] for k in ("agent", "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) + if method == "online.collect": + return {"cases": ds.collect(p["since"], p["until"], p["limit"], p.get("args", {}))} if method == "online.judge": - return ds.online_judge(p["record"], p["judges"], p.get("judge_args", {}), p.get("trace"), p.get("agent")) + return ds.online_judge(p["case"], p["judges"], p.get("judge_args", {}), p.get("trace"), p.get("agent")) raise ValueError(f"unknown method {method!r}") diff --git a/core/tests/fixtures/project/evals/chat_eval.py b/core/tests/fixtures/project/evals/chat_eval.py index 819264a..6464fd8 100644 --- a/core/tests/fixtures/project/evals/chat_eval.py +++ b/core/tests/fixtures/project/evals/chat_eval.py @@ -56,8 +56,8 @@ def discover(dataset): for seed in (seed for case in cases for seed in case.get("seeds", [])): if credentials := needs("seed"): seed["credentials"] = credentials - return {"cases": cases, "args_schema": {"type": "object", "properties": {"model": {"type": "string"}}}} - return {"args_schema": {"type": "object"}} + return {"cases": cases} + return {} def needs(part): @@ -121,9 +121,6 @@ def validate_args(mode, args, judges, judge_args): if any(set(values) - {"strict"} for values in judge_args.values()): raise ValueError("unknown judge args") log("validate", mode=mode, args=args, judges=judges, judge_args=judge_args) - if mode == "offline": - return {"model": "small", **args} - return {"region": "us", **args} def seed_setup(seed): @@ -154,14 +151,14 @@ def fetch_trace(conversation_id): } -def execute(case, seeds, args, conversation_id): +def run_case(case, seeds, args, conversation_id): log( - "execute", + "run", case=case["name"], seeds=sorted(seeds), args=args, conversation_id=conversation_id, - together=together("execute", case["name"]), + 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}} @@ -195,25 +192,25 @@ def judge(case, output, judges, seeds, trace, run): return {"scores": scores, **(fetched or {})} -def fetch(since, until, limit, args): - log("fetch", since=since, until=until, limit=limit, args=args) - records = [ - {"id": "trace_0", "conversation_id": "conv-0", "input": {"q": "hi"}, "output": {"reply": "thanks!"}}, - {"id": "trace_1", "conversation_id": "conv-1", "input": {"q": "hey"}, "output": {"reply": ""}}, +def collect(since, until, limit, args): + log("collect", since=since, until=until, limit=limit, 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": ""}}, ] - return records[:limit] + return cases[:limit] -def online_judge(record, judges, judge_args, trace, agent): - fetched = fetch_trace(record.get("conversation_id")) if trace is None else None +def online_judge(case, judges, judge_args, trace, agent): + fetched = fetch_trace(case.get("conversation_id")) if trace is None else None log( "online_judge", - record=record["id"], + case=case["name"], judges=judges, judge_args=judge_args, agent=agent, - together=together("online_judge", record["id"]), + together=together("online_judge", case["name"]), ) - reply = (record.get("output") or {}).get("reply", "") + reply = (case.get("output") 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 {})} diff --git a/docs/app/cases-and-runners/page.mdx b/docs/app/cases-and-runners/page.mdx index f5fc2ba..b8d28cc 100644 --- a/docs/app/cases-and-runners/page.mdx +++ b/docs/app/cases-and-runners/page.mdx @@ -10,14 +10,13 @@ A **case** is one input to test. A **runner** takes a case, calls your system, a ```python from eac import Case -from eac.judges import Contains, Equals CASES = [ Case( name="greets", input={"query": "hi"}, expected_output={"response": "hello"}, - judges=[Contains(["hello"]), Equals()], + judges=[Matches()], # your own judges, see Judges splits=["smoke"], ), ] @@ -25,6 +24,8 @@ 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 few other options you might want: - `seeds=[...]` for fixtures the case needs. See [Seeds](/seeds). @@ -45,18 +46,19 @@ Prefer keeping cases in data files? `from_jsonl("cases/*.jsonl", judges=[...])` from eac import OfflineRunner class ChatRunner(OfflineRunner): - def execute(self, case, ctx): - reply = my_chatbot(case.input["query"], tag=ctx.conversation_id) + def run_case(self, case, *, seeds, conversation_id): + model = self.args.get("model", "small") + reply = my_chatbot(case.input["query"], model=model, tag=conversation_id) return {"response": reply} ``` -Return plain JSON and leave the scoring to your judges. The `ctx` gives you: +Return plain JSON and leave the scoring to your judges. Along with the case, you get: -- `ctx.seed("name")` to get a fixture. -- `ctx.args` for anything passed with `--args`. -- `ctx.conversation_id` to tag your agent's run, so judges can find its trace later. +- `seeds`, each fixture's handle by name, like `seeds["project"]`. +- `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. Runners, judges and seeds can be sync or async. Use whichever fits your code. @@ -76,4 +78,4 @@ offline: args: {model: big} ``` -Then run `eac offline compare models`. Each arm gets its own run, and they share fixtures. +Then run `eac offline compare models`. Each arm gets its own run, and they share fixtures. Each arm's `args` reach the runner as `self.args`. diff --git a/docs/app/cli/page.mdx b/docs/app/cli/page.mdx index 74f833d..295b0ad 100644 --- a/docs/app/cli/page.mdx +++ b/docs/app/cli/page.mdx @@ -17,8 +17,8 @@ Run `eac --help` any time for the full list. ['`eac offline judge`', 'Score the outputs.'], ['`eac offline compare NAME`', 'Run a comparison, one run per arm.'], ['`eac offline prune`', "Clean up cached fixtures nothing uses."], - ['`eac online run`', 'Fetch production records and judge them.'], - ['`eac online collect`', 'Fetch production records into a new run.'], + ['`eac online run`', 'Collect production runs and judge them.'], + ['`eac online collect`', 'Collect production runs into a new run.'], ['`eac online judge`', 'Judge a collected run.'], ['`eac auth`', 'Log in to every credential your datasets need.'], ['`eac catalog`', 'Print every dataset, case and split as JSON.'], @@ -34,12 +34,12 @@ Run `eac --help` any time for the full list. ['`--dataset NAME`', 'Only run this dataset.'], ['`--case NAME`', 'Only run this case.'], ['`--split NAME`', 'Only run cases in this split.'], - ['`--args JSON`', 'Pass args to your runner.'], - ['`--judge-args JSON`', 'Pass args to your judges, keyed by judge name.'], + ['`--args JSON`', 'Pass args to your runner, as `self.args`.'], + ['`--judge-args JSON`', "Pass args to your judges, keyed by judge name. Each gets its entry as `self.args`."], ['`--run ID`', 'Which run to use. Defaults to `latest`.'], ['`--concurrency N`', 'How many cases to run at once.'], ['`--judge NAME`', 'Online: which judge to score with.'], - ['`--since 24h`', 'Online: how far back to fetch. Defaults to 1h.'], + ['`--since 24h`', 'Online: how far back to collect. Defaults to 1h.'], ['`-C DIR`', 'Run as if from another directory.'], ]} /> @@ -48,4 +48,4 @@ Run `eac --help` any time for the full list. ## Exit codes -`0` means everything passed, `1` means a case failed, and `2` means eac itself hit a problem. +`0` means no case failed or errored, `1` means one did, and `2` means eac itself hit a problem. `eac --version` prints the version. diff --git a/docs/app/concepts/page.mdx b/docs/app/concepts/page.mdx index f128c82..6ef6f85 100644 --- a/docs/app/concepts/page.mdx +++ b/docs/app/concepts/page.mdx @@ -4,7 +4,7 @@ export const metadata = {title: 'How eac works'}; ## Projects and datasets -A **project** is any folder with an `eac.yml` in it. A **dataset** is a `dataset.yml` and the code next to it. eac finds every dataset under the project root on its own, so adding one never means editing shared config. +A **project** is your repo, or the folder with an `eac.yml` in it if you need shared settings. A **dataset** is a `dataset.yml` and the code next to it. eac finds every dataset under the project root on its own, so adding one never means editing shared config. ## Workers @@ -30,8 +30,8 @@ An offline run has three phases: ]} /> -`eac offline run` does all three in one go. Online runs skip seeding: they **collect** records from production and **judge** them. +`eac offline run` does all three in one go. Online runs skip seeding: they **collect** production runs as cases and **judge** them. ## 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. 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 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/configuration/page.mdx b/docs/app/configuration/page.mdx index d267c60..e0b3151 100644 --- a/docs/app/configuration/page.mdx +++ b/docs/app/configuration/page.mdx @@ -4,7 +4,7 @@ export const metadata = {title: 'Configuration'}; ## eac.yml -This file marks your project's root. Every key is optional, so an empty file works fine. +You probably don't need one. Without it, your project's root is the root of your git repo (or the current folder, outside one). Add an `eac.yml` to make its folder the root instead, or to change any of these settings. Every key is optional. ```yaml artifacts: .eac # where runs are saved @@ -14,13 +14,9 @@ runtimes: python: command: [uv, run, python] env: {PYTHONPATH: src} - -online: - judges: # judges every online dataset can use - - {name: polite, path: "evals.judges:Polite"} ``` -If you don't set a Python command, eac uses your active virtualenv, then the nearest `.venv`, then `uv run python` if there's a `uv.lock`, then `python3`. It also loads a `.env` file next to `eac.yml`. +If you don't set a Python command, eac uses `$EAC_PYTHON`, then your active virtualenv, then the nearest `.venv`, then `uv run python` if there's a `uv.lock`, then `python3`. It also loads a `.env` file from the project root. ## dataset.yml @@ -40,4 +36,4 @@ online: - {name: polite, path: ./judges.py:Polite} ``` -A dataset needs `offline`, `online`, or both. Code can be referenced as `./file.py:name` (relative to the YAML file) or `module.path:name`. +A dataset needs `offline`, `online`, or both. Code can be referenced as `./file.py:name` (relative to the YAML file) or `module.path:name`. A runner or judge reference can be a class, which eac builds with no arguments, or an instance you've configured. diff --git a/docs/app/credentials/page.mdx b/docs/app/credentials/page.mdx index 8bb023c..c86aa5d 100644 --- a/docs/app/credentials/page.mdx +++ b/docs/app/credentials/page.mdx @@ -29,7 +29,7 @@ class GitHub(Credential): -Then add it to whatever needs it: a seed's or judge's `credentials`, or a runner's `credentials(args)` method. +Then add it to the `credentials` of whatever needs it: a seed, a runner or a judge. ## Logging in diff --git a/docs/app/judges/page.mdx b/docs/app/judges/page.mdx index c7933a6..e136f76 100644 --- a/docs/app/judges/page.mdx +++ b/docs/app/judges/page.mdx @@ -2,31 +2,22 @@ export const metadata = {title: 'Judges'}; # Judges -A judge looks at one output and gives it a score between 0 and 1. - -## Built-in 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`. ```python -from eac.judges import Contains, Equals -from eac.common.judges.regex_judge import Regex - -Contains(["hello", "world"]) # how many of these appear in the response -Equals() # response matches expected_output exactly -Regex([r"https://\S+"], output_lambda=lambda out: out.get("response", "")) -``` - - - -## Writing your own - -Subclass `Judge` and return a `Score`: +from eac import Judge, Score - +class Matches(Judge): + name = "matches" -```python -from eac import Judge, Score + def judge(self, case, *, seeds, agent_trace=None): + expected = case.expected_output.get("response") + if expected is None: + return None # doesn't apply to this case + ok = case.output.get("response") == expected + return Score(name=self.name, score=1.0 if ok else 0.0) class CalledTool(Judge): name = "called_tool" @@ -34,8 +25,8 @@ class CalledTool(Judge): def __init__(self, tool: str): self.tool = tool - def judge(self, *, case_output, case, seed_results, agent_trace=None): - ok = self.tool in case_output.get("tool_calls", []) + def judge(self, case, *, seeds, agent_trace=None): + ok = self.tool in case.output.get("tool_calls", []) return Score( name=self.name, score=1.0 if ok else 0.0, @@ -45,9 +36,19 @@ class CalledTool(Judge): -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 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". + +`seeds` holds the case's fixtures by name, the same ones the runner got. + +## Settings per run + +Need settings that change per run, like a rubric? Pass them with `--judge-args`, keyed by the judge's name: + +```sh +eac offline run --judge-args '{"called_tool": {"strict": true}}' +``` -Need settings that change per run, like a rubric? Give the judge an `args_model` (a pydantic model) and pass values with `--judge-args`. +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. ## Reading agent traces diff --git a/docs/app/online-evals/page.mdx b/docs/app/online-evals/page.mdx index 49dde7b..96e588b 100644 --- a/docs/app/online-evals/page.mdx +++ b/docs/app/online-evals/page.mdx @@ -2,7 +2,7 @@ export const metadata = {title: 'Online evals'}; # Online evals -Online evals score what your system already did in production. There are no cases or fixtures. You fetch recent records and judge them. +Online evals score what your system already did in production. Nothing is re-run and there are no fixtures. You collect recent production runs as cases and judge them. ## Set it up @@ -18,33 +18,43 @@ runtime: python online: runner: ./dataset.py:ProdChats judges: - - {name: greets, path: ./dataset.py:GREETS} + - {name: greets, path: ./dataset.py:Greets} ``` -The runner's `fetch` returns records from a time window: +The runner's `collect_cases` returns what happened in a time window, as cases with their `output` already filled in: ```python -from eac import OnlineRunner, Record -from eac.judges import Contains +from eac import Case, Judge, OnlineRunner, Score class ProdChats(OnlineRunner): - def fetch(self, since, until, limit): + def collect_cases(self, window): + rows = query_production(window.since, window.until, window.limit) return [ - Record(id=row.id, input={"query": row.query}, output={"response": row.reply}) - for row in query_production(since, until, limit) + Case( + name=row.id, + input={"query": row.query}, + output={"response": row.reply}, + conversation_id=row.trace_id, # lets judges fetch the agent trace + ) + for row in rows ] -GREETS = Contains(["hello"]) +class Greets(Judge): + name = "greets" + + def judge(self, case, *, seeds, agent_trace=None): + ok = "hello" in case.output.get("response", "") + return Score(name=self.name, score=1.0 if ok else 0.0) ``` @@ -58,7 +68,7 @@ eac online run --judge greets --since 24h ``` - Production records don't have an expected output, so judges like `Equals` won't work here. Online runs report average scores and never fail. + Production runs don't have an expected output, so judges that compare against one should return `None`. Online runs report average scores and never fail. -Judges you want in every dataset can go under `online.judges` in `eac.yml`. +`--args` reach the runner as `self.args`, like offline. To use a judge in several datasets, point each `dataset.yml` at the same code. diff --git a/docs/app/page.mdx b/docs/app/page.mdx index ab9fc9d..f3e7309 100644 --- a/docs/app/page.mdx +++ b/docs/app/page.mdx @@ -24,7 +24,7 @@ eac handles everything else: setting up fixtures, running each case, scoring the **Offline evals** run your system on cases you wrote. Use them in development and CI to catch regressions. -**Online evals** score what your system already did in production. Nothing gets re-run. eac just pulls recent records and judges them. +**Online evals** score what your system already did in production. Nothing gets re-run. eac just collects recent production runs as cases and judges them. ## Why eac? diff --git a/docs/app/protocol/page.mdx b/docs/app/protocol/page.mdx index c97252e..b0d7a14 100644 --- a/docs/app/protocol/page.mdx +++ b/docs/app/protocol/page.mdx @@ -14,7 +14,7 @@ eac starts a worker process for your language and talks to it with JSON, one mes - When eac closes fd 3, the worker should exit. ```json -{"id": 1, "method": "case.execute", "params": {}} +{"id": 1, "method": "case.run", "params": {}} {"id": 1, "result": {"output": {}}} ``` @@ -25,13 +25,13 @@ eac starts a worker process for your language and talks to it with JSON, one mes widths={[200, 'auto']} rows={[ ['`discover`', "Load a dataset and list its cases."], - ['`args.validate`', 'Check args before anything runs.'], + ['`args.validate`', 'Report the credentials a run needs, before anything runs.'], ['`seed.setup`', 'Set up a fixture.'], ['`seed.teardown`', 'Clean up a fixture.'], - ['`case.execute`', 'Run one case.'], + ['`case.run`', 'Run one case.'], ['`case.judge`', "Score one case's output."], - ['`online.fetch`', 'Fetch production records.'], - ['`online.judge`', 'Score one production record.'], + ['`online.collect`', 'Collect production runs as cases.'], + ['`online.judge`', 'Score one collected case.'], ['`credentials.check`', 'Report which credentials are ready.'], ['`credentials.login`', 'Log in to a credential.'], ]} diff --git a/docs/app/quick-start/page.mdx b/docs/app/quick-start/page.mdx index 2161223..57df6a1 100644 --- a/docs/app/quick-start/page.mdx +++ b/docs/app/quick-start/page.mdx @@ -26,16 +26,15 @@ pip install -e sdks/python # needs Python 3.11+ -## Create a project +## Add a dataset -An `eac.yml` marks the root of your project. It can be empty. Each dataset gets its own folder: +Each dataset gets its own folder, anywhere in your repo. eac finds it on its own, so there's no project config to write: ```text -eac.yml evals/chat/ dataset.yml dataset.py @@ -63,15 +62,14 @@ offline: -Then write the runner and cases: +Then write the runner, a judge and the cases: ```python -from eac import Case, OfflineRunner -from eac.judges import Contains +from eac import Case, Judge, OfflineRunner, Score def reply(query: str) -> str: @@ -79,13 +77,19 @@ def reply(query: str) -> str: class ChatRunner(OfflineRunner): - def execute(self, case, ctx): + def run_case(self, case, *, seeds, conversation_id): return {"response": reply(case.input["query"])} -CASES = [ - Case(name="greets", input={"query": "hi"}, judges=[Contains(["hello"])]), -] +class Greets(Judge): + name = "greets" + + def judge(self, case, *, seeds, agent_trace=None): + ok = "hello" in case.output.get("response", "") + return Score(name=self.name, score=1.0 if ok else 0.0) + + +CASES = [Case(name="greets", input={"query": "hi"}, judges=[Greets()])] ``` @@ -94,6 +98,8 @@ CASES = [ ## Run it +From the root of your repo: + ```sh eac list # see what eac found eac offline run # seed, collect and judge diff --git a/docs/app/run-directory/page.mdx b/docs/app/run-directory/page.mdx index 3ed8461..37d09e7 100644 --- a/docs/app/run-directory/page.mdx +++ b/docs/app/run-directory/page.mdx @@ -11,12 +11,13 @@ Every run is saved to its own folder: 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 -eac never sends results anywhere. If you want them in a dashboard, point a script at the run folder. Commands that judge print the run id, so you can chain them: +eac never sends results anywhere. If you want them in a dashboard, point a script at the run's `results/` folder. It's the one format meant for other tools: [`schemas/results.schema.json`](https://github.com/getsentry/eve/blob/main/schemas/results.schema.json) describes it, and its `schema_version` goes up whenever a change could break a reader. Commands that judge print the run id, so you can chain them: ```sh id=$(eac offline run); ./upload.py ".eac/runs/$id" diff --git a/docs/app/seeds/page.mdx b/docs/app/seeds/page.mdx index 2ca836d..a310b1e 100644 --- a/docs/app/seeds/page.mdx +++ b/docs/app/seeds/page.mdx @@ -29,7 +29,7 @@ class Project(Seed): -Attach it with `Case(seeds=[Project()])`, then read it in your runner with `ctx.seed("project")`. +Attach it with `Case(seeds=[Project()])`, then read its handle in your runner and judges as `seeds["project"]`. ## Caching diff --git a/examples/basic-example-python/README.md b/examples/basic-example-python/README.md index 9e0f03d..3cbfa62 100644 --- a/examples/basic-example-python/README.md +++ b/examples/basic-example-python/README.md @@ -4,7 +4,7 @@ A complete eval with no network calls and no API keys, laid out as an eac project: one dataset, in its own folder. ``` -eac.yml the project: settings every dataset shares +eac.yml the project root, and settings every dataset shares evals/assistant/ dataset.yml the dataset: its name, and the code it runs offline and online dataset.py that code: runners, cases, a seed and judges @@ -22,35 +22,35 @@ eac offline run # seed, collect, judge eac offline run --dataset assistant # only this dataset, once there are more eac offline run --case get_dsn eac offline run --split smoke -eac online run --judge contains # collect and score "production" records +eac online run --judge replied # collect and score "production" runs eac offline prune # tear down the cached seed ``` Its `eac.yml` points `PYTHONPATH` at `sdks/python` because the SDK isn't -installed inside this repo. In your own project, `pip install` the SDK and drop -that `runtimes` block. +installed inside this repo. In your own project, `pip install` the SDK and you +won't need an `eac.yml` at all. It shows: - A `dataset.yml` that points at its code in `dataset.py`. Offline, that's the runner and `CASES`. Online, it's the runner and the judge it names - `contains`. + `replied`. - An offline runner that calls the system under test and returns raw output. It doesn't score or decide pass/fail. -- An online runner, `ProdChats`, and the online judge that - `eac online run --judge contains` picks. +- An online runner, `ProdChats`, that collects production runs as cases, and + the online judge that `eac online run --judge replied` picks. - A seed, `FakeProject`, with a `key()`. All three cases ask for the same fixture, so setup runs once and is shared. The seed phase prints "creating project demo" only once. The seed is cached, so later runs reuse it until `eac offline prune`. -- The built-in `Regex` and `Contains` judges, and a custom one, `CalledTool`, - for anything product-specific. +- Judges, which are your own code: `Mentions` checks the reply's words and + `CalledTool` checks which tools ran. ## Add a dataset of your own Make a folder next to `evals/assistant/` with a runner, its cases, and a `dataset.yml` that points at them with paths relative to itself. eac finds it -without any change to `eac.yml`. +on its own. ```yaml # evals/my_feature/dataset.yml diff --git a/examples/basic-example-python/evals/assistant/dataset.py b/examples/basic-example-python/evals/assistant/dataset.py index 9dffefc..7f21e97 100644 --- a/examples/basic-example-python/evals/assistant/dataset.py +++ b/examples/basic-example-python/evals/assistant/dataset.py @@ -7,11 +7,9 @@ from __future__ import annotations -from datetime import datetime from typing import Any -from eac import Case, Context, OfflineRunner, OnlineRunner, Record, Seed, judges, stable_hash -from eac.common.judges.regex_judge import Regex +from eac import Case, Handle, Judge, OfflineRunner, OnlineRunner, Score, Seed, Window, stable_hash class FakeProject(Seed): @@ -20,6 +18,7 @@ class FakeProject(Seed): name = "fake_project" def __init__(self, slug: str = "demo"): + super().__init__() self.slug = slug def key(self) -> str: @@ -39,31 +38,41 @@ def cleanup(self, handle: dict[str, Any]) -> None: class AssistantRunner(OfflineRunner): - async def execute(self, case: Case, ctx: Context) -> dict[str, Any]: - project = ctx.seed("fake_project") - reply, tools = assistant(case.input["query"], project) + async def run_case(self, case: Case, *, seeds: dict[str, Handle], conversation_id: str) -> dict[str, Any]: + reply, tools = assistant(case.input["query"], seeds["fake_project"]) return {"response": reply, "tool_calls": tools} -class CalledTool(judges.Judge): - """A custom judge. Passes if the assistant called the given tool.""" +class Mentions(Judge): + """The fraction of the given words the reply mentions.""" + + name = "mentions" + + def __init__(self, *words: str): + self.words = words + + def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None) -> Score: + reply = (case.output.get("response") or "").lower() + missing = [word for word in self.words if word.lower() not in reply] + return Score( + name=self.name, + score=1 - len(missing) / len(self.words), + explanation=f"missing: {', '.join(missing)}" if missing else None, + ) + + +class CalledTool(Judge): + """Passes if the assistant called the given tool.""" name = "called_tool" def __init__(self, tool: str): self.tool = tool - def judge( - self, - *, - case_output: dict[str, Any], - case: Case, - seed_results: dict[str, dict[str, Any]], - agent_trace: Any = None, - ) -> judges.Score: - called = case_output.get("tool_calls") or [] + def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None) -> Score: + called = case.output.get("tool_calls") or [] ok = self.tool in called - return judges.Score( + return Score( name=self.name, score=1.0 if ok else 0.0, explanation=None if ok else f"{self.tool} was not called; called {called}", @@ -71,57 +80,57 @@ def judge( ) +class Replied(Judge): + """The online judge. Production runs have no expected output, so it checks + the reply alone.""" + + name = "replied" + + def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None) -> Score: + ok = bool(case.output.get("response")) + return Score(name=self.name, score=1.0 if ok else 0.0, explanation=None if ok else "empty reply") + + class ProdChats(OnlineRunner): """A real online runner would query your production traces. This one - returns fixed records so the example runs offline.""" + returns fixed runs so the example works offline.""" - def fetch(self, since: datetime, until: datetime, limit: int) -> list[Record]: - print(f"fetching chats from {since:%Y-%m-%d %H:%M} to {until:%H:%M}") + def collect_cases(self, window: Window) -> list[Case]: + print(f"collecting chats from {window.since:%Y-%m-%d %H:%M} to {window.until:%H:%M}") replies = [ "Your DSN is https://abc123@o0.ingest.sentry.io/demo", "You're in the demo project.", "", # a bad one, to show up in the aggregate ] return [ - Record(id=f"trace-{i}", input={"query": "..."}, output={"response": reply}) - for i, reply in enumerate(replies[:limit]) + Case(name=f"trace-{i}", input={"query": "..."}, output={"response": reply}) + for i, reply in enumerate(replies[: window.limit]) ] -def response(output: dict[str, Any] | None) -> str: - return (output or {}).get("response") or "" - - CASES = [ Case( name="get_dsn", input={"query": "What's my DSN?"}, seeds=[FakeProject()], - judges=[ - CalledTool("get_dsn"), - Regex([r"(?i)dsn", r"https://[^\s]+@[^\s]+/[^\s]+"], output_lambda=response), - ], + judges=[CalledTool("get_dsn"), Mentions("DSN", "ingest.sentry.io")], splits=["smoke"], ), Case( name="project_slug", input={"query": "Which project am I in?"}, seeds=[FakeProject()], - judges=[judges.Contains(["demo"])], + judges=[Mentions("demo")], splits=["smoke"], ), Case( name="refuses_unknown", input={"query": "What is the airspeed velocity of an unladen swallow?"}, seeds=[FakeProject()], - judges=[judges.Contains(["don't know"])], + judges=[Mentions("don't know")], ), ] -# The online judge. Production records have no expected output, so it checks -# the reply alone. -ENDS_A_SENTENCE = judges.Contains(["."]) - def assistant(query: str, project: dict[str, Any]) -> tuple[str, list[str]]: """Pretend LLM. Replace with a real call to your product.""" diff --git a/examples/basic-example-python/evals/assistant/dataset.yml b/examples/basic-example-python/evals/assistant/dataset.yml index 2887c6b..cb0a20f 100644 --- a/examples/basic-example-python/evals/assistant/dataset.yml +++ b/examples/basic-example-python/evals/assistant/dataset.yml @@ -8,5 +8,5 @@ offline: online: runner: ./dataset.py:ProdChats judges: - - name: contains - path: ./dataset.py:ENDS_A_SENTENCE + - name: replied + path: ./dataset.py:Replied diff --git a/schemas/README.md b/schemas/README.md new file mode 100644 index 0000000..81ce9ef --- /dev/null +++ b/schemas/README.md @@ -0,0 +1,12 @@ +# Schemas + +JSON Schemas for data that third-party tools can consume. + +`make generate` generates Rust and other SDK language-specific models from them. `make generate-check` fails if one is out of date, so don't edit them by hand. + +| File | Describes | Defined in | +|---|---|---| +| [`results.schema.json`](results.schema.json) | `results/.json` in a run's directory: one dataset's results from one run | [`core/src/eac/run/results.rs`](../core/src/eac/run/results.rs) | + +External tools that use eval results should read only the `results.schema.json` file. Any nested schemas within [/core](/core) belong to eac and changes freely. + diff --git a/schemas/results.schema.json b/schemas/results.schema.json new file mode 100644 index 0000000..0fa4a77 --- /dev/null +++ b/schemas/results.schema.json @@ -0,0 +1,326 @@ +{ + "$defs": { + "CaseResult": { + "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`.", + "type": "object" + }, + "conversation_id": { + "description": "The agent conversation, for looking up its trace.", + "type": [ + "string", + "null" + ] + }, + "duration_seconds": { + "description": "How long the runner took. 0 for online runs.", + "type": "number" + }, + "end_time": { + "description": "When the runner finished. Null for online runs.", + "format": "date-time", + "type": [ + "string", + "null" + ] + }, + "error": { + "description": "Why the case errored.", + "type": [ + "string", + "null" + ] + }, + "expected_output": { + "type": [ + "object", + "null" + ] + }, + "input": { + "type": "object" + }, + "name": { + "type": "string" + }, + "otel_metrics": { + "$ref": "#/$defs/Metrics", + "description": "The case's LLM usage, taken from its agent trace when a judge fetched one." + }, + "output": { + "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", + "type": [ + "string", + "null" + ] + }, + "status": { + "$ref": "#/$defs/Status" + } + }, + "required": [ + "name", + "status", + "input", + "output", + "expected_output", + "error", + "scores", + "otel_metrics", + "conversation_id", + "attributes", + "start_time", + "end_time", + "duration_seconds" + ], + "type": "object" + }, + "Metrics": { + "description": "LLM usage: tokens, calls, time and cost.", + "properties": { + "cache_read_tokens": { + "type": "number" + }, + "cache_write_tokens": { + "type": "number" + }, + "cost_usd": { + "type": "number" + }, + "input_tokens": { + "type": "number" + }, + "llm_calls": { + "type": "integer" + }, + "llm_duration_seconds": { + "type": "number" + }, + "output_tokens": { + "type": "number" + }, + "reasoning_tokens": { + "type": "number" + }, + "tool_calls": { + "type": "integer" + }, + "total_tokens": { + "type": "number" + } + }, + "required": [ + "input_tokens", + "output_tokens", + "total_tokens", + "cache_read_tokens", + "cache_write_tokens", + "reasoning_tokens", + "llm_duration_seconds", + "llm_calls", + "tool_calls", + "cost_usd" + ], + "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.", + "properties": { + "explanation": { + "description": "Why the judge gave this score.", + "type": [ + "string", + "null" + ] + }, + "llm_judge_metrics": { + "anyOf": [ + { + "$ref": "#/$defs/Metrics" + }, + { + "type": "null" + } + ], + "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": { + "type": [ + "number", + "null" + ] + } + }, + "required": [ + "name", + "score" + ], + "type": "object" + }, + "Source": { + "description": "The commit, pull request and CI job a run came from.", + "properties": { + "actor": { + "description": "Who started the run.", + "type": [ + "string", + "null" + ] + }, + "base_sha": { + "description": "The pull request's base commit.", + "type": [ + "string", + "null" + ] + }, + "branch": { + "type": [ + "string", + "null" + ] + }, + "commit_url": { + "type": [ + "string", + "null" + ] + }, + "pr_author": { + "description": "The pull request author's GitHub login.", + "type": [ + "string", + "null" + ] + }, + "pr_number": { + "type": [ + "integer", + "null" + ] + }, + "pr_url": { + "type": [ + "string", + "null" + ] + }, + "run_url": { + "description": "The GitHub Actions run.", + "type": [ + "string", + "null" + ] + }, + "sha": { + "description": "The commit tested. For a pull request, its head commit.", + "type": [ + "string", + "null" + ] + }, + "trigger": { + "$ref": "#/$defs/Trigger" + } + }, + "required": [ + "trigger" + ], + "type": "object" + }, + "Status": { + "description": "`passed` when every score is 1, `failed` when any is lower, `error` when the runner or a judge failed, and `skipped` when there are no scores. Null scores don't count.", + "enum": [ + "passed", + "failed", + "error", + "skipped" + ], + "type": "string" + }, + "Trigger": { + "description": "What started the run: the workflow's event on GitHub Actions, `ci` on other CI services, and `local` outside CI.", + "enum": [ + "local", + "ci", + "pull_request", + "push", + "workflow_dispatch", + "schedule" + ], + "type": "string" + } + }, + "$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.", + "properties": { + "cases": { + "description": "Every case judged, in the dataset's order.", + "items": { + "$ref": "#/$defs/CaseResult" + }, + "type": "array" + }, + "created_at": { + "description": "When the run started.", + "format": "date-time", + "type": "string" + }, + "dataset_name": { + "type": "string" + }, + "duration_seconds": { + "description": "How long judging the dataset took.", + "type": "number" + }, + "metadata": { + "description": "What sets this run apart from others of the same dataset, like the variant, args and --meta values.", + "type": "object" + }, + "schema_version": { + "const": 2, + "description": "The version of this format. Changes that could break a reader bump it." + }, + "source": { + "$ref": "#/$defs/Source" + } + }, + "required": [ + "schema_version", + "dataset_name", + "created_at", + "cases", + "duration_seconds", + "metadata", + "source" + ], + "title": "eac results", + "type": "object" +} diff --git a/scripts/generate.py b/scripts/generate.py index fa28832..fa79683 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -1,11 +1,8 @@ -"""Generates the worker protocol's files from core's Rust types. +"""Generates files from core's Rust types. - core/src/schema/protocol.schema.json `eac schema` - sdks/python/eac/protocol.py python() below, from the schema - -With --check, writes nothing and fails if either is out of date. Run it with -`make generate` or `make generate-check`. Uses only the standard library, so -it runs on Python 3.9 or newer. + schemas/results.schema.json `eac schema results`, the public results format + core/src/schema/protocol.schema.json `eac schema protocol`, the worker protocol + sdks/python/eac/protocol.py python() below, from the protocol's schema """ from __future__ import annotations @@ -18,10 +15,11 @@ from typing import Any ROOT = Path(__file__).resolve().parent.parent -SCHEMA = "core/src/schema/protocol.schema.json" +RESULTS = "schemas/results.schema.json" +PROTOCOL = "core/src/schema/protocol.schema.json" PYTHON = "sdks/python/eac/protocol.py" -GENERATED = f"Generated by `make generate` from {SCHEMA}; DO NOT EDIT." +GENERATED = f"Generated by `make generate` from {PROTOCOL}; DO NOT EDIT." # The method tables in $defs, and the name each one's union of method names gets. TABLES = {"WorkerMethods": "WorkerMethod"} @@ -35,15 +33,12 @@ def main() -> None: - schema_text = subprocess.run( - ["cargo", "run", "--quiet", "--manifest-path", "core/Cargo.toml", "--", "schema"], - cwd=ROOT, - stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, - check=True, - encoding="utf-8", - ).stdout - files = {SCHEMA: schema_text, PYTHON: python(json.loads(schema_text))} + schema_text = eac_schema("protocol") + files = { + PROTOCOL: schema_text, + RESULTS: eac_schema("results"), + PYTHON: python(json.loads(schema_text)), + } if "--check" in sys.argv[1:]: stale = [path for path, text in files.items() if read(path) != text] @@ -58,6 +53,17 @@ def main() -> None: (ROOT / path).write_text(text, encoding="utf-8", newline="\n") +def eac_schema(which: str) -> str: + return subprocess.run( + ["cargo", "run", "--quiet", "--manifest-path", "core/Cargo.toml", "--", "schema", which], + cwd=ROOT, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + check=True, + encoding="utf-8", + ).stdout + + def read(path: str) -> str | None: try: return (ROOT / path).read_text(encoding="utf-8") diff --git a/sdks/python/README.md b/sdks/python/README.md index 2e49860..f73b8bf 100644 --- a/sdks/python/README.md +++ b/sdks/python/README.md @@ -25,20 +25,20 @@ the nearest `.venv`, `uv run python` if the project has a `uv.lock`, and ## Project layout ``` -eac.yml marks the project root, and holds what datasets share +eac.yml optional: marks the project root, and holds what datasets share evals/ chat/ dataset.yml the dataset: its name, and the code it runs dataset.py that code: runner, cases, judges, seeds ``` -eac finds every `dataset.yml` under the root, so adding a dataset doesn't -touch `eac.yml`. Run `eac` from the root or below it, or point it at the root -with `-C dir`. +The project root is the nearest folder with an `eac.yml`, or else the git +repository's root. eac finds every `dataset.yml` under it. Run `eac` from the +root or below it, or point it at the root with `-C dir`. ## eac.yml -An empty file is fine. Every key is optional: +Most projects don't need one. Every key is optional: ```yaml artifacts: .eac # where runs and the seed cache go @@ -48,13 +48,9 @@ runtimes: python: command: [uv, run, python] # the interpreter to use env: {PYTHONPATH: src} # extra environment for your code - -online: - judges: # judges every online dataset offers - - {name: polite, path: "evals.judges:Polite", runtime: python} ``` -Your code also gets the variables in a `.env` next to `eac.yml`, unless the +Your code also gets the variables in a `.env` in the project root, unless the real environment already sets them. ## dataset.yml @@ -90,14 +86,13 @@ The `offline` section can also have: ```python from eac import Case -from eac.judges import Contains, Equals CASES = [ Case( name="greets", input={"query": "hi"}, expected_output={"response": "hello"}, - judges=[Contains(["hello"]), Equals()], + judges=[Matches()], # see Judges below splits=["smoke"], # pick with --split smoke ), ] @@ -105,6 +100,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. - `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 @@ -120,73 +118,70 @@ The runner calls your system on one case and returns its raw output. Scoring is left to the judges. ```python -from eac import Case, Context, OfflineRunner +from eac import Case, OfflineRunner class ChatRunner(OfflineRunner): - def execute(self, case: Case, ctx: Context) -> dict: - reply = my_chatbot(case.input["query"], tag=ctx.conversation_id) + def run_case(self, case: Case, *, seeds, conversation_id) -> dict: + model = self.args.get("model", "small") + reply = my_chatbot(case.input["query"], model=model, tag=conversation_id) return {"response": reply} ``` -`ctx` holds: - -- `ctx.seed(name)`: a seed's handle, by the seed's name. -- `ctx.args`: the run's `--args`, as a dict. -- `ctx.conversation_id`: tag your agent's run with it, so a judge's +- `seeds` maps each of the case's seed names to its handle. +- 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. ## Judges -A judge scores one case's output from 0 to 1. Three come built in: +A judge scores one case's output from 0 to 1. Judges are your own code: subclass +`Judge` and read `case.output`. ```python -from eac.judges import Contains, Equals -from eac.common.judges.regex_judge import Regex - -Contains(["hello", "world"]) # fraction of substrings in output["response"] -Contains(["error"], field="log") # ...or in another field -Equals() # output["response"] == expected_output["response"] -Regex([r"https://\S+"], output_lambda=lambda out: (out or {}).get("response", "")) -``` +from eac import Judge, Score -A custom judge subclasses `Judge`: +class Matches(Judge): + name = "matches" # what its scores are called -```python -from eac import Judge, Score + def judge(self, case, *, seeds, agent_trace=None): + expected = case.expected_output.get("response") + if expected is None: + return None # doesn't apply, e.g. online + ok = case.output.get("response") == expected + return Score(name=self.name, score=1.0 if ok else 0.0, explanation=None if ok else "wrong reply") class CalledTool(Judge): - name = "called_tool" # what its scores are called + name = "called_tool" def __init__(self, tool: str): self.tool = tool - def judge(self, *, case_output, case, seed_results, agent_trace=None): - called = case_output.get("tool_calls") or [] - ok = self.tool in called - return Score( - name=self.name, - score=1.0 if ok else 0.0, - explanation=None if ok else f"{self.tool} wasn't called", - ) + def judge(self, case, *, seeds, agent_trace=None): + ok = self.tool in (case.output.get("tool_calls") or []) + return Score(name=self.name, score=1.0 if ok else 0.0) ``` -- `seed_results` maps each of the case's seed names to its handle. +- `seeds` maps each of the case's seed names to its handle. - `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. It fails when any is lower or it has no -scores, and errors when the runner raised. A judge that raises scores 0 with -the label "judge error". +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". -For settings that change per run, like a rubric, give the judge an -`args_model`: a pydantic model whose fields all have defaults. eac validates -`--judge-args '{"called_tool": {...}}'`, keyed by the judge's name, against -it, and sets `self.args` before judging. +For settings that change per run, like a rubric, pass +`--judge-args '{"called_tool": {...}}'`, keyed by the judge's name. The judge +gets its entry as `self.args`, a plain dict, or `{}` without one. eac doesn't +check them, so check any you rely on yourself. eac does reject a name that no +judge in the run has. ### Agent traces @@ -211,14 +206,13 @@ class SentryJudge(Judge): class UsedTheRightTool(SentryJudge): name = "used_the_right_tool" - def judge(self, *, case_output, case, seed_results, agent_trace=None): + def judge(self, case, *, seeds, agent_trace=None): ... ``` -- `run` is an `AgentRun`: the `conversation_id` the agent's run was tagged - with (`ctx.conversation_id`, or a `Record`'s online), the dataset, its - `agent` from `dataset.yml`, the case's name, and when it ran, which is - `None` for production records. +- `run` is an `AgentRun`: the case's `conversation_id`, the dataset, its + `agent` from `dataset.yml`, the case's name, and when the runner ran it, + which is `None` for collected production runs. - Before judging a case, eac asks its judges in order and gives the first trace found to every one of them. Each class's `get_agent_trace()` is asked once per case, so judges sharing a base class cost one lookup. One that @@ -299,33 +293,35 @@ class SharedSeed(Seed): ## Online runner -An online runner fetches what your system already did in production, so the -online judges can score it. Nothing is re-run. +An online runner collects what your system already did in production, as +cases with their outputs, so the online judges can score them. Nothing is +re-run. ```python -from eac import OnlineRunner, Record +from eac import Case, OnlineRunner class ProdChats(OnlineRunner): - def fetch(self, since, until, limit): + def collect_cases(self, window): return [ - Record( - id=row.id, + Case( + name=row.id, input={"query": row.query}, output={"response": row.reply}, conversation_id=row.trace_id, # for get_agent_trace() ) - for row in query_traces(since, until, limit) + for row in query_traces(window.since, window.until, window.limit) ] ``` -`fetch` returns at most `limit` records from `[since, until)`. +`collect_cases` returns at most `window.limit` cases from +`[window.since, window.until)`. As offline, `self.args` is the run's `--args`. -Online judges are named in `dataset.yml`, or shared from `eac.yml`, and picked -with `--judge `. `eac online run --judge ` collects records and +Online judges are named in each `dataset.yml` and picked with +`--judge `. `eac online run --judge ` collects cases and judges them in one go, or `eac online collect` saves them in a run for -`eac online judge --run --judge ` to score later. Production records have no -`expected_output`, so judges like `Equals` don't apply. Online runs report each -judge's mean score and never fail. +`eac online judge --run --judge ` to score later. Production runs +have no `expected_output`, so judges that compare against it should return +`None`. Online runs report each judge's mean score and never fail. ## Storing results @@ -372,8 +368,7 @@ 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. -- A runner's `credentials(args)` method, since `--args` can change what it - needs. eac checks them before collecting. +- A runner's `credentials`. eac checks them before collecting. - A judge's `credentials`, checked before judging. Include what `get_agent_trace()` needs. @@ -406,7 +401,7 @@ eac --help # every command and flag Narrow a run with `--dataset`, `--case` and `--split`, and pass runner args with `--args '{"model": "big"}'`. Each run is saved under `.eac/runs//`. -eac exits with `0` when everything passed, `1` on failures or errors, and `2` +eac exits with `0` when no case failed or errored, `1` when any did, and `2` when eac itself failed. Runner, judge and seed methods can be sync or async. Async ones run diff --git a/sdks/python/eac/__init__.py b/sdks/python/eac/__init__.py index 6ed73d6..0dae3e6 100644 --- a/sdks/python/eac/__init__.py +++ b/sdks/python/eac/__init__.py @@ -1,37 +1,26 @@ from eac._version import __version__ from eac.credential import Credential -from eac.judge.judge import Judge -from eac.models import ( - AgentRun, - AgentTrace, - Case, - Context, - LLMMetrics, - OfflineRunner, - OnlineRunner, - Record, - Score, - from_jsonl, - stable_hash, -) +from eac.judge import Judge +from eac.models import AgentRun, AgentTrace, Case, Handle, LLMMetrics, Score, Window, from_jsonl, stable_hash from eac.protocol import PROTOCOL_VERSION -from eac.seed.seed import Seed, current_week_salt +from eac.runner import OfflineRunner, OnlineRunner +from eac.seed import Seed, current_week_salt __all__ = [ "__version__", "AgentRun", "AgentTrace", "Case", - "Context", "Credential", + "Handle", "Judge", "LLMMetrics", "OfflineRunner", "OnlineRunner", "PROTOCOL_VERSION", - "Record", "Score", "Seed", + "Window", "current_week_salt", "from_jsonl", "stable_hash", diff --git a/sdks/python/eac/common/judges/regex_judge.py b/sdks/python/eac/common/judges/regex_judge.py deleted file mode 100644 index f95455e..0000000 --- a/sdks/python/eac/common/judges/regex_judge.py +++ /dev/null @@ -1,46 +0,0 @@ -from __future__ import annotations - -from typing import Any, Callable, ClassVar, Sequence -import re -from eac.judge.judge import Judge -from eac.models import Case, Score - -OutputLambda = Callable[[dict[str, Any] | None], str] - -class Regex(Judge): - """Fraction of the given patterns that match a field of the output.""" - - name: ClassVar[str] = "regex" - # Pulls the text to match out of the case output. - output_lambda: OutputLambda | None = None - - def __init__( - self, - patterns: Sequence[str], # TODO: Type? - *, - output_lambda: OutputLambda | None = None, - ): - if not patterns: - raise ValueError("Regex needs at least one pattern") - - self.patterns = [re.compile(p) for p in patterns] - self.output_lambda = output_lambda - - def judge( - self, - *, - case: Case, - case_output: dict[str, Any] | None, - seed_results: dict[str, dict[str, Any]], - agent_trace: Any = None, - ) -> Score: - # TODO - text = self.output_lambda(case_output) - matched = [p.pattern for p in self.patterns if p.search(text)] - missed = [p.pattern for p in self.patterns if not p.search(text)] - return Score( - name=self.name, - score=len(matched) / len(self.patterns), - explanation=None if not missed else f"no match for: {', '.join(missed)}", - metadata={"matched": matched, "missed": missed}, - ) diff --git a/sdks/python/eac/credential.py b/sdks/python/eac/credential.py index 0b5c479..0f05df6 100644 --- a/sdks/python/eac/credential.py +++ b/sdks/python/eac/credential.py @@ -9,10 +9,10 @@ class Credential(ABC): """Credentials a seed, runner or judge needs, such as a token in .env or a CLI login. - List them in `credentials` on a Seed or Judge, or return them from a - runner's credentials(). Before each phase, eac checks every - distinct credential the phase needs and stops if one isn't set up. On a - terminal it offers to log in first, and `eac auth` logs in to every one. + List them in `credentials` on a Seed, Judge or runner. Before each phase, + eac checks every distinct credential the phase needs and stops if one + isn't set up. On a terminal it offers to log in first, and `eac auth` logs + in to every one. eac rebuilds credentials in other processes from their class and fields, so make each a frozen dataclass whose fields are JSON values, or a class diff --git a/sdks/python/eac/judge/__init__.py b/sdks/python/eac/judge/__init__.py new file mode 100644 index 0000000..8ce87ff --- /dev/null +++ b/sdks/python/eac/judge/__init__.py @@ -0,0 +1,3 @@ +from eac.judge.judge import Judge + +__all__ = ["Judge"] diff --git a/sdks/python/eac/judge/judge.py b/sdks/python/eac/judge/judge.py index 48dbf8c..24904c1 100644 --- a/sdks/python/eac/judge/judge.py +++ b/sdks/python/eac/judge/judge.py @@ -5,53 +5,34 @@ if TYPE_CHECKING: from eac.credential import Credential - from eac.models import AgentRun, AgentTrace, Case, Score + from eac.models import AgentRun, AgentTrace, Case, Handle, Score class Judge(ABC): - name: ClassVar[str] + """Scores a case's output from 0 to 1.""" - #: Validates the `--judge-args` given under this judge's name. Usually a - #: pydantic model, but anything with model_validate() and - #: model_json_schema() works. Args are optional, so every field needs a - #: default. None means the judge takes no args. - args_model: ClassVar[type[Any] | None] = None + #: What its scores are called, and what --judge-args are keyed by. + name: ClassVar[str] - #: This run's validated args. eac sets them on a copy of the judge before - #: judging. - args: Any = None + #: The --judge-args given under this judge's name, as given. eac sets them + #: on a copy of the judge, one per distinct args, before judging. Checking + #: them is up to you. + args: dict[str, Any] = {} #: What judging needs, such as an LLM provider's key or what #: get_agent_trace() reads traces with. eac checks them before the judge #: phase. credentials: Sequence[Credential] = () - def with_args(self, args: dict[str, Any] | None) -> Judge: - - """Return this judge configured by `--judge-args`. Raise ValueError for - invalid args.""" - if self.args_model is None: - raise ValueError("Judge does not accept args") - - self.args = self.args_model.model_validate(args) - return self - @abstractmethod - def judge( - self, - *, - case_output: dict[str, Any], - case: Case, - seed_results: dict[str, dict[str, Any]], # TODO: Type? - agent_trace: Any = None, # TODO: Type? - ) -> Score | None: - """Return a Score, or None if this judge doesn't apply to the case, - e.g. one without the expected output it compares against. May be async. - - Cases whose execution raised are never judged. `seed_results` maps - each of the case's seed names to its handle and is empty for online - records. `agent_trace` is the trace a judge's get_agent_trace() - found, or None. + def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None) -> Score | None: + """Score `case.output`, or return None if this judge doesn't apply to + the case, e.g. one without the expected output it compares against. + May be async. + + 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. """ def get_agent_trace(self, run: AgentRun) -> AgentTrace | None: diff --git a/sdks/python/eac/judges.py b/sdks/python/eac/judges.py deleted file mode 100644 index 2eff828..0000000 --- a/sdks/python/eac/judges.py +++ /dev/null @@ -1,78 +0,0 @@ -from __future__ import annotations - -import re - -from typing import Any, ClassVar, Sequence - -from eac.judge.judge import Judge -from eac.models import Case, Score - - -def _field(output: dict[str, Any] | None, key: str) -> str: - if not output: - return "" - value = output.get(key) - return value if isinstance(value, str) else ("" if value is None else str(value)) - - -class Contains(Judge): - """Fraction of the given substrings present in a field of the output.""" - - name: ClassVar[str] = "contains" - - def __init__(self, substrings: Sequence[str], *, field: str = "response", case_sensitive: bool = False): - if not substrings: - raise ValueError("Contains needs at least one substring") - self.substrings = list(substrings) - self.field = field - self.case_sensitive = case_sensitive - - def judge( - self, - *, - case_output: dict[str, Any], - case: Case, - seed_results: dict[str, dict[str, Any]], - agent_trace: Any = None, - ) -> Score: - text = _field(case_output, self.field) - if not self.case_sensitive: - text = text.lower() - wanted = [s if self.case_sensitive else s.lower() for s in self.substrings] - missed = [s for s in wanted if s not in text] - return Score( - name=self.name, - score=(len(wanted) - len(missed)) / len(wanted), - explanation=None if not missed else f"missing: {', '.join(missed)}", - metadata={"missing": missed, "field": self.field}, - ) - - -class Equals(Judge): - """Exact match of a field against the case's expected_output. Doesn't - apply to cases without one, like online records.""" - - name: ClassVar[str] = "equals" - - def __init__(self, *, field: str = "response"): - self.field = field - - def judge( - self, - *, - case_output: dict[str, Any], - case: Case, - seed_results: dict[str, dict[str, Any]], - agent_trace: Any = None, - ) -> Score | None: - if self.field not in case.expected_output: - return None - expected = case.expected_output[self.field] - actual = case_output.get(self.field) - ok = expected == actual - return Score( - name=self.name, - score=1.0 if ok else 0.0, - explanation=None if ok else f"expected {expected!r}, got {actual!r}", - metadata={"field": self.field}, - ) diff --git a/sdks/python/eac/models.py b/sdks/python/eac/models.py index 48dd9b8..4cfa11d 100644 --- a/sdks/python/eac/models.py +++ b/sdks/python/eac/models.py @@ -5,22 +5,20 @@ import inspect import json import os - -from abc import ABC, abstractmethod from dataclasses import dataclass, field from datetime import datetime -from typing import TYPE_CHECKING, Any, ClassVar, Iterable, Sequence +from typing import TYPE_CHECKING, Any, Sequence if TYPE_CHECKING: - from eac.credential import Credential - from eac.judge.judge import Judge - from eac.seed.seed import Seed + from eac.judge import Judge + from eac.seed import Seed + +#: What a seed's setup() returned: plain JSON, like ids and URLs. +Handle = dict[str, Any] @dataclass(frozen=True) class LLMMetrics: - """LLM usage.""" - input_tokens: float = 0 output_tokens: float = 0 total_tokens: float = 0 @@ -35,12 +33,10 @@ class LLMMetrics: @dataclass(frozen=True) class Score: - """A judgement between 0 and 1. A None score is recorded and shown but - doesn't gate the verdict.""" - + #: Usually the judge's name. name: str + #: From 0 to 1. None is recorded but doesn't count toward pass or fail. score: float | None = None - label: str | None = None explanation: str | None = None metadata: dict[str, Any] = field(default_factory=dict) #: What an LLM judge spent producing this score. @@ -51,32 +47,20 @@ def __post_init__(self) -> None: raise ValueError(f"score must be between 0 and 1, got {self.score}") - - - -@dataclass -class Context: - """What an OfflineRunner is given alongside its case.""" - - seeds: dict[str, dict[str, Any]] = field(default_factory=dict) - #: The run's --args. - args: dict[str, Any] = field(default_factory=dict) - #: Tag the system's agent run with this, so its trace can be found for judging. - conversation_id: str | None = None - - def seed(self, name: str) -> dict[str, Any]: - try: - return self.seeds[name] - except KeyError: - known = ", ".join(sorted(self.seeds)) or "(none)" - raise KeyError(f"no seed named {name!r} in this case; available: {known}") from None - - @dataclass(frozen=True) class Case: + """An offline case to run, or a production run an OnlineRunner collected.""" + name: str input: dict[str, Any] = field(default_factory=dict) expected_output: dict[str, Any] = field(default_factory=dict) + #: 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) + #: The ID the agent's run was tagged with, for get_agent_trace(). Set + #: like `output`. + conversation_id: str | None = None #: Named groups `eac --split` picks cases by. splits: Sequence[str] = () #: A disabled case runs only when picked by name or by one of its splits. @@ -92,36 +76,33 @@ def __post_init__(self) -> None: # Runners and judges look seeds up by name, children included. names = [seed.name for seed in walk(self.seeds)] - duplicates = sorted({name for name in names if names.count(name) > 1}) - if duplicates: + 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)}") @dataclass(frozen=True) -class Record: - """One thing the system already did, as observed in production.""" +class Window: + """The production runs an OnlineRunner collects: at most `limit` of them, + from `since` up to, but not including, `until`.""" - id: str - input: dict[str, Any] = field(default_factory=dict) - output: dict[str, Any] = field(default_factory=dict) - #: Lets judges fetch the production run's agent trace. - conversation_id: str | None = None + since: datetime + until: datetime + limit: int @dataclass(frozen=True) class AgentRun: """The agent run a judge's get_agent_trace() looks the trace up by.""" - #: What the run was tagged with: Context.conversation_id offline, or the - #: Record's conversation_id online. + #: What the run was tagged with: the case's conversation_id. conversation_id: str #: The dataset's name, from its dataset.yml. dataset: str #: The production agent, from dataset.yml's `agent`. agent: str | None - #: The case's name, or the record's id online. + #: The case's name. case: str - #: When the case ran. None for production records. + #: When the runner ran the case. None for collected production runs. started_at: datetime | None = None ended_at: datetime | None = None @@ -135,42 +116,6 @@ class AgentTrace: metrics: LLMMetrics | None = None -class OfflineRunner(ABC): - """Calls the system under test on the dataset's cases. - - Reference it from `offline.runner` in dataset.yml, as a configured instance - or a subclass that takes no arguments. - """ - - @abstractmethod - def execute(self, case: Case, ctx: Context) -> dict[str, Any]: - """Run the case and return its output as a JSON-serializable dict. - May be async.""" - - def credentials(self, args: dict[str, Any]) -> Sequence[Credential]: - """What running cases with these --args needs. eac checks them - before the collect phase. Defaults to none.""" - return () - - -class OnlineRunner(ABC): - """Reads output the system already produced in production. - - Reference it from `online.runner` in dataset.yml, next to the `judges` - that score its records. - """ - - @abstractmethod - def fetch(self, since: datetime, until: datetime, limit: int) -> Iterable[Record]: - """Return at most `limit` Records observed in [since, until). May be - async.""" - - def credentials(self, args: dict[str, Any]) -> Sequence[Credential]: - """What fetching records with these --args needs. eac checks them - before the collect phase. Defaults to none.""" - return () - - def stable_hash(value: Any) -> str: """A short, deterministic hash of any JSON-able value.""" return hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest()[:16] @@ -179,7 +124,7 @@ def stable_hash(value: Any) -> str: def from_jsonl(pattern: str, *, judges: Sequence[Judge] = (), splits: Sequence[str] = ()) -> list[Case]: """Cases from JSONL files, relative to the file that calls this. - Each line is {"name", "input", "expected_output"}. + Each line is {"name", "input", "expected_output", "splits"}. """ root = os.path.dirname(os.path.abspath(inspect.stack()[1].filename)) paths = sorted(glob.glob(os.path.join(root, pattern))) diff --git a/sdks/python/eac/protocol.py b/sdks/python/eac/protocol.py index d940a77..1588ec3 100644 --- a/sdks/python/eac/protocol.py +++ b/sdks/python/eac/protocol.py @@ -10,8 +10,8 @@ PROTOCOL_VERSION = 1 -#: What a seed's setup returned. It must be JSON-serializable because it's written to -#: seeds.json and read back by a later phase. +#: What a seed's setup returned. Saved to seeds.json for later phases, so it must be +#: JSON. Handle = dict[str, Any] Mode = Literal["offline", "online"] @@ -19,12 +19,12 @@ #: The methods an SDK worker answers. WorkerMethod = Literal[ "args.validate", - "case.execute", "case.judge", + "case.run", "credentials.check", "credentials.login", "discover", - "online.fetch", + "online.collect", "online.judge", "seed.setup", "seed.teardown", @@ -36,98 +36,107 @@ class ArgsValidateParams(TypedDict): dataset: DatasetRef #: --judge-args, by judge name. judge_args: NotRequired[dict[str, Any]] - #: Online: the judges picked. Offline: judges that replace every case's own, as in a - #: comparison. Empty keeps each case's judges. + #: 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. judges: NotRequired[list[str]] mode: Mode class ArgsValidateResult(TypedDict): - #: The args with defaults filled in. Absent keeps them as sent. - args: NotRequired[dict[str, Any] | None] - #: What each of the run's judges needs, by the name cases and --judge use. + #: The credentials each of the run's judges needs, by judge name. judge_credentials: NotRequired[dict[str, list[Credential]]] - #: What the runner needs with these args. + #: The credentials the runner needs. runner_credentials: NotRequired[list[Credential]] class Case(TypedDict): + """An offline case, or a production run collected for online judging.""" + + #: The ID the agent's run was tagged with, for judges to fetch its trace by. Set + #: like `output`. + 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] - #: Names, for display only. Judges run inside the worker. + #: 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] seeds: NotRequired[list[Seed]] splits: NotRequired[list[str]] -class CaseExecuteParams(TypedDict): - args: NotRequired[dict[str, Any]] - case: Case - #: Tag the agent run with this so its trace can be fetched for judging. - conversation_id: str - dataset: DatasetRef - #: Handles by seed name. - seeds: NotRequired[dict[str, Handle]] - - -class CaseExecuteResult(TypedDict): - #: Overrides the conversation id eac sent, if the agent used another. - conversation_id: NotRequired[str | None] - metrics: NotRequired[Metrics | None] - #: Must be JSON-serializable, since it's saved for the judge phase. - output: NotRequired[dict[str, Any] | None] - - class CaseJudgeParams(TypedDict): - #: The production agent, from dataset.yml. + #: The agent named in dataset.yml. agent: NotRequired[str | None] + #: With the runner's `output` and `conversation_id`. case: Case - #: The id the agent run was tagged with. - conversation_id: NotRequired[str | None] 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 by name that replace the case's own, as in a comparison. Empty keeps the - #: case's own. + #: Judges to use instead of the case's own, as in a comparison. Empty keeps the + #: case's judges. judges: NotRequired[list[str]] - output: dict[str, Any] | None seeds: NotRequired[dict[str, Handle]] - #: When the case ran. + #: When the runner started. started_at: NotRequired[str | None] #: The agent trace an earlier judge phase saved. Without one, the judges may fetch - #: it by conversation_id. + #: it by the case's conversation_id. trace: NotRequired[Any] class CaseJudgeResult(TypedDict): - """Also what online.judge returns.""" + """What case.judge and online.judge return.""" scores: NotRequired[list[Score]] - #: The agent trace a judge fetched, if eac didn't send one. eac saves it, so judging - #: again doesn't fetch it again. + #: The agent trace a judge fetched, if eac didn't send one. eac saves it for later + #: judge runs. trace: NotRequired[Any] - #: The LLM usage the fetched trace records. It replaces what the runner reported. + #: The LLM usage recorded in the fetched trace. It replaces what the runner + #: reported. trace_metrics: NotRequired[Metrics | None] +class CaseRunParams(TypedDict): + args: NotRequired[dict[str, Any]] + case: Case + #: 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, Handle]] + + +class CaseRunResult(TypedDict): + #: The conversation ID the agent used, if it isn't the one eac sent. + 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] + + class Credential(TypedDict): - """Credentials a seed, runner or judge needs, such as a token or a CLI login. The - SDK rebuilds it from `path` and `fields` to check it or log in, so eac can check - each distinct one once, before the phases that need it. + """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. """ - #: What its class is built with. + #: The arguments its class is built with. fields: NotRequired[dict[str, Any]] - #: It can only be set up by hand, so eac shows how instead of offering to log in. + #: Can only be set up by hand, so eac shows the instructions instead of offering to + #: log in. manual: NotRequired[bool] - #: Shown in status lines and prompts, e.g. "github". + #: Shown in status lines and prompts, like "github". name: str - #: Its class. + #: The credential's class, as a code reference. path: str #: How to set it up by hand, shown when it isn't set up. setup_instructions: NotRequired[str] @@ -147,19 +156,19 @@ class CredentialsLoginParams(TypedDict): class CredentialsLoginResult(TypedDict): - #: Environment variables the credential needs. eac gives them to every process it - #: starts, and saves them for later commands once the credential checks out. + #: Environment variables the credential sets. eac passes them to every process it + #: starts and saves them once the credential checks out. env: NotRequired[dict[str, str]] class DatasetRef(TypedDict): - """Where a dataset's code is, per its dataset.yml. Every worker method that needs - the dataset gets this, so a worker can import it in any phase. + """Where a dataset's code is, from its dataset.yml. Sent with every method that + needs the dataset, so any worker can import it. """ - #: Offline: the sequence of Cases. + #: The dataset's cases. Offline only. cases: NotRequired[str | None] - #: Online: the judges `eac online judge --judge` picks from. + #: The judges --judge picks from. Online only. judges: NotRequired[list[JudgeRef]] mode: Mode #: The dataset's name, from its dataset.yml. @@ -173,15 +182,11 @@ class DiscoverParams(TypedDict): class DiscoverResult(TypedDict): - """What only the dataset's code knows. Its dataset.yml says the rest.""" + """What eac learns by importing the dataset's code. Its dataset.yml covers the rest. + """ - #: JSON Schema of the runner's --args. - args_schema: NotRequired[Any] - #: Offline: every case. + #: Every case. Offline only. cases: NotRequired[list[Case]] - #: JSON Schema of each judge's --judge-args, by judge name, for the judges that take - #: any. - judge_args_schemas: NotRequired[dict[str, Any]] class Error(TypedDict): @@ -190,16 +195,16 @@ class Error(TypedDict): class JudgeRef(TypedDict): - """A judge named in a dataset.yml or in eac.yml's online.judges.""" + """A judge named in a dataset.yml's online.judges.""" - #: The name --judge and --judge-args use. Its scores keep the judge's own name. + #: The name --judge and --judge-args use. Scores still carry the judge's own name. name: str #: A Judge class, built with no arguments, or a configured instance. path: str class Metrics(TypedDict): - """LLM usage for one case, reported by the runner or derived from its trace.""" + """LLM usage: tokens, calls, time and cost.""" cache_read_tokens: NotRequired[float] cache_write_tokens: NotRequired[float] @@ -213,28 +218,31 @@ class Metrics(TypedDict): total_tokens: NotRequired[float] -class OnlineFetchParams(TypedDict): +class OnlineCollectParams(TypedDict): args: NotRequired[dict[str, Any]] dataset: DatasetRef limit: int - #: RFC 3339. Only records in [since, until) are returned. + #: RFC 3339. Return runs from since up to, but not including, until. since: str until: str -class OnlineFetchResult(TypedDict): - records: NotRequired[list[Record]] +class OnlineCollectResult(TypedDict): + #: One case per production run, each with its `output` and, if it has one, its + #: `conversation_id`. + cases: NotRequired[list[Case]] class OnlineJudgeParams(TypedDict): agent: NotRequired[str | None] + #: 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 the names their YAML gives them. + #: The judges picked, by their YAML names. judges: list[str] - record: Record - #: As in case.judge. The record's conversation_id identifies its trace. + #: As in case.judge. The case's conversation_id identifies the trace. trace: NotRequired[Any] @@ -244,16 +252,6 @@ class Ready(TypedDict): protocol: Literal[1] -class Record(TypedDict): - """One thing the system already did, observed in production.""" - - #: Identifies the production run's agent trace, for judges to fetch. - conversation_id: NotRequired[str | None] - id: str - input: NotRequired[dict[str, Any] | None] - output: NotRequired[dict[str, Any] | None] - - class Request(TypedDict): id: int method: str @@ -267,27 +265,29 @@ class Response(TypedDict): class Score(TypedDict): - """A score from 0 to 1. A null score is diagnostic and doesn't affect the verdict. + """A judge's score from 0 to 1. A null score is recorded but doesn't count toward + pass or fail. """ + #: Why the judge gave this score. explanation: NotRequired[str | None] - label: NotRequired[str | None] - #: What an LLM judge spent producing this score. + #: 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] class Seed(TypedDict): - """A fixture. `key` is a content hash, and seeds with the same key are set up once - and shared. + """A fixture. Seeds with the same `key`, a content hash, are set up once and shared. """ - #: Cached seeds are reused across runs while their key matches. Uncached ones are - #: torn down after the run, e.g. because the agent mutates them. + #: 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. cache: NotRequired[bool] - #: What setting it up or tearing it down needs, its children's included. + #: The credentials setting it up or tearing it down needs, including its children's. credentials: NotRequired[list[Credential]] key: str name: str @@ -305,7 +305,7 @@ class SeedSetupResult(TypedDict): class SeedTeardownParams(TypedDict): - """A cached seed is also removed from its own cache, before it's torn down.""" + """A cached seed is also removed from its own cache before it's torn down.""" dataset: DatasetRef handle: Handle diff --git a/sdks/python/eac/runner/__init__.py b/sdks/python/eac/runner/__init__.py new file mode 100644 index 0000000..cfeae3b --- /dev/null +++ b/sdks/python/eac/runner/__init__.py @@ -0,0 +1,5 @@ +from eac.runner.offline_runner import OfflineRunner +from eac.runner.online_runner import OnlineRunner +from eac.runner.runner import Runner + +__all__ = ["OfflineRunner", "OnlineRunner", "Runner"] diff --git a/sdks/python/eac/runner/offline_runner.py b/sdks/python/eac/runner/offline_runner.py new file mode 100644 index 0000000..7103444 --- /dev/null +++ b/sdks/python/eac/runner/offline_runner.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +from abc import abstractmethod +from typing import Any + +from eac.models import Case, Handle +from eac.runner.runner import Runner + + +class OfflineRunner(Runner): + """Calls the system under test on the dataset's cases. + + Reference it from `offline.runner` in dataset.yml, as a configured instance + or a subclass that takes no arguments. + """ + + @abstractmethod + def run_case(self, case: Case, *, seeds: dict[str, Handle], conversation_id: str) -> dict[str, Any]: + """Run the case and return its output as a JSON-serializable dict. + May be async. + + `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. + """ diff --git a/sdks/python/eac/runner/online_runner.py b/sdks/python/eac/runner/online_runner.py new file mode 100644 index 0000000..016707f --- /dev/null +++ b/sdks/python/eac/runner/online_runner.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from abc import abstractmethod +from typing import Iterable + +from eac.models import Case, Window +from eac.runner.runner import Runner + + +class OnlineRunner(Runner): + """Collects what the system already did in production, as cases for the + dataset's online judges to score. + + Reference it from `online.runner` in dataset.yml, next to the `judges` + that score its cases. + """ + + @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 + get_agent_trace(). May be async.""" diff --git a/sdks/python/eac/runner/runner.py b/sdks/python/eac/runner/runner.py new file mode 100644 index 0000000..c859d45 --- /dev/null +++ b/sdks/python/eac/runner/runner.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from abc import ABC +from typing import Any, Sequence + +from eac.credential import Credential + + +class Runner(ABC): + """What offline and online runners share.""" + + #: The run's --args, as given. eac sets them on a copy of the runner, one + #: per distinct args, before calling it. Checking them is up to you. + args: dict[str, Any] = {} + + #: What the runner needs. eac checks them before the collect phase. + credentials: Sequence[Credential] = () diff --git a/sdks/python/eac/seed/__init__.py b/sdks/python/eac/seed/__init__.py new file mode 100644 index 0000000..a2d33d2 --- /dev/null +++ b/sdks/python/eac/seed/__init__.py @@ -0,0 +1,3 @@ +from eac.seed.seed import Seed, current_week_salt + +__all__ = ["Seed", "current_week_salt"] diff --git a/sdks/python/eac/worker.py b/sdks/python/eac/worker.py index 3b7b6a2..a4532a0 100644 --- a/sdks/python/eac/worker.py +++ b/sdks/python/eac/worker.py @@ -15,27 +15,16 @@ import os import sys import traceback - -from dataclasses import asdict -from pathlib import Path from datetime import datetime +from pathlib import Path from types import ModuleType from typing import Any, BinaryIO, Callable, Iterable, Sequence from eac import protocol as wire from eac.credential import Credential -from eac.judge.judge import Judge -from eac.models import ( - AgentRun, - AgentTrace, - Case, - Context, - OfflineRunner, - OnlineRunner, - Record, - Score, - stable_hash, -) +from eac.judge import Judge +from eac.models import AgentRun, AgentTrace, Case, Score, Window, stable_hash +from eac.runner import OfflineRunner, OnlineRunner, Runner from eac.seed.seed import Seed, walk REQUEST_FD, RESPONSE_FD = 3, 4 @@ -48,46 +37,30 @@ class WorkerError(Exception): """Reported to the CLI rather than crashed on.""" -async def _maybe_await(value: Any) -> Any: - if inspect.isawaitable(value): - return await value - return value - - -async def _call(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: - """Run a coroutine function on the worker's event loop and anything else - in a thread, so sync user code can block or call asyncio.run().""" - if inspect.iscoroutinefunction(fn): - return await fn(*args, **kwargs) - return await _maybe_await(await asyncio.to_thread(fn, *args, **kwargs)) - - -class Server: - """Answers the CLI's requests. The Worker subclass handles each method.""" +class Worker: + """Answers the CLI's requests, each in a task of its own.""" def __init__(self, reader: asyncio.StreamReader, out: BinaryIO): self._reader = reader self._out = out - - def _send(self, message: wire.Ready | wire.Response) -> None: - # A blocking write with no await, so concurrent responses can't interleave. - self._out.write(json.dumps(message, default=str).encode() + b"\n") - self._out.flush() + #: Each imported dataset, by its DatasetRef. + self._datasets: dict[str, LoadedDataset] = {} async def serve(self) -> None: self._send({"protocol": wire.PROTOCOL_VERSION}) tasks: set[asyncio.Task[None]] = set() - while True: - line = await self._reader.readline() - if not line: - break - # One task per request, so the CLI can send them concurrently. + while line := await self._reader.readline(): task = asyncio.create_task(self._respond(line)) tasks.add(task) task.add_done_callback(tasks.discard) if tasks: await asyncio.gather(*tasks, return_exceptions=True) + def _send(self, message: wire.Ready | wire.Response) -> None: + # A blocking write with no await, so concurrent responses can't interleave. + self._out.write(json.dumps(message, default=str).encode() + b"\n") + self._out.flush() + async def _respond(self, line: bytes) -> None: try: request = json.loads(line) @@ -98,128 +71,64 @@ async def _respond(self, line: bytes) -> None: result = await self._dispatch(request.get("method", ""), request.get("params") or {}) self._send({"id": request_id, "result": result}) except Exception as exc: - self._send( - { - "id": request_id, - "error": { - "message": f"{type(exc).__name__}: {exc}", - "traceback": traceback.format_exc(), - }, - } - ) + error: wire.Error = {"message": f"{type(exc).__name__}: {exc}", "traceback": traceback.format_exc()} + self._send({"id": request_id, "error": error}) async def _dispatch(self, method: str, params: dict[str, Any]) -> Any: - raise NotImplementedError - - -def import_ref(reference: str) -> Any: - """Resolve `module.path:attr`, or `./file.py:attr` relative to the cwd, - which is the project root. The CLI rewrites dataset.yml's ./file - references to be relative to the root.""" - specifier, _, attr = reference.rpartition(":") - if specifier.startswith(("./", "../")): - module = _import_file(Path(specifier)) - else: - module = importlib.import_module(specifier) - try: - return getattr(module, attr) - except AttributeError: - raise WorkerError(f"{specifier} has no {attr!r}, which is referenced as {reference}") from None - - -def _import_file(path: Path) -> ModuleType: - """Import a file by its module name under the deepest sys.path entry that - contains it, so `./evals/chat/cases.py` and `from evals.chat.cases import - ...` share one module. Files outside sys.path are loaded by path.""" - file = path.resolve() - if not file.is_file(): - raise WorkerError(f"no such file: {path}") - roots = sorted({Path(entry or ".").resolve() for entry in sys.path}, key=lambda r: len(r.parts), reverse=True) - for root in roots: - if not file.is_relative_to(root): - continue - parts = file.relative_to(root).with_suffix("").parts - if not all(part.isidentifier() for part in parts): - break - name = ".".join(parts) - module = importlib.import_module(name) - if Path(module.__file__ or "").resolve() != file: - raise WorkerError(f"{path} imports as {name}, but that name is {module.__file__}, which shadows it") - return module - - # So the file can import its neighbors by name. - if str(file.parent) not in sys.path: - sys.path.insert(0, str(file.parent)) - name = f"eac_file_{abs(hash(str(file)))}" - spec = importlib.util.spec_from_file_location(name, file) - if spec is None or spec.loader is None: - raise WorkerError(f"cannot import {path}") - module = importlib.util.module_from_spec(spec) - sys.modules[name] = module - spec.loader.exec_module(module) - return module - + match method: + case "credentials.check": + return await _check_credentials(params["credentials"]) + case "credentials.login": + return await _log_in(params["credential"]) + dataset = self._load(params["dataset"]) + match method: + case "discover": + return dataset.discover() + case "args.validate": + return dataset.validate_args(params.get("judges") or []) + case "seed.setup": + return await dataset.seed_setup(params["seed"]) + case "seed.teardown": + return await dataset.seed_teardown(params["seed"], params.get("handle") or {}) + case "case.run": + return await dataset.run_case(params) + case "online.collect": + return await dataset.collect_cases(params) + case "case.judge" | "online.judge": + return await dataset.judge(params) + case _: + raise WorkerError(f"unknown method {method!r}") -def _build(reference: str, base: type) -> Any: - """Build the referenced `base` subclass with no arguments, or return the - referenced instance.""" - target = import_ref(reference) - if isinstance(target, type) and issubclass(target, base): - try: - return target() - except TypeError as exc: - raise WorkerError(f"can't build {reference}: {exc}; reference a configured instance instead") from None - if isinstance(target, base): - return target - raise WorkerError(f"{reference} isn't a {base.__name__} subclass or instance") + def _load(self, ref: wire.DatasetRef) -> LoadedDataset: + key = json.dumps(ref, sort_keys=True) + if key not in self._datasets: + self._datasets[key] = LoadedDataset(ref) + return self._datasets[key] class LoadedDataset: - """A dataset's code, imported from its dataset.yml references.""" + """A dataset's code, imported from its dataset.yml references, and the + methods that use it.""" def __init__(self, ref: wire.DatasetRef): self.name = ref["name"] + self.offline = ref["mode"] == "offline" self.cases: list[Case] = [] #: Online judges by their dataset.yml names, for --judge to pick from. self.judges: dict[str, Judge] = {} - if ref["mode"] == "offline": + if self.offline: self.runner: Any = _build(ref["runner"], OfflineRunner) - cases = import_ref(ref["cases"]) - if isinstance(cases, (str, bytes)) or not isinstance(cases, Sequence): - raise WorkerError(f"{ref['cases']} isn't a sequence of Cases") - if bad := [c for c in cases if not isinstance(c, Case)]: - raise WorkerError(f"{ref['cases']} has a {type(bad[0]).__name__}, not a Case") - self.cases = list(cases) - names = [case.name for case in self.cases] - if duplicates := sorted({name for name in names if names.count(name) > 1}): - raise WorkerError(f"{ref['cases']} has more than one case named {', '.join(duplicates)}") + self.cases = _import_cases(ref["cases"]) else: self.runner = _build(ref["runner"], OnlineRunner) - for entry in ref.get("judges") or []: - self.judges[entry["name"]] = _build(entry["path"], Judge) - # --judge-args are keyed by judge name and always optional. - args_models: dict[str, Any] = {} - for name, judge in self.all_judges(): - if judge.args_model is None: - continue - if args_models.setdefault(name, judge.args_model) is not judge.args_model: - raise WorkerError( - f"dataset {self.name!r} has judges named {name!r} with different args models, " - f"which --judge-args can't tell apart" - ) - try: - judge.args_model.model_validate({}) - except Exception as exc: - raise WorkerError( - f"dataset {self.name!r}: judge {name!r} needs args, but --judge-args are " - f"optional, so give every field of its args_model a default ({exc})" - ) from None - # Offline judges_named() builds each judge once and caches it here. + self.judges = {entry["name"]: _build(entry["path"], Judge) for entry in ref.get("judges") or []} + #: Offline, the judge judges_named() built for each name. self._named: dict[str, Judge] = {} - - def all_judges(self) -> list[tuple[str, Judge]]: - """Every judge, paired with the name --judge-args uses for it.""" - return [*self.judges.items(), *((judge.name, judge) for case in self.cases for judge in case.judges)] + #: Copies of the runner and judges, by the object and its args' JSON. + self._with_args: dict[tuple[int, str], Runner | Judge] = {} + #: Each case's top-level seed by (name, key). Built when first needed, + #: since key() hashes source files. + self._seeds: dict[tuple[str, str], Seed] | None = None def case(self, name: str) -> Case: for case in self.cases: @@ -237,104 +146,52 @@ def judges_named(self, names: Sequence[str]) -> list[tuple[str, Judge]]: f"available: {', '.join(self.judges)}" ) return [(name, self.judges[name]) for name in names] - out = [] for name in names: - if name not in self._named: - classes = {type(judge) for case in self.cases for judge in case.judges if judge.name == name} - if len(classes) != 1: - found = "no case uses it" if not classes else "more than one class has that name" - raise WorkerError(f"dataset {self.name!r} can't judge with {name}: {found}") - [cls] = classes - try: - self._named[name] = cls() - except TypeError: - raise WorkerError( - f"judge {name} needs a case's arguments to build, so it can't score every case" - ) from None - out.append((name, self._named[name])) - return out - - -class Worker(Server): - def __init__(self, reader: asyncio.StreamReader, out: BinaryIO): - super().__init__(reader, out) - self._datasets: dict[str, LoadedDataset] = {} - # Each dataset's top-level seeds by (name, key). Built lazily, since - # key() hashes source files. - self._seeds: dict[str, dict[tuple[str, str], Seed]] = {} - - async def _dispatch(self, method: str, params: dict[str, Any]) -> Any: - match method: - case "credentials.check": - return await _check_credentials(params["credentials"]) - case "credentials.login": - return await _log_in(params["credential"]) - ref: wire.DatasetRef = params["dataset"] - match method: - case "discover": - return self._discover(ref) - case "args.validate": - return self._validate_args( - ref, - params["mode"], - params.get("args") or {}, - params.get("judges") or [], - params.get("judge_args") or {}, - ) - case "seed.setup": - return await self._seed_setup(ref, params["seed"]) - case "seed.teardown": - return await self._seed_cleanup(ref, params["seed"], params.get("handle") or {}) - case "case.execute": - ctx = Context( - seeds=params.get("seeds") or {}, - args=params.get("args") or {}, - conversation_id=params.get("conversation_id"), - ) - return await self._execute(ref, params["case"], ctx) - case "case.judge": - return await self._judge(ref, params) - case "online.fetch": - return await self._online_fetch(ref, params["since"], params["until"], params["limit"]) - case "online.judge": - return await self._online_judge(ref, params) - case _: - raise WorkerError(f"unknown method {method!r}") - - def _load(self, ref: wire.DatasetRef) -> LoadedDataset: - key = json.dumps(ref, sort_keys=True) - if key not in self._datasets: - self._datasets[key] = LoadedDataset(ref) - return self._datasets[key] - - def _seed(self, ref: wire.DatasetRef, name: str, key: str, *, cleanup: bool = False) -> Seed: - dataset = self._load(ref) - dataset_key = json.dumps(ref, sort_keys=True) - if dataset_key not in self._seeds: - self._seeds[dataset_key] = { - (seed.name, _protocol_seed(case, seed)["key"]): seed - for case in dataset.cases - for seed in case.seeds - } - seeds = self._seeds[dataset_key] - if (name, key) in seeds: - return seeds[(name, key)] + if name in self._named: + continue + classes = {type(judge) for case in self.cases for judge in case.judges if judge.name == name} + if len(classes) != 1: + found = "no case uses it" if not classes else "more than one class has that name" + raise WorkerError(f"dataset {self.name!r} can't judge with {name}: {found}") + try: + self._named[name] = classes.pop()() + except TypeError: + raise WorkerError( + f"judge {name} needs a case's arguments to build, so it can't score every case" + ) from None + return [(name, self._named[name]) for name in names] + + def with_args(self, target: Any, args: dict[str, Any]) -> Any: + """A copy of the runner or a judge with `args` as its self.args. Each + distinct args gets one copy, so state it builds on first use lasts the + command, while each arm of a comparison gets its own.""" + key = (id(target), json.dumps(args, sort_keys=True)) + if key not in self._with_args: + self._with_args[key] = copy.copy(target) + self._with_args[key].args = args + return self._with_args[key] + + def seed(self, name: str, key: str, *, cleanup: bool = False) -> Seed: + if self._seeds is None: + 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 # changed since setup, like one being pruned, is matched by name. if cleanup: - for (seed_name, _), seed in seeds.items(): + for (seed_name, _), seed in self._seeds.items(): if seed_name == name: return seed raise WorkerError( - f"dataset {dataset.name!r} has no seed {name!r} with key {key}. " + f"dataset {self.name!r} has no seed {name!r} with key {key}. " f"If the dataset changed since 'eac offline seed', re-seed the run." ) - def _discover(self, ref: wire.DatasetRef) -> wire.DiscoverResult: - dataset = self._load(ref) - result: wire.DiscoverResult = {} - if ref["mode"] == "offline": - result["cases"] = [ + def discover(self) -> wire.DiscoverResult: + if not self.offline: + return {} + return { + "cases": [ { "name": c.name, "input": c.input, @@ -344,43 +201,21 @@ def _discover(self, ref: wire.DatasetRef) -> wire.DiscoverResult: "seeds": [_protocol_seed(c, seed) for seed in c.seeds], "judges": [judge.name for judge in c.judges], } - for c in dataset.cases + for c in self.cases ] - schemas = { - name: judge.args_model.model_json_schema() - for name, judge in dataset.all_judges() - if judge.args_model is not None } - if schemas: - result["judge_args_schemas"] = schemas - return result - def _validate_args( - self, - ref: wire.DatasetRef, - mode: str, - args: dict[str, Any], - judge_names: list[str], - judge_args: dict[str, Any], - ) -> wire.ArgsValidateResult: - # Runner args aren't validated. They reach the runner as ctx.args. - dataset = self._load(ref) - # Check judges up front so bad args fail before any setup or fetch. - # The CLI checks args for judges this dataset doesn't use, since a - # run's --judge-args cover all its datasets. + def validate_args(self, judge_names: list[str]) -> wire.ArgsValidateResult: + """What the run's runner and judges need. Looking the judges up also + fails early on ones that can't be built. --args and --judge-args aren't + checked; they reach the runner and judges as self.args.""" if judge_names: - judges = dataset.judges_named(judge_names) + judges = self.judges_named(judge_names) else: - judges = [(judge.name, judge) for case in dataset.cases for judge in case.judges] - for name, judge in dict(judges).items(): - if name not in judge_args: - continue - if judge.args_model is None: - raise WorkerError(f"judge {name!r} takes no --judge-args") - judge.args_model.model_validate(judge_args[name]) + judges = [(judge.name, judge) for case in self.cases for judge in case.judges] result: wire.ArgsValidateResult = {} - if runner_credentials := _credentials(dataset.runner.credentials(args)): + if runner_credentials := _credentials(self.runner.credentials): result["runner_credentials"] = runner_credentials by_judge: dict[str, list[Credential]] = {} for name, judge in judges: @@ -389,11 +224,11 @@ def _validate_args( result["judge_credentials"] = judge_credentials return result - async def _seed_setup(self, ref: wire.DatasetRef, seed_ref: wire.Seed) -> wire.SeedSetupResult: + async def seed_setup(self, sent: wire.Seed) -> wire.SeedSetupResult: """Set the seed up, or load it from its own cache if it's cached.""" - key = seed_ref["key"] - seed = self._seed(ref, seed_ref["name"], key) - cached = seed_ref.get("cache", True) + key = sent["key"] + seed = self.seed(sent["name"], key) + cached = sent.get("cache", True) if cached and (handle := await _load_cached(seed, key)) is not None: return {"handle": handle, "from_cache": True} handle = await _set_up(seed) @@ -401,279 +236,103 @@ async def _seed_setup(self, ref: wire.DatasetRef, seed_ref: wire.Seed) -> wire.S try: await _call(seed.save_cached, key, handle) except Exception as exc: - print(f"saving {seed.name} to its cache: {type(exc).__name__}: {exc}", file=sys.stderr) + _warn(f"saving {seed.name} to its cache", exc) return {"handle": handle} - async def _seed_cleanup( - self, ref: wire.DatasetRef, seed_ref: wire.Seed, handle: wire.Handle - ) -> dict[str, Any]: - seed = self._seed(ref, seed_ref["name"], seed_ref["key"], cleanup=True) + async def seed_teardown(self, sent: wire.Seed, handle: wire.Handle) -> 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 seed_ref.get("cache", True): - await _call(seed.delete_cached, seed_ref["key"]) + if sent.get("cache", True): + await _call(seed.delete_cached, sent["key"]) await _clean_up(seed, handle) return {} - async def _execute( - self, ref: wire.DatasetRef, case_ref: wire.Case, ctx: Context - ) -> wire.CaseExecuteResult: - dataset = self._load(ref) - case = dataset.case(case_ref["name"]) - runner = dataset.runner - ctx.seeds = _seed_handles(case, ctx.seeds) - output = await _call(runner.execute, case, ctx) + async 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 = await _call(runner.run_case, case, seeds=seeds, conversation_id=params["conversation_id"]) + return {"output": _json_dict(output, f"{type(runner).__name__}.run_case()")} + + async def collect_cases(self, params: wire.OnlineCollectParams) -> wire.OnlineCollectResult: + since, until = datetime.fromisoformat(params["since"]), datetime.fromisoformat(params["until"]) + window = Window(since=since, until=until, limit=params["limit"]) + runner = self.with_args(self.runner, params.get("args") or {}) + what = f"{type(runner).__name__}.collect_cases()" + cases = await _call(runner.collect_cases, window) + out: list[wire.Case] = [] + for case in cases: + if len(out) >= window.limit: + break + if not isinstance(case, Case): + raise WorkerError(f"{what} must return Cases, got {type(case).__name__}") + sent: wire.Case = {"name": case.name, "input": case.input, "output": case.output} + if case.conversation_id is not None: + sent["conversation_id"] = case.conversation_id + _require_serializable(sent, what) + out.append(sent) + return {"cases": out} + + async def judge(self, params: wire.CaseJudgeParams | wire.OnlineJudgeParams) -> wire.CaseJudgeResult: + """Score the case with the judges named in params, or else its own. + 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: - output = {} - if not isinstance(output, dict): - raise WorkerError( - f"{type(runner).__name__}.execute() must return a dict, " - f"got {type(output).__name__}." - ) - _require_serializable(output, f"{type(runner).__name__}.execute()") - return {"output": output} - - async def _judge(self, ref: wire.DatasetRef, params: dict[str, Any]) -> wire.CaseJudgeResult: - dataset = self._load(ref) - case = dataset.case(params["case"]["name"]) - if judge_names := params.get("judges") or []: - judges = dataset.judges_named(judge_names) - else: - judges = [(judge.name, judge) for judge in case.judges] - seed_results = _seed_handles(case, params.get("seeds") or {}) - run = None - if conversation_id := params.get("conversation_id"): + return {"scores": []} + 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")) + 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] + judges = [(name, self.with_args(judge, judge_args.get(name) or {})) for name, judge in judges] + + result: wire.CaseJudgeResult = {} + agent_trace = params.get("trace") + if agent_trace is None and case.conversation_id: run = AgentRun( - conversation_id=conversation_id, - dataset=dataset.name, + conversation_id=case.conversation_id, + dataset=self.name, agent=params.get("agent"), case=case.name, started_at=_time(params.get("started_at")), ended_at=_time(params.get("ended_at")), ) - return await self._score( - judges, - case, - params.get("output"), - seed_results, - params.get("trace"), - run, - params.get("judge_args") or {}, - ) - - async def _online_fetch( - self, ref: wire.DatasetRef, since: str, until: str, limit: int - ) -> wire.OnlineFetchResult: - runner = self._load(ref).runner - window = (datetime.fromisoformat(since), datetime.fromisoformat(until)) - records = await _call(runner.fetch, *window, limit) - - out: list[wire.Record] = [] - for record in records: - if isinstance(record, Record): - row: wire.Record = {"id": record.id, "input": record.input, "output": record.output} - if record.conversation_id is not None: - row["conversation_id"] = record.conversation_id - elif isinstance(record, dict): - row = {"id": record["id"], "input": record.get("input") or {}, "output": record.get("output") or {}} - if record.get("conversation_id") is not None: - row["conversation_id"] = record["conversation_id"] - else: - raise WorkerError(f"{type(runner).__name__}.fetch() must yield Record, got {type(record).__name__}") - _require_serializable(row, f"{type(runner).__name__}.fetch()") - out.append(row) - if len(out) >= limit: - break - return {"records": out} - - async def _online_judge(self, ref: wire.DatasetRef, params: dict[str, Any]) -> wire.CaseJudgeResult: - dataset = self._load(ref) - judges = dataset.judges_named(params["judges"]) - record = params["record"] - # Wrapped in a case so judges cannot tell online from offline. - case = Case(name=record["id"], input=record.get("input") or {}) - run = None - if conversation_id := record.get("conversation_id"): - run = AgentRun(conversation_id=conversation_id, dataset=dataset.name, agent=params.get("agent"), case=case.name) - return await self._score( - judges, case, record.get("output"), {}, params.get("trace"), run, params.get("judge_args") or {} - ) - - async def _score( - self, - judges: Sequence[tuple[str, Judge]], - case: Case, - output: dict[str, Any] | None, - seed_results: dict[str, wire.Handle], - agent_trace: Any, - run: AgentRun | None, - judge_args: dict[str, Any], - ) -> wire.CaseJudgeResult: - """Score with each judge, passing it the --judge-args under its name. - Without the trace eac saved, the judges fetch it, and it's returned - for eac to save.""" - # A case whose execution raised has no output, and gets no scores. - if output is None: - return {"scores": []} - configured: list[tuple[str, Judge]] = [] - for name, judge in judges: - if judge.args_model is not None: - judge = copy.copy(judge) - judge.args = judge.args_model.model_validate(judge_args.get(name) or {}) - configured.append((name, judge)) - result: wire.CaseJudgeResult = {} - if agent_trace is None and run is not None: - fetched = await _fetch_trace(configured, run) - if fetched is not None: - agent_trace = fetched.trace - result["trace"] = fetched.trace + if (fetched := await _fetch_trace(judges, run)) is not None: + agent_trace = result["trace"] = fetched.trace if fetched.metrics is not None: - result["trace_metrics"] = asdict(fetched.metrics) - scores: list[wire.Score] = [] - for name, judge in configured: - score = await self._score_one( - judge, - case_output=output, - case=case, - seed_results=seed_results, - agent_trace=agent_trace, - ) - if score is not None: - scores.append(score) - result["scores"] = scores - return result + result["trace_metrics"] = dataclasses.asdict(fetched.metrics) - async def _score_one(self, judge: Judge, **inputs: Any) -> wire.Score | None: - """The judge's score, or None if it doesn't apply. A judge that raises - scores 0.""" - try: - score = await _call(judge.judge, **inputs) - 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: - return { - "name": getattr(judge, "name", type(judge).__name__), - "score": 0.0, - "label": "judge error", - "explanation": f"{type(exc).__name__}: {exc}", - } - result: wire.Score = { - "name": score.name, - "score": score.score, - "label": score.label, - "explanation": score.explanation, - "metadata": score.metadata, - } - if score.llm_judge_metrics is not None: - result["llm_judge_metrics"] = asdict(score.llm_judge_metrics) + seeds = _seed_handles(case, params.get("seeds") or {}) + scores = [await _score(judge, case, seeds, agent_trace) for _, judge in judges] + result["scores"] = [score for score in scores if score is not None] return result -def _protocol_seed(case: Case, seed: Seed) -> wire.Seed: - """A case's top-level seed as the CLI sees it, children included.""" - key = seed.key() - if not case.cache: - # A per-case key, so this case never shares a cached seed. - key = stable_hash({"key": key, "case": case.name}) - cache = case.cache and all(s.cacheable for s in walk([seed])) - out: wire.Seed = {"name": seed.name, "key": key, "cache": cache} - if credentials := _credentials(c for s in walk([seed]) for c in s.credentials): - out["credentials"] = credentials - return out - - -def _credentials(credentials: Iterable[Credential]) -> list[wire.Credential]: - """Each distinct credential as the CLI sees it, for the SDK to rebuild - from its class and fields.""" - out: dict[str, wire.Credential] = {} - for credential in credentials: - if not isinstance(credential, Credential): - raise WorkerError(f"{credential!r} isn't a Credential") - cls = type(credential) - if "" in cls.__qualname__: - raise WorkerError(f"{cls.__qualname__} must be defined at the top level of a module") - fields: dict[str, Any] = {} - if dataclasses.is_dataclass(credential): - fields = {f.name: getattr(credential, f.name) for f in dataclasses.fields(credential) if f.init} - _require_serializable(fields, f"{cls.__qualname__}'s fields") - name = getattr(credential, "name", None) - if not isinstance(name, str): - raise WorkerError(f"{cls.__qualname__} needs a name") - ref: wire.Credential = {"path": _class_ref(cls), "name": name} - if fields: - ref["fields"] = fields - if credential.setup_instructions: - ref["setup_instructions"] = credential.setup_instructions - if cls.authenticate is Credential.authenticate: - ref["manual"] = True - out.setdefault(json.dumps([ref["path"], fields], sort_keys=True), ref) - return list(out.values()) - - -def _class_ref(cls: type) -> str: - """A reference import_ref resolves to cls. A file loaded by path has no - module name to import, so it's referenced by path.""" - module = sys.modules[cls.__module__] - if cls.__module__.startswith("eac_file_"): - return f"./{os.path.relpath(module.__file__ or '')}:{cls.__qualname__}" - return f"{cls.__module__}:{cls.__qualname__}" - - -def _credential(ref: wire.Credential) -> Credential: - """Rebuild a credential the CLI sent. Lists become tuples, which frozen - dataclasses hold instead.""" - specifier, _, qualname = ref["path"].rpartition(":") - top, *nested = qualname.split(".") - cls = import_ref(f"{specifier}:{top}") - for name in nested: - cls = getattr(cls, name) - if not (isinstance(cls, type) and issubclass(cls, Credential)): - raise WorkerError(f"{ref['path']} isn't a Credential subclass") - fields = {k: tuple(v) if isinstance(v, list) else v for k, v in (ref.get("fields") or {}).items()} - try: - return cls(**fields) - except TypeError as exc: - raise WorkerError(f"can't build {ref['path']}: {exc}") from None - - -async def _check_credentials(refs: list[wire.Credential]) -> wire.CredentialsCheckResult: - """Check every credential at once. One that fails to check isn't set up.""" - env = dict(os.environ) - - async def check(ref: wire.Credential) -> bool: - try: - return bool(await _call(_credential(ref).is_authenticated, env)) - except Exception as exc: - print(f"checking {ref['name']}: {type(exc).__name__}: {exc}", file=sys.stderr) - return False - - return {"authenticated": list(await asyncio.gather(*(check(ref) for ref in refs)))} - - -async def _log_in(ref: wire.Credential) -> wire.CredentialsLoginResult: - credential = _credential(ref) - env = await _call(credential.authenticate) or {} - if not isinstance(env, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in env.items()): - raise WorkerError(f"{type(credential).__qualname__}.authenticate() must return a dict of strings") - return {"env": env} - - -async def _load_cached(seed: Seed, key: str) -> wire.Handle | None: - """The handle the seed's own cache has, or None. A cache that fails only - warns, so the seed is set up instead.""" +async def _score(judge: Judge, case: Case, seeds: dict[str, wire.Handle], agent_trace: Any) -> wire.Score | None: + """The judge's score, or None if it doesn't apply. A judge that raises + scores 0.""" try: - handle = await _call(seed.load_cached, key) + score = await _call(judge.judge, case, seeds=seeds, 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: - print(f"loading {seed.name} from its cache: {type(exc).__name__}: {exc}", file=sys.stderr) - return None - if handle is None: - return None - if not isinstance(handle, dict): - raise WorkerError(f"{type(seed).__name__}.load_cached() must return a dict or None, got {type(handle).__name__}") - _require_serializable(handle, f"{type(seed).__name__}.load_cached()") - return handle + name = getattr(judge, "name", type(judge).__name__) + return {"name": name, "score": 0.0, "explanation": f"judge error: {type(exc).__name__}: {exc}"} + result: wire.Score = { + "name": score.name, + "score": score.score, + "explanation": score.explanation, + "metadata": score.metadata, + } + if score.llm_judge_metrics is not None: + result["llm_judge_metrics"] = dataclasses.asdict(score.llm_judge_metrics) + return result async def _fetch_trace(judges: Sequence[tuple[str, Judge]], run: AgentRun) -> AgentTrace | None: @@ -685,39 +344,132 @@ async def _fetch_trace(judges: Sequence[tuple[str, Judge]], run: AgentRun) -> Ag if get is Judge.get_agent_trace or get in asked: continue asked.add(get) + what = f"{type(judge).__name__}.get_agent_trace()" try: found = await _call(judge.get_agent_trace, run) except Exception as exc: - print(f"fetching the trace of {run.case} for {name}: {type(exc).__name__}: {exc}", file=sys.stderr) + _warn(f"fetching the trace of {run.case} for {name}", exc) continue if found is None: continue if not isinstance(found, AgentTrace): - raise WorkerError( - f"{type(judge).__name__}.get_agent_trace() must return an AgentTrace or None, got {type(found).__name__}" - ) - _require_serializable(found.trace, f"{type(judge).__name__}.get_agent_trace()") + raise WorkerError(f"{what} must return an AgentTrace or None, got {type(found).__name__}") + _require_serializable(found.trace, what) return found return None -def _time(value: str | None) -> datetime | None: - return datetime.fromisoformat(value) if value else None +# Importing the user's code. + + +def import_ref(reference: str) -> Any: + """Resolve `module.path:attr`, or `./file.py:attr` relative to the cwd, + which is the project root. The CLI rewrites dataset.yml's ./file + references to be relative to the root.""" + specifier, _, attr = reference.rpartition(":") + if specifier.startswith(("./", "../")): + module = _import_file(Path(specifier)) + else: + module = importlib.import_module(specifier) + try: + return getattr(module, attr) + except AttributeError: + raise WorkerError(f"{specifier} has no {attr!r}, which is referenced as {reference}") from None + + +def _import_file(path: Path) -> ModuleType: + """Import a file by its module name under the deepest sys.path entry that + contains it, so `./evals/chat/cases.py` and `from evals.chat.cases import + ...` share one module. Files outside sys.path are loaded by path.""" + file = path.resolve() + if not file.is_file(): + raise WorkerError(f"no such file: {path}") + roots = sorted({Path(entry or ".").resolve() for entry in sys.path}, key=lambda r: len(r.parts), reverse=True) + for root in roots: + if not file.is_relative_to(root): + continue + parts = file.relative_to(root).with_suffix("").parts + if not all(part.isidentifier() for part in parts): + break + name = ".".join(parts) + module = importlib.import_module(name) + if Path(module.__file__ or "").resolve() != file: + raise WorkerError(f"{path} imports as {name}, but that name is {module.__file__}, which shadows it") + return module + + # So the file can import its neighbors by name. + if str(file.parent) not in sys.path: + sys.path.insert(0, str(file.parent)) + name = f"eac_file_{abs(hash(str(file)))}" + spec = importlib.util.spec_from_file_location(name, file) + if spec is None or spec.loader is None: + raise WorkerError(f"cannot import {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def _build(reference: str, base: type) -> Any: + """Build the referenced `base` subclass with no arguments, or return the + referenced instance.""" + target = import_ref(reference) + if isinstance(target, type) and issubclass(target, base): + try: + return target() + except TypeError as exc: + raise WorkerError(f"can't build {reference}: {exc}; reference a configured instance instead") from None + if isinstance(target, base): + return target + raise WorkerError(f"{reference} isn't a {base.__name__} subclass or instance") + + +def _import_cases(reference: str) -> list[Case]: + cases = import_ref(reference) + if isinstance(cases, (str, bytes)) or not isinstance(cases, Sequence): + raise WorkerError(f"{reference} isn't a sequence of Cases") + if bad := [c for c in cases if not isinstance(c, Case)]: + raise WorkerError(f"{reference} has a {type(bad[0]).__name__}, not a Case") + names = [case.name for case in cases] + if duplicates := sorted({name for name in names if names.count(name) > 1}): + raise WorkerError(f"{reference} has more than one case named {', '.join(duplicates)}") + return list(cases) + + +# Seeds. + + +def _seed_key(case: Case, seed: Seed) -> str: + """The seed's key, made per-case for a case that doesn't share its seeds.""" + key = seed.key() + return key if case.cache else stable_hash({"key": key, "case": case.name}) + + +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): + out["credentials"] = credentials + return out + + +async def _load_cached(seed: Seed, key: str) -> wire.Handle | None: + """The handle the seed's own cache has, or None. A cache that fails only + warns, so the seed is set up instead.""" + try: + handle = await _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()") async def _set_up(seed: Seed) -> wire.Handle: """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 = await _call(seed.setup) - if handle is None: - handle = {} - if not isinstance(handle, dict): - raise WorkerError( - f"{type(seed).__name__}.setup() must return a dict, got {type(handle).__name__}. " - f"The handle is written to seeds.json and read back by a later phase." - ) - _require_serializable(handle, f"{type(seed).__name__}.setup()") + handle = _json_dict(await _call(seed.setup), f"{type(seed).__name__}.setup()") if not seed.children: return handle @@ -731,7 +483,7 @@ async def _set_up(seed: Seed) -> wire.Handle: try: await _clean_up(seed, tree) except Exception as exc: - print(f"cleaning up {seed.name} after its setup failed: {exc}", file=sys.stderr) + _warn(f"cleaning up {seed.name} after its setup failed", exc) raise return tree @@ -741,8 +493,7 @@ async def _clean_up(seed: Seed, handle: wire.Handle) -> None: if seed.children: tree, handle = handle, handle["handle"] children = tree["children"] - unknown = set(children) - {child.name for child in seed.children} - if unknown: + 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" @@ -775,6 +526,108 @@ def add(seed: Seed, handle: wire.Handle) -> None: return out +# Credentials. + + +def _credentials(credentials: Iterable[Credential]) -> list[wire.Credential]: + """Each distinct credential as the CLI sees it, for the SDK to rebuild + from its class and fields.""" + out: dict[str, wire.Credential] = {} + for credential in credentials: + if not isinstance(credential, Credential): + raise WorkerError(f"{credential!r} isn't a Credential") + cls = type(credential) + if "" in cls.__qualname__: + raise WorkerError(f"{cls.__qualname__} must be defined at the top level of a module") + fields: dict[str, Any] = {} + if dataclasses.is_dataclass(credential): + fields = {f.name: getattr(credential, f.name) for f in dataclasses.fields(credential) if f.init} + _require_serializable(fields, f"{cls.__qualname__}'s fields") + name = getattr(credential, "name", None) + if not isinstance(name, str): + raise WorkerError(f"{cls.__qualname__} needs a name") + sent: wire.Credential = {"path": _class_ref(cls), "name": name} + if fields: + sent["fields"] = fields + if credential.setup_instructions: + sent["setup_instructions"] = credential.setup_instructions + if cls.authenticate is Credential.authenticate: + sent["manual"] = True + out.setdefault(json.dumps([sent["path"], fields], sort_keys=True), sent) + return list(out.values()) + + +def _class_ref(cls: type) -> str: + """A reference import_ref resolves to cls. A file loaded by path has no + module name to import, so it's referenced by path.""" + module = sys.modules[cls.__module__] + if cls.__module__.startswith("eac_file_"): + return f"./{os.path.relpath(module.__file__ or '')}:{cls.__qualname__}" + return f"{cls.__module__}:{cls.__qualname__}" + + +def _credential(sent: wire.Credential) -> Credential: + """Rebuild a credential the CLI sent. Lists become tuples, which frozen + dataclasses hold instead.""" + specifier, _, qualname = sent["path"].rpartition(":") + top, *nested = qualname.split(".") + cls = import_ref(f"{specifier}:{top}") + for name in nested: + cls = getattr(cls, name) + if not (isinstance(cls, type) and issubclass(cls, Credential)): + raise WorkerError(f"{sent['path']} isn't a Credential subclass") + fields = {k: tuple(v) if isinstance(v, list) else v for k, v in (sent.get("fields") or {}).items()} + try: + return cls(**fields) + except TypeError as exc: + raise WorkerError(f"can't build {sent['path']}: {exc}") from None + + +async def _check_credentials(sent: list[wire.Credential]) -> wire.CredentialsCheckResult: + """Check every credential at once. One that fails to check isn't set up.""" + env = dict(os.environ) + + async def check(credential: wire.Credential) -> bool: + try: + return bool(await _call(_credential(credential).is_authenticated, env)) + except Exception as exc: + _warn(f"checking {credential['name']}", exc) + return False + + return {"authenticated": list(await asyncio.gather(*(check(c) for c in sent)))} + + +async def _log_in(sent: wire.Credential) -> wire.CredentialsLoginResult: + credential = _credential(sent) + env = await _call(credential.authenticate) or {} + if not isinstance(env, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in env.items()): + raise WorkerError(f"{type(credential).__qualname__}.authenticate() must return a dict of strings") + return {"env": env} + + +# Helpers. + + +async def _call(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + """Run a coroutine function on the worker's event loop and anything else + in a thread, so sync user code can block or call asyncio.run().""" + if inspect.iscoroutinefunction(fn): + return await fn(*args, **kwargs) + result = await asyncio.to_thread(fn, *args, **kwargs) + return await result if inspect.isawaitable(result) else result + + +def _json_dict(value: Any, what: str) -> dict[str, Any]: + """What user code returned, as a dict that can be saved for a later + phase. None reads as an empty dict.""" + if value is None: + return {} + if not isinstance(value, dict): + raise WorkerError(f"{what} must return a dict, got {type(value).__name__}") + _require_serializable(value, what) + return value + + def _require_serializable(value: Any, what: str) -> None: try: json.dumps(value) @@ -785,15 +638,22 @@ def _require_serializable(value: Any, what: str) -> None: ) from None -async def run(server: Callable[[asyncio.StreamReader, BinaryIO], Server]) -> None: +def _time(value: str | None) -> datetime | None: + return datetime.fromisoformat(value) if value else None + + +def _warn(doing: str, exc: Exception) -> None: + print(f"{doing}: {type(exc).__name__}: {exc}", file=sys.stderr) + + +async def run() -> None: """Serve the CLI on fd 3 and fd 4 until it closes fd 3.""" reader = asyncio.StreamReader(limit=STREAM_LIMIT) loop = asyncio.get_running_loop() - await loop.connect_read_pipe( - lambda: asyncio.StreamReaderProtocol(reader), os.fdopen(REQUEST_FD, "rb", buffering=0) - ) + requests = os.fdopen(REQUEST_FD, "rb", buffering=0) + await loop.connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), requests) with os.fdopen(RESPONSE_FD, "wb") as out: - await server(reader, out).serve() + await Worker(reader, out).serve() def main() -> None: @@ -801,7 +661,7 @@ def main() -> None: print("eac.worker must be started by the eac CLI", file=sys.stderr) raise SystemExit(2) try: - asyncio.run(run(Worker)) + asyncio.run(run()) except KeyboardInterrupt: pass