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
141 changes: 141 additions & 0 deletions benchmarking/evaluate/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Run evaluations

`evaluate` judges a finished benchmark run against CEL conditions declared in
its test entry, and returns the verdicts as a `Report`.
Depends on [`cel-expr-python`](https://github.com/cel-expr/cel-python) and
[pydantic](https://docs.pydantic.dev/) (`requirements.txt`, Python 3.11 or later).

## Model

- A **source** reads the run and returns several named **values**, or
says it can't judge the run (`invalid`, with a reason). Sources:
`run_results`.
- A **variable** is one source query: `{name, source, source_cfg}`. Its values
are exposed to CEL as a map under `<variable>` (`<variable>.<value>`, or
`<variable>["<value>"]` when `<value>` contains dots or CEL keywords).
- A **condition** is `{name, cel}`: a [CEL](https://cel.dev/) boolean
expression over the variables.
- An **evaluation** is a named set of variables and conditions, AND-ed: it
`fail`s if any condition failed, else is `invalid` if any condition or
variable is invalid, else `pass`es. Evaluations are judged independently, with no hierarchy between
them.
- The run's **summary** combines its evaluations the same way.
- `passed` is true for `pass` only, and false for both `fail` and `invalid`,
so an alert should key on `passed`.

## Config

Evaluations live in the test entry, next to the test they judge. This one
checks two envelope health gates:

```yaml
- name: sweperf_150u_c3hc192metal_microvm
# ...
evaluations:
- name: envelope_health
description: "Failure ratio and worker memory within the scalability envelope"
variables:
- name: trial
source: run_results
source_cfg: {metric: trial_summary, measurements: [aggregate_failure_ratio, allocatable_ram_gb]}
- name: server
source: run_results
source_cfg: {metric: server_summary, measurements: [working_set_node_max_gb]}
conditions:
- {name: failure_rate, cel: "trial.aggregate_failure_ratio <= 0.001"}
- {name: worker_memory, cel: "server.working_set_node_max_gb < 0.85 * trial.allocatable_ram_gb"}
```

- Evaluation, variable and condition names match `^[a-z][a-z0-9_]*$`, at most
64 characters, and are unique where they live. CEL itself rejects a
variable named after a CEL type (`int`, `map`) or a keyword (`in`, `true`)
when a condition compiles. Value names come from the source
and may be any non-empty string
(`locust_ResumeActor`, `metric_nighthawk.builtin_attempted_rps`, `p99.9`).
Unknown or non-string mapping keys are errors, and `source_cfg` holds JSON
values only, so a YAML date in it is an error too. There is no version field
while the schema is experimental.
- Conditions are standard CEL, compiled when the evaluations load, with
`round(x, digits)` added. Each must evaluate to `bool`: a bare value such as
`trial.ok` compiles, and a result that isn't a bool makes the condition `invalid`.
- Values enter CEL as doubles, whatever number type the source returns,
since they come from JSON, which has one number type, and as ints `a / b`
would be integer division. The results keep the source's own value types.
CEL has no arithmetic between int and double, so write `2.0 * t.x`, not
`2 * t.x`; the same goes for comparing a double expression
(`round(t.x, 1) >= 90.0`). A value compared directly may use an int
literal (`t.x <= 1500`). Mixing int and double fails when the evaluations
load if CEL can see both types; otherwise (`t.x * 100 >= 99`, where
`t.x` is only known at run time) the condition is `invalid` on every run,
so it never passes.
- Missing or null values are omitted from `<variable>`'s map: reading one
directly fails lookup and makes the condition `invalid`, while
`has(<variable>.<key>)` returns `false` without error. A value CEL can't
hold makes the conditions `invalid`. An `invalid` variable is left out of
the CEL data, so a condition that reads it is `invalid` with CEL's error,
and the evaluation is `invalid` even if no condition reads it: a source
failure never lets an evaluation pass.
- CEL `==` and `!=` across distinct dynamic types (`1.1 == "1.10"`,
`true == 1.0`) evaluate to `false` and `true` without raising an error. Float
division inside a condition follows IEEE-754 (`1.0 / 0.0` produces `+Inf`
and `0.0 / 0.0` produces `NaN`).

## Sources

A source is a class with three hooks (`sources/base.py`):

| hook | runs | does |
|---|---|---|
| `validate(cfg)`, a classmethod | when the evaluations are loaded | raises `ValueError` for a bad `source_cfg` |
| `init(run)` | once, when the run starts (its files may not exist yet) | takes the `BenchmarkRunContext`, the run being evaluated: which run it is (`identity`: `uri`, and `test_name`, `tag`, `run_date`, `run_ts` when known), where it is stored, and its stored artifacts (`artifact(name)`, a local path or None); the source chooses what it reads |
| `query(cfg)` | after the run, once per distinct `source_cfg` | returns named values (numbers, bools, strings or null), or raises `SourceInvalid(reason, values)` when it can't judge the run |

Value names come from `source_cfg` or are fixed by the source, never from the
run's data. The evaluator creates one instance of each source the evaluations
name. The values of a `SourceInvalid` are kept in the results, while the
variable and the conditions reading it become `invalid`. Any other exception
from a hook makes the source's variables `invalid` with the error, and so does
a value of another type, such as a list or a mapping, or a value name that
isn't a non-empty string. Sources never write files. A new source is a class
in `sources/` and a line in `SOURCES`.

### `run_results`

The measurements of one `stats.jsonl` row:

```yaml
source_cfg:
metric: trial_summary # if repeated, the last row wins
measurements: [aggregate_failure_ratio] # returned under the same names
```

Numeric strings without `_` become floats and `"true"`/`"false"` bools. Strings
with `_` (`"2026_11"`) stay strings. A measurement the row lacks, or a number
that isn't finite (NaN, an infinity, `1e999`), is null. Blank lines are skipped;
any other line that isn't a JSON object with a `metric` makes the variable
`invalid`, naming the line, since the runner writes one such object per line.

## Results

`Evaluator.evaluate` returns a `Report` (`evaluator.py`): the run, the
`summary` (`status`, `passed`, `failed`, `invalid`), and per evaluation its
status and reason, each condition with its CEL expression and verdict, each
variable with its values (and why it is invalid), and the evaluation as loaded
(`config`). An evaluation's reason names the conditions that failed, else the
invalid conditions and variables.

## Layout

| file | |
|---|---|
| `config.py` | loads and validates an `evaluations` block (pydantic models) |
| `cel_env.py` | shared CEL environment, `round()`, and evaluation |
| `evaluator.py` | runs the source hooks and judges a run into a `Report` |
| `sources/` | the hooks (`base.py`) and the sources |

## Tests

```sh
hack/verify/benchmarking-python.sh # as CI runs them; or, with requirements.txt installed:
cd benchmarking/evaluate && python3 -m unittest discover -s unit_tests
```
21 changes: 21 additions & 0 deletions benchmarking/evaluate/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Copyright 2026 The Agent Substrate Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Run evaluations: judge a finished benchmark run against conditions declared in its test entry.

A test entry's `evaluations:` (config.py) name sources, which read the run's
files into values (sources/), and CEL conditions over those values
(cel_env.py). evaluator.py judges them into a Report. Depends on
cel-expr-python and pydantic (requirements.txt). See README.md.
"""
77 changes: 77 additions & 0 deletions benchmarking/evaluate/cel_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Copyright 2026 The Agent Substrate Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Shared CEL environment, round(), and evaluation."""

from typing import Any, Mapping

from cel_expr_python import cel


def _round(x: float, digits: float) -> float:
if not float(digits).is_integer():
raise ValueError(f"round: digits {digits} isn't a whole number")
return round(x, int(digits))


# round(x, digits) as Python rounds, so an expression can keep a fixed number of decimals.
ROUND = cel.FunctionDecl("round", [
cel.Overload(f"round_double_{t.name().lower()}", return_type=cel.Type.DOUBLE, parameters=[cel.Type.DOUBLE, t],
impl=_round) for t in (cel.Type.DOUBLE, cel.Type.INT)])


def to_cel(values: Mapping[str, Any]) -> dict[str, Any]:
"""values as CEL reads them: ints as doubles, and no key for None, so has()
tests presence. Source values come from JSON, which has one number type, and
as ints `a / b` would be integer division."""
return {k: float(v) if isinstance(v, int) and not isinstance(v, bool) else v
for k, v in values.items() if v is not None}


def evaluate_condition(expr: cel.Expression, data: Mapping[str, Any]) -> bool:
"""Whether the boolean expr is true for data. Raises ValueError with CEL's
error when it fails to evaluate, for example on a key data lacks or a value
CEL can't hold."""
try:
result = expr.eval(data=data)
except RuntimeError as e: # a value CEL can't take in, such as a string with a lone surrogate
raise ValueError(str(e)) from None
if result.type() == cel.Type.ERROR:
raise ValueError(str(result.value()))
if result.type() != cel.Type.BOOL:
raise ValueError(f"gives a {result.type().name().lower()}, not a bool")
return result.value()


class Env:
"""A CEL environment with variables and functions."""

def __init__(self, variables: Mapping[str, cel.Type], functions: tuple[cel.FunctionDecl, ...] = ()):
self.variables = dict(variables)
try:
self.env = cel.NewEnv(variables=self.variables, functions=list(functions))
except RuntimeError as e:
raise ValueError(str(e)) from None

def compile(self, expression: str, where: str,
gives: tuple[cel.Type, ...] = (cel.Type.BOOL,)) -> cel.Expression:
"""expression compiled. Raises ValueError unless it type-checks and gives one of gives."""
try:
expr = self.env.compile(expression)
except RuntimeError as e: # a syntax or type error, or a variable CEL already declares
raise ValueError(f"{where}: {e}") from None
if expr.return_type() not in gives:
Comment thread
roycaihw marked this conversation as resolved.
Resolved
wanted = " or a ".join(t.name().lower() for t in gives if t != cel.Type.DYN)
raise ValueError(f"{where}: must give a {wanted}, gives {expr.return_type().name()}")
return expr
124 changes: 124 additions & 0 deletions benchmarking/evaluate/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Copyright 2026 The Agent Substrate Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""The `evaluations:` block of a test entry: loading and validation.

evaluations:
- name: envelope_health # unique in the test
description: "..." # optional
variables: # each is one source query, with several named values
- {name: trial, source: run_results, source_cfg: {...}}
conditions: # AND-ed
- {name: failure_ratio, cel: "trial.aggregate_failure_ratio <= 0.001"}

The models below give the shape. Loading also checks what a shape can't: that
names are unique, each variable's source_cfg (by its source's validate hook),
and that each condition compiles, so a bad config fails before a run is read.
There is no version field while the schema is experimental.
"""

from typing import Annotated, Any

from cel_expr_python import cel
from pydantic import Field, JsonValue, PrivateAttr, TypeAdapter, ValidationError, field_validator, model_validator

from . import cel_env
from .sources import SOURCES
from .sources.base import Model, Name, describe

CelExpression = cel.Expression


class ConfigError(ValueError):
"""The evaluations block is invalid; the message names where."""


class Variable(Model):
name: Name
source: str
# JSON, as the results echo it: a YAML date or a non-string key is an error here.
# Validation builds new containers, so later edits to the input don't reach it.
source_cfg: dict[str, JsonValue] = {}

@field_validator("source")
@classmethod
def _known(cls, source: str) -> str:
if source not in SOURCES:
raise ValueError(f"source {source!r} is not one of {sorted(SOURCES)}")
return source

@model_validator(mode="after")
def _source_cfg(self) -> "Variable":
try:
SOURCES[self.source].validate(self.source_cfg)
except ValueError as e:
raise ValueError(f"source_cfg: {e}") from None
return self


class Condition(Model):
name: Name
cel: str
_expr: CelExpression = PrivateAttr() # compiled by the Evaluation, which knows the variables

@property
def expr(self) -> CelExpression:
return self._expr


class Evaluation(Model):
name: Name
description: str = ""
# Lists, not tuples: pydantic counts a tuple's length after dropping the items that failed,
# so one bad item would also report the tuple as empty.
variables: list[Variable] = Field(min_length=1)
conditions: list[Condition] = Field(min_length=1)

@model_validator(mode="after")
def _compile(self) -> "Evaluation":
_unique([v.name for v in self.variables], "variable")
_unique([c.name for c in self.conditions], "condition")
env = cel_env.Env({v.name: cel.Type.Map(cel.Type.STRING, cel.Type.DYN) for v in self.variables},
functions=(cel_env.ROUND,))
for c in self.conditions:
# DYN too, as when a condition is just a value (`trial.ok`); a non-bool
# result then makes the condition invalid when it runs.
c._expr = env.compile(c.cel, f"condition {c.name!r}: cel", # pylint: disable=protected-access
gives=(cel.Type.BOOL, cel.Type.DYN))
return self


_EVALUATIONS = TypeAdapter(Annotated[list[Evaluation], Field(min_length=1)])


def load(evaluations: Any) -> list[Evaluation]:
"""The evaluations of a test entry, validated; raises ConfigError."""
try:
out = _EVALUATIONS.validate_python(evaluations)
_unique([e.name for e in out], "evaluation")
except ValidationError as e:
raise ConfigError(f"evaluations: {describe(e)}") from None
except ValueError as e:
raise ConfigError(f"evaluations: {e}") from None
return out


def to_json(evaluations: list[Evaluation]) -> list[dict[str, Any]]:
"""The evaluations as loaded, defaults filled: what the results echo, and load() reads back."""
return [e.model_dump(mode="json") for e in evaluations]


def _unique(names: list[str], what: str) -> None:
if dupes := sorted({n for n in names if names.count(n) > 1}):
raise ValueError(f"{what} names repeated: {dupes}")
Loading
Loading