Skip to content
Open
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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ internal/ Private implementation — never import from outside the mod
skill/ Install Skill files into Engine's conventional path (excluding evals/)
evaluator/ Evaluator: iterates cases, calls agent.Run, returns CaseResult
evalevent/ Internal evaluation event model, publisher, lifecycle, and JSONL sink
measurement/ Validation and stored form of engine-reported runtime measurements
judge/ Judges: rule_based, script, agent_judge
report/ Report generators: JSON / JUnit / HTML / Anthropic grading & benchmark
runner/ End-to-end orchestration for `skill-up run`
Expand Down
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Custom engines can report runtime measurements that the fixed `SessionResult`
fields cannot carry, such as decode speed at given context lengths or time to
first token. An optional `measurements` object holds named `scalars` and
`series`, each with a unit, on both the `local` and `http` transports. skill-up
validates and masks it, then writes it to `result.json` and `report.json` as
`engine_measurements`: on the case for a single-turn case, and on each turn for
a multi-turn one. A value that could not be measured stays `MISSING` with its
reason; nothing is truncated or stored as `0`. Measurements are informational.
They never change a verdict, a pass rate or the benchmark, and an invalid
object or entry is listed in `engine_measurement_diagnostics` instead of
failing the case. Results without measurements are unchanged. See the
Measurements contract in `docs/design/custom-engine.md`.

- A mocked MCP tool in a fixture's `tools` map can return a failed tool call.
`is_error: true` sends the tool's `response` with MCP's `isError: true`, so
a case can check how a Skill handles a tool that ran and failed. The field
Expand Down
6 changes: 6 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ skill-up/
│ ├── runtime/ # Eval runtime: none / opensandbox
│ ├── agent/ # Agent Engine adapters (claude_code, codex, custom)
│ ├── evalevent/ # Internal evaluation event protocol and JSONL publisher
│ ├── measurement/ # Validation of engine-reported runtime measurements
│ ├── judge/ # Evaluators: rule_based, agent_judge, script
│ ├── report/ # Report output: JSON, JUnit, HTML
│ ├── runner/ # End-to-end orchestration (config → environment → cases → report)
Expand Down Expand Up @@ -129,6 +130,11 @@ skill-up/
- **Meaning**: Defines the internal typed evaluation event envelope and payloads, invocation lifecycle state, publisher, and JSONL sink. It is not a public stable API.
- **Relation to design**: Implements the producer-side protocol defined by SUP-0005 without coupling it to CLI, runner, evaluator, report, or UI packages.

### `internal/measurement/`

- **Meaning**: Strictly validates the optional `measurements` object of a custom engine's `SessionResult` and defines the form stored in `result.json`: named scalars and series with units, plus a diagnostic for every rejection. It depends on no other internal package.
- **Relation to design**: Implements the Measurements contract in `docs/design/custom-engine.md`. Measurements are informational and never reach grading.

### `internal/judge/`

- **Meaning**: Performs evaluation on top of Engine output: `rule_based`, `agent_judge`, `script`, producing results aligned with `grading.json`.
Expand Down
322 changes: 322 additions & 0 deletions docs/design/custom-engine.md

Large diffs are not rendered by default.

39 changes: 39 additions & 0 deletions docs/guide/writing-evals.md
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,45 @@ HTTP specifics:
- Credentials must be referenced from `headers` (or `request_body`), never from `http.url` — a URL that renders `${api_key}` is rejected to keep the key out of request logs.
- A non-2xx response is treated as an invocation error. Artifacts the agent returns under `artifacts.files[].url` are GET-downloaded (http/https only, no redirects, size/time bounded) into the report directory.

**Reporting runtime measurements.** With `response_format: session_result`, the
`SessionResult` may carry an optional `measurements` object for numbers the fixed
fields cannot hold, such as decode speed at given context lengths or time to first
token. Every value has a name and a unit. Both transports accept it:

```json
{
"exit_code": 0,
"final_message": "Decay sweep finished.",
"measurements": {
"schema_version": 1,
"provenance": {"producer": "dsh-eval-harness", "producer_version": "e90c255"},
"scalars": [
{"id": "half_speed_context", "unit": "token", "value": 67000}
],
"series": [
{
"id": "decode_tps",
"unit": "tok/s",
"axis": {"id": "requested_context_tokens", "unit": "token"},
"points": [
{"at": 8192, "value": 178.2},
{"at": 131072, "value": 67.7},
{"at": 262144, "availability": "MISSING", "reason": "request_timed_out"}
]
}
]
}
}
```

- `scalars` entries hold one value each. `series` entries hold ordered points along a declared `axis`; `at` must increase from one point to the next.
- A value that could not be measured is reported as `"availability": "MISSING"` with a `reason` code. It is never stored as `0`.
- skill-up validates the object and writes it to `result.json` and `report.json` as `engine_measurements`: on the case for a single-turn case, and on each turn for a multi-turn one. Whatever it rejects is listed in `engine_measurement_diagnostics`.
- Measurements are informational. They never change PASS/FAIL, pass rates or the benchmark, and an invalid `measurements` object never fails the case.
- JSON cannot express `NaN` or `Infinity`. A serializer that writes them as bare tokens (Python's `json.dumps` does by default) makes the whole `SessionResult` unparseable, and the case then errors. Serialize with `allow_nan=False` and report such a value as `MISSING`.

The field rules, unit spellings, size limits and diagnostic codes are in the [Measurements contract](../design/custom-engine.md#measurements-contract).

See `docs/design/custom-engine.md` for the full SessionInput / SessionResult schema your agent must conform to.

### MCP configuration
Expand Down
38 changes: 38 additions & 0 deletions docs/zh/guide/writing-evals.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,44 @@ HTTP 要点:
- 凭据必须从 `headers`(或 `request_body`)引用,不能写进 `http.url` —— URL 渲染出 `${api_key}` 会被拒绝,避免泄漏到请求日志。
- 非 2xx 响应按调用错误处理。Agent 在 `artifacts.files[].url` 返回的产物会被 GET 下载(仅 http/https、不跟随重定向、有大小与时间上限)到报告目录。

**上报运行时测量值。** `response_format: session_result` 时,`SessionResult` 可以带一个
可选的 `measurements` 对象,用来上报固定字段放不下的数值,比如各个上下文长度下的解码
速度、首 token 时间。每个值都有名字和单位。local 和 http 两种传输都支持:

```json
{
"exit_code": 0,
"final_message": "Decay sweep finished.",
"measurements": {
"schema_version": 1,
"provenance": {"producer": "dsh-eval-harness", "producer_version": "e90c255"},
"scalars": [
{"id": "half_speed_context", "unit": "token", "value": 67000}
],
"series": [
{
"id": "decode_tps",
"unit": "tok/s",
"axis": {"id": "requested_context_tokens", "unit": "token"},
"points": [
{"at": 8192, "value": 178.2},
{"at": 131072, "value": 67.7},
{"at": 262144, "availability": "MISSING", "reason": "request_timed_out"}
]
}
]
}
}
```

- `scalars` 里每个条目是一个值。`series` 里每个条目是沿着所声明的 `axis` 排列的一串点,`at` 必须逐点递增。
- 没测到的值用 `"availability": "MISSING"` 加一个 `reason` 码上报,不会被存成 `0`。
- skill-up 校验这个对象,并以 `engine_measurements` 写入 `result.json` 和 `report.json`:单轮 case 写在 case 上,多轮 case 写在各自的轮次上。被拒绝的部分列在 `engine_measurement_diagnostics` 里。
- 测量值只是信息,不影响 PASS/FAIL、通过率和 benchmark;`measurements` 无效也不会让 case 失败。
- JSON 无法表示 `NaN` 和 `Infinity`。序列化器如果把它们写成裸 token(Python 的 `json.dumps` 默认如此),整个 `SessionResult` 都无法解析,case 会报错。请用 `allow_nan=False` 序列化,并把这类值上报为 `MISSING`。

字段规则、单位写法、大小上限和诊断码见 [Measurements contract](../../design/custom-engine.md#measurements-contract)。

SessionInput / SessionResult 的完整 JSON 契约见 `docs/design/custom-engine.md`。

### MCP 配置说明
Expand Down
220 changes: 220 additions & 0 deletions e2e/custom_engine_measurements_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
//go:build e2e

package e2e

import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"

"github.com/alibaba/skill-up/internal/judge"
"github.com/alibaba/skill-up/internal/measurement"
"github.com/alibaba/skill-up/internal/report"
)

// serveSessionResults starts a server that answers the n-th request with the
// n-th body; the last body repeats for any further request.
func serveSessionResults(t *testing.T, bodies ...string) *httptest.Server {
t.Helper()
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
index := min(int(calls.Add(1)), len(bodies)) - 1
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, bodies[index])
}))
t.Cleanup(srv.Close)
return srv
}

// runCustomEngineEval runs one custom engine eval file and returns the output
// directory. It fails the test unless the run exits zero with one passed case.
func runCustomEngineEval(t *testing.T, evalFile string, env ...string) string {
t.Helper()
dir := getCustomEngineTestdataDir()
outputDir := t.TempDir()
result := Run(t, RunConfig{
Env: append([]string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")}, env...),
WorkDir: dir,
Timeout: 60 * time.Second,
}, "run", filepath.Join(dir, "evals", evalFile), "--no-delete", "--output-dir", outputDir)
if result.ExitCode != 0 {
t.Fatalf("run failed: exit=%d\nstdout:\n%s\nstderr:\n%s", result.ExitCode, result.Stdout, result.Stderr)
}
if !strings.Contains(result.Stdout, "1 passed") {
t.Fatalf("expected the summary line to report 1 passed, got:\n%s", result.Stdout)
}
return outputDir
}

// readSingleCase reads iteration-1/<name> and returns its only case result.
func readSingleCase(t *testing.T, outputDir, name string) report.CaseResult {
t.Helper()
data, err := os.ReadFile(filepath.Join(outputDir, "iteration-1", name))
if err != nil {
t.Fatalf("read %s: %v", name, err)
}
var input report.Input
if err := json.Unmarshal(data, &input); err != nil {
t.Fatalf("parse %s: %v", name, err)
}
if len(input.CaseResults) != 1 {
t.Fatalf("%s: expected exactly 1 case result, got %d", name, len(input.CaseResults))
}
return input.CaseResults[0]
}

// assertFixtureMeasurements checks that both JSON outputs carry the validated
// content of measured-session-result.json: the valid scalar and the series
// with its missing point are kept, the scalar with an invalid unit is rejected
// alone, and the case still passes.
func assertFixtureMeasurements(t *testing.T, outputDir, engine, transport string) {
t.Helper()
want := &measurement.Set{
SchemaVersion: 1,
Source: measurement.Source{Engine: engine, Transport: transport, Trust: measurement.TrustEngineReported},
Provenance: measurement.Provenance{Producer: "e2e-measuring-agent", ProducerVersion: "1", Method: "fixed fixture values"},
Scalars: []measurement.Scalar{
{ID: "baseline_decode_tps", Unit: "tok/s", Value: "200.0", Availability: measurement.AvailabilityAvailable},
},
Series: []measurement.Series{{
ID: "decode_tps", Unit: "tok/s",
Axis: measurement.Axis{ID: "requested_context_tokens", Unit: "token"},
Points: []measurement.Point{
{At: "8192", Value: "178.2", Availability: measurement.AvailabilityAvailable},
{At: "16384", Availability: measurement.AvailabilityMissing, Reason: "request_timed_out"},
},
}},
}
wantDiagnostics := []measurement.Diagnostic{
{Scope: measurement.ScopeEntry, Code: measurement.CodeInvalidUnit, Path: "scalars[1]", ID: "broken_unit"},
}
for _, name := range []string{"result.json", "report.json"} {
cr := readSingleCase(t, outputDir, name)
if cr.Status != judge.StatusPass {
t.Errorf("%s: status = %q, want %q", name, cr.Status, judge.StatusPass)
}
if !reflect.DeepEqual(cr.EngineMeasurements, want) {
t.Errorf("%s: engine_measurements = %+v\nwant %+v", name, cr.EngineMeasurements, want)
}
if !reflect.DeepEqual(cr.EngineMeasurementDiagnostics, wantDiagnostics) {
t.Errorf("%s: engine_measurement_diagnostics = %+v\nwant %+v", name, cr.EngineMeasurementDiagnostics, wantDiagnostics)
}
}
}

func readMeasuredSessionResult(t *testing.T) string {
t.Helper()
data, err := os.ReadFile(filepath.Join(getCustomEngineTestdataDir(), "measured-session-result.json"))
if err != nil {
t.Fatalf("read fixture: %v", err)
}
return string(data)
}

// TestPipeline_CustomEngine_Measurements_LocalTransport runs the pipeline
// against a local custom engine that reports runtime measurements and checks
// they are validated and persisted with the engine and transport that
// delivered them.
func TestPipeline_CustomEngine_Measurements_LocalTransport(t *testing.T) {
skipIfNoPOSIXShell(t)
t.Parallel()

agentBin := filepath.Join(getCustomEngineTestdataDir(), "measuring-agent.sh")
outputDir := runCustomEngineEval(t, "eval.yaml", "CUSTOM_AGENT_BIN="+agentBin)
assertFixtureMeasurements(t, outputDir, "e2e-custom-agent", "local")
}

// TestPipeline_CustomEngine_Measurements_HTTPTransport serves the same
// SessionResult over the http transport.
func TestPipeline_CustomEngine_Measurements_HTTPTransport(t *testing.T) {
t.Parallel()

srv := serveSessionResults(t, readMeasuredSessionResult(t))
outputDir := runCustomEngineEval(t, "eval-http.yaml", "CUSTOM_AGENT_ENDPOINT="+srv.URL)
assertFixtureMeasurements(t, outputDir, "e2e-custom-http-agent", "http")
}

// TestPipeline_CustomEngine_Measurements_StayOnTheirTurn runs a two-turn
// stateful case in which each turn reports a different value: every turn keeps
// its own measurements and the case itself carries none.
func TestPipeline_CustomEngine_Measurements_StayOnTheirTurn(t *testing.T) {
t.Parallel()

const measurements = `"measurements":{"schema_version":1,"provenance":{"producer":"e2e"},"scalars":[{"id":"ttft","unit":"ms","value":%VALUE%}]}`
srv := serveSessionResults(t,
`{"exit_code":0,"session_id":"session-1","final_message":"token=abc",`+strings.Replace(measurements, "%VALUE%", "11", 1)+`}`,
`{"exit_code":0,"final_message":"used token abc",`+strings.Replace(measurements, "%VALUE%", "22", 1)+`}`,
)
outputDir := runCustomEngineEval(t, "eval-stateful-http.yaml", "CUSTOM_AGENT_ENDPOINT="+srv.URL)

for _, name := range []string{"result.json", "report.json"} {
cr := readSingleCase(t, outputDir, name)
if cr.EngineMeasurements != nil || cr.EngineMeasurementDiagnostics != nil {
t.Errorf("%s: a multi-turn case carries measurements on the case: %+v", name, cr.EngineMeasurements)
}
if len(cr.TurnResults) != 2 {
t.Fatalf("%s: turn results = %d, want 2", name, len(cr.TurnResults))
}
for i, wantValue := range []string{"11", "22"} {
set := cr.TurnResults[i].EngineMeasurements
if set == nil || len(set.Scalars) != 1 || set.Scalars[0].Value.String() != wantValue {
t.Errorf("%s: turn %d measurements = %+v, want ttft=%s", name, i+1, set, wantValue)
continue
}
if set.Source.Engine != "e2e-custom-stateful-http-agent" || set.Source.Transport != "http" {
t.Errorf("%s: turn %d source = %+v", name, i+1, set.Source)
}
}
}
}

// TestPipeline_CustomEngine_Measurements_InvalidNeverChangesTheVerdict returns
// a measurements value that is rejected as a whole. The case still passes, and
// the rejection is recorded instead of the measurements.
func TestPipeline_CustomEngine_Measurements_InvalidNeverChangesTheVerdict(t *testing.T) {
t.Parallel()

srv := serveSessionResults(t, `{"exit_code":0,"final_message":"custom-engine-handled","measurements":[1,2]}`)
outputDir := runCustomEngineEval(t, "eval-http.yaml", "CUSTOM_AGENT_ENDPOINT="+srv.URL)

want := []measurement.Diagnostic{{Scope: measurement.ScopeObject, Code: measurement.CodeNotAnObject}}
for _, name := range []string{"result.json", "report.json"} {
cr := readSingleCase(t, outputDir, name)
if cr.Status != judge.StatusPass || cr.Grading == nil || cr.Grading.Status != judge.StatusPass {
t.Errorf("%s: status = %q, grading = %+v; invalid measurements must not change the verdict", name, cr.Status, cr.Grading)
}
if cr.EngineMeasurements != nil || !reflect.DeepEqual(cr.EngineMeasurementDiagnostics, want) {
t.Errorf("%s: measurements = %+v, diagnostics = %+v; want only %+v", name, cr.EngineMeasurements, cr.EngineMeasurementDiagnostics, want)
}
}
}

// TestPipeline_CustomEngine_NoMeasurementsLeavesTheOutputsUntouched runs an
// engine that reports no measurements and checks the JSON outputs do not
// mention them.
func TestPipeline_CustomEngine_NoMeasurementsLeavesTheOutputsUntouched(t *testing.T) {
t.Parallel()

srv := serveSessionResults(t, `{"exit_code":0,"final_message":"custom-engine-handled"}`)
outputDir := runCustomEngineEval(t, "eval-http.yaml", "CUSTOM_AGENT_ENDPOINT="+srv.URL)

for _, name := range []string{"result.json", "report.json"} {
data, err := os.ReadFile(filepath.Join(outputDir, "iteration-1", name))
if err != nil {
t.Fatalf("read %s: %v", name, err)
}
if bytes.Contains(data, []byte("engine_measurement")) {
t.Errorf("%s mentions engine measurements although the engine reported none", name)
}
}
}
32 changes: 32 additions & 0 deletions e2e/testdata/custom-engine/measured-session-result.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"exit_code": 0,
"final_message": "custom-engine-handled",
"turns": 1,
"transcript": [
{"role": "user", "content": "ping"},
{"role": "assistant", "content": "custom-engine-handled"}
],
"measurements": {
"schema_version": 1,
"provenance": {
"producer": "e2e-measuring-agent",
"producer_version": "1",
"method": "fixed fixture values"
},
"scalars": [
{"id": "baseline_decode_tps", "unit": "tok/s", "value": 200.0},
{"id": "broken_unit", "unit": "tok per s", "value": 1}
],
"series": [
{
"id": "decode_tps",
"unit": "tok/s",
"axis": {"id": "requested_context_tokens", "unit": "token"},
"points": [
{"at": 8192, "value": 178.2},
{"at": 16384, "availability": "MISSING", "reason": "request_timed_out"}
]
}
]
}
}
Loading
Loading