Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
258 changes: 250 additions & 8 deletions core/Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ dotenvy = { git = "https://github.com/allan2/dotenvy", rev = "cf125ddeb263c234ad
humantime = "2"
libc = "0.2"
schemars = { version = "1", features = ["chrono04"] }
semver = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_yaml = "0.9"
tempfile = "3"
# For the notice when a newer release is out.
ureq = { version = "3", default-features = false, features = ["rustls"] }
uuid = { version = "1", features = ["v4"] }
which = "8"
8 changes: 4 additions & 4 deletions core/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ eac writes requests to the process's **fd 3** and reads responses from its **fd

**Ready line.**

The first line a process writes to fd 4 is its ready line, which says which protocol version it speaks. After that, every line is the response to the request eac just sent, carrying that request's `id`. eac stops with an error on any other line.
The first line a process writes to fd 4 is its ready line, which says which protocol version it speaks. It can also give the SDK's language and version, so eac can say when a newer release is out. After that, every line is the response to the request eac just sent, carrying that request's `id`. eac stops with an error on any other line.

```jsonc
{"protocol": 1} // ready line
{"id": 1, "method": "discover", "params": {...}} // request
{"id": 1, "result": {...}} // response
{"protocol": 1, "sdk": {"language": "Python", "version": "0.0.1"}} // ready line
{"id": 1, "method": "discover", "params": {...}} // request
{"id": 1, "result": {...}} // response
{"id": 1, "error": {"message": "...", "traceback": "..."}}
```

Expand Down
17 changes: 16 additions & 1 deletion core/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod cli;
mod commands;
mod eac;
mod schema;
mod update;
mod worker;

use std::process::ExitCode;
Expand All @@ -15,7 +16,21 @@ use cli::Cli;
use commands::FailedRun;

fn main() -> ExitCode {
let args = Cli::parse();
let update = update::start();
let code = run();
update::finish(update);
code
}

fn run() -> ExitCode {
let args = match Cli::try_parse() {
Ok(args) => args,
// --help, --version or a usage error.
Err(e) => {
let _ = e.print();
return ExitCode::from(e.exit_code() as u8);
}
};
let _ = ctrlc::set_handler(worker::interrupt);
match cli::dispatch(args.command) {
Ok(()) => ExitCode::SUCCESS,
Expand Down
10 changes: 10 additions & 0 deletions core/src/schema/framing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,14 @@ impl std::error::Error for Error {}
pub struct Ready {
#[schemars(extend("const" = VERSION))]
pub protocol: i64,
#[serde(default)]
pub sdk: Option<Sdk>,
}

/// The SDK package a worker runs on.
#[derive(Deserialize, JsonSchema)]
pub struct Sdk {
/// As shown to users, e.g. "Python".
pub language: String,
pub version: String,
}
27 changes: 27 additions & 0 deletions core/src/schema/protocol.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,16 @@
"properties": {
"protocol": {
"const": 1
},
"sdk": {
"anyOf": [
{
"$ref": "#/$defs/Sdk"
},
{
"type": "null"
}
]
}
},
"required": [
Expand Down Expand Up @@ -623,6 +633,23 @@
],
"type": "object"
},
"Sdk": {
"description": "The SDK package a worker runs on.",
"properties": {
"language": {
"description": "As shown to users, e.g. \"Python\".",
"type": "string"
},
"version": {
"type": "string"
}
},
"required": [
"language",
"version"
],
"type": "object"
},
"Seed": {
"description": "A fixture. Seeds with the same `key`, a content hash, are set up once and shared.",
"properties": {
Expand Down
104 changes: 104 additions & 0 deletions core/src/update.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
//! Says when a newer eac release is out than the CLI or an SDK a worker ran
//! on. The latest release is looked up on a thread while the command runs, and
//! only reported if the lookup finished by the end. Skipped in CI, when stderr
//! isn't a terminal, or with EAC_NO_UPDATE_CHECK set.

use std::collections::BTreeMap;
use std::io::IsTerminal;
use std::sync::mpsc::{self, Receiver};
use std::sync::Mutex;
use std::thread;

use semver::Version;

use crate::schema::Sdk;

/// Redirects to the latest release's page, /releases/tag/<version>.
const LATEST: &str = "https://github.com/getsentry/eac/releases/latest";

/// Each SDK version workers reported, by language.
static SDKS: Mutex<BTreeMap<String, String>> = Mutex::new(BTreeMap::new());

/// Notes the SDK a worker runs on, from its ready line.
pub fn saw_sdk(sdk: &Sdk) {
let mut sdks = SDKS.lock().unwrap_or_else(|e| e.into_inner());
sdks.insert(sdk.language.clone(), sdk.version.clone());
}

/// Starts looking up the latest release's version.
pub fn start() -> Option<Receiver<Version>> {
let set = |name| std::env::var_os(name).is_some_and(|v| !v.is_empty());
if set("EAC_NO_UPDATE_CHECK") || set("CI") || !std::io::stderr().is_terminal() {
return None;
}
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
if let Some(version) = latest() {
let _ = tx.send(version);
}
});
Some(rx)
}

/// Prints what's older than the latest release, if the lookup has finished.
pub fn finish(latest: Option<Receiver<Version>>) {
let Some(latest) = latest.and_then(|rx| rx.try_recv().ok()) else { return };
let sdks = SDKS.lock().unwrap_or_else(|e| e.into_inner()).clone();
let outdated = outdated(&latest, env!("CARGO_PKG_VERSION"), &sdks);
if outdated.is_empty() {
return;
}
eprintln!();
warning!("There's a new version of eac:");
for line in outdated {
warning!(" {line}");
}
detail!("{LATEST}");
}

fn latest() -> Option<Version> {
let agent: ureq::Agent = ureq::Agent::config_builder().max_redirects(0).build().into();
let response = agent.head(LATEST).call().ok()?;
let location = response.headers().get("location")?.to_str().ok()?;
let (_, tag) = location.rsplit_once("/tag/")?;
Version::parse(tag.trim_start_matches('v')).ok()
}

/// A line for the CLI and each SDK older than latest.
fn outdated(latest: &Version, cli: &str, sdks: &BTreeMap<String, String>) -> Vec<String> {
let older = |version: &str| Version::parse(version).is_ok_and(|v| v < *latest);
let mut lines = Vec::new();
if older(cli) {
lines.push(format!("CLI {latest} is out, you are using {cli}"));
}
for (language, version) in sdks {
if older(version) {
lines.push(format!("{language} SDK {latest} is out, you are using {version}"));
}
}
lines
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn a_line_for_whatever_is_older() {
let latest = Version::new(0, 2, 0);
let sdks = BTreeMap::from([("Python".to_string(), "0.1.0".to_string())]);
assert_eq!(
outdated(&latest, "0.1.0", &sdks),
[
"CLI 0.2.0 is out, you are using 0.1.0",
"Python SDK 0.2.0 is out, you are using 0.1.0",
]
);
// Up to date, or a build from main ahead of the release.
assert_eq!(
outdated(&latest, "0.2.0", &sdks),
["Python SDK 0.2.0 is out, you are using 0.1.0"]
);
assert!(outdated(&latest, "0.3.0", &BTreeMap::new()).is_empty());
}
}
7 changes: 6 additions & 1 deletion core/src/worker/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl Worker {
Ok(worker)
}

/// Waits for the ready line and checks its protocol version.
/// Waits for the ready line, checks its protocol version and notes its SDK.
fn ready(&self) -> Result<()> {
let ready = match self.responses.next_line() {
Ok(line) => line.and_then(|l| serde_json::from_str::<Ready>(&l).ok()),
Expand All @@ -71,6 +71,11 @@ impl Worker {
let Some(ready) = ready else {
bail!("{} exited before it was ready; see its output above", self.label);
};
// Before the protocol check, since an SDK on another protocol most
// needs the notice that a newer release is out.
if let Some(sdk) = &ready.sdk {
crate::update::saw_sdk(sdk);
}
if ready.protocol != VERSION {
bail!(
"{} speaks protocol v{}, CLI speaks v{VERSION}: upgrade it",
Expand Down
4 changes: 4 additions & 0 deletions docs/app/cli/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,7 @@ Run `eac --help` any time for the full list.
## Exit codes

`0` means no case failed or errored, `1` means one did, and `2` means eac itself hit a problem. `eac --version` prints the version.

## Updates

When a newer eac release is out than your CLI or the SDK your evals run on, eac says so after a command's output. It looks up the latest [GitHub release](https://github.com/getsentry/eac/releases). `EAC_NO_UPDATE_CHECK=1` turns this check off.
2 changes: 1 addition & 1 deletion docs/app/protocol/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ You only need this page if you're adding support for a new language. If you just
eac starts a worker process for your language and talks to it with JSON, one message per line:

- Requests come in on **fd 3** and responses go out on **fd 4**, so stdout and stderr stay free for logs.
- The worker's first line says which protocol it speaks: `{"protocol": 1}`.
- The worker's first line says which protocol it speaks, and optionally its SDK's language and version, so eac can tell users when it's out of date: `{"protocol": 1, "sdk": {"language": "Python", "version": "0.0.1"}}`.
- eac sends one request at a time and waits for the answer.
- When eac closes fd 3, the worker should exit.

Expand Down
9 changes: 9 additions & 0 deletions sdks/python/eac/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ class Ready(TypedDict):
"""The first line a worker sends."""

protocol: Literal[1]
sdk: NotRequired[Sdk | None]


class Request(TypedDict):
Expand All @@ -237,6 +238,14 @@ class Score(TypedDict):
score: NotRequired[float | None]


class Sdk(TypedDict):
"""The SDK package a worker runs on."""

#: As shown to users, e.g. "Python".
language: str
version: str


class Seed(TypedDict):
"""A fixture. Seeds with the same `key`, a content hash, are set up once and shared.
"""
Expand Down
3 changes: 2 additions & 1 deletion sdks/python/eac/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from typing import Any, BinaryIO, Callable, Iterable, Sequence, cast

from eac import protocol as wire
from eac._version import __version__
from eac.credential import Credential
from eac.judge import Judge
from eac.models import AgentRun, AgentTrace, Case, LLMMetrics, Score, Window, stable_hash
Expand All @@ -46,7 +47,7 @@ def __init__(self, requests: BinaryIO, out: BinaryIO):
self._datasets: dict[str, LoadedDataset] = {}

def serve(self) -> None:
self._send({"protocol": wire.PROTOCOL_VERSION})
self._send({"protocol": wire.PROTOCOL_VERSION, "sdk": {"language": "Python", "version": __version__}})
for line in self._requests:
self._respond(line)

Expand Down
Loading