diff --git a/AGENTS.md b/AGENTS.md index c71070e5..4505e5ea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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` diff --git a/CHANGELOG.md b/CHANGELOG.md index 98415cbf..b1f1750d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3aed38a0..e0385f44 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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) @@ -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`. diff --git a/docs/design/custom-engine.md b/docs/design/custom-engine.md index b88a53b3..847dd3e8 100644 --- a/docs/design/custom-engine.md +++ b/docs/design/custom-engine.md @@ -850,6 +850,7 @@ The standard result of a Custom Engine is `SessionResult` JSON: | `stderr` | string | Error output or diagnostic information | | `transcript` | array | Unified transcript | | `artifacts` | object | Artifacts, logs, and workspace diff | +| `measurements` | object | Runtime measurements with names and units. Informational only; see [Measurements contract](#measurements-contract) | ### Transcript contract @@ -893,6 +894,296 @@ At least one of `path`, `url`, `content`, `content_base64` must be provided. A non-local transport must not point `generated_files` or `files.path` at an arbitrary host file path. +### Measurements contract + +The fixed fields above carry four numbers about a run: `duration_ms`, `turns`, +`input_tokens` and `output_tokens`. An engine that measures anything else — decode +throughput at given context lengths, time to first token, effective context length — +reports it in the optional `measurements` object, where every value has a name and a +unit. Both transports accept it. + +skill-up validates the object, masks it, and stores it in `result.json` and +`report.json`. It does nothing else with it: + +- Measurements describe what happened during execution. They are not quality scores. + They never change `PASS` / `FAIL` / `ERROR` / `SKIP`, pass rates, or the benchmark, + and no threshold applies to them. +- They are separate from the named metrics a judge reports, which are quality scores + in `[0, 1]` stored in the `metrics` field of a result. The two have their own id + namespaces, so a measurement id never collides with a metric id, and neither + changes the other. +- skill-up does not verify them. Every stored set is marked + `"trust": "engine_reported"`. +- A defect in `measurements` never fails the case. It is recorded as a diagnostic + next to the result, and the rest of the `SessionResult` is used as usual. + +#### Worked example: a decode-speed sweep + +An instrumented harness, wrapped as a Custom Engine, sends streaming requests at fixed +context lengths, measures the decode speed at each one, and fits a baseline speed and +the context length at which the speed falls to half of it. + +```json +{ + "exit_code": 0, + "final_message": "Decay sweep finished.", + "measurements": { + "schema_version": 1, + "provenance": { + "producer": "dsh-eval-harness", + "producer_version": "e90c255", + "measured_at": "2026-11-17T08:00:00Z", + "subject": "provider=example model=example-model (the deployment as measured, not the architecture)", + "method": "Streaming requests at nominal context steps; a per-request nonce defeats prefix caching; temperature 0, max_tokens 256; median of 3 repeats per step." + }, + "scalars": [ + { + "id": "baseline_decode_tps", + "unit": "tok/s", + "value": 200.0, + "description": "1/a of the least-squares fit tps(n) = 1/(a + b*n)" + }, + { + "id": "half_speed_context", + "unit": "token", + "value": 67000, + "description": "context length where the fitted speed is half of baseline" + } + ], + "series": [ + { + "id": "decode_tps", + "unit": "tok/s", + "description": "median decode speed at each requested context length", + "axis": {"id": "requested_context_tokens", "unit": "token"}, + "points": [ + {"at": 8192, "value": 178.2}, + {"at": 16384, "value": 160.7}, + {"at": 32768, "value": 134.3}, + {"at": 65536, "value": 101.1}, + {"at": 131072, "value": 67.7}, + {"at": 262144, "availability": "MISSING", "reason": "request_timed_out"} + ] + }, + { + "id": "observed_input_tokens", + "unit": "token", + "description": "input tokens the provider reported for each request", + "axis": {"id": "requested_context_tokens", "unit": "token"}, + "points": [ + {"at": 8192, "value": 8201}, + {"at": 16384, "value": 16390}, + {"at": 32768, "value": 32779}, + {"at": 65536, "value": 65541}, + {"at": 131072, "value": 131080}, + {"at": 262144, "availability": "MISSING", "reason": "request_timed_out"} + ] + } + ] + } +} +``` + +`at` is a position on the series' declared axis. Here the axis is the context length +the harness **requested**, because that is known for every step, including the one +that timed out. The input-token count the provider **observed** is a second series +on the same axis. At 262144 tokens the request timed out, so both series report that +step as missing instead of guessing a value. + +The `measurements` object of this example is also the test fixture +`internal/measurement/testdata/decode_sweep.json`; keep the two in step. + +#### Fields + +| Field | Required | Description | +| --- | --- | --- | +| `schema_version` | yes | Must be `1` | +| `provenance` | yes | How the values were produced; see below | +| `scalars` | no | Entries with one value each, for the whole session or for the turn that reported them | +| `series` | no | Entries with an ordered list of points along a declared axis | + +`provenance` is the engine's own account. Its text is masked the same way as +`stderr` and `final_message`. + +| Field | Required | Limit | Description | +| --- | --- | --- | --- | +| `producer` | yes | 1–64 characters | The tool that took the measurements | +| `producer_version` | no | 512 bytes | Its version or commit | +| `measured_at` | no | RFC 3339 | When the measurements were taken | +| `subject` | no | 512 bytes | What was measured, for example provider, model and endpoint. It is for people to read and is never used as a matching key | +| `method` | no | 2 KiB | How it was measured | + +A `scalars` entry: + +| Field | Required | Description | +| --- | --- | --- | +| `id` | yes | Matches `^[a-z][a-z0-9_-]{0,63}$`. Unique within one `measurements` object, across `scalars` and `series` together | +| `unit` | yes | 1–32 characters from `[A-Za-z0-9/%._^*-]`; see [Units](#units) | +| `value` | conditional | A finite JSON number | +| `availability` | no | `AVAILABLE` or `MISSING`. Defaults to `AVAILABLE` when `value` is present | +| `reason` | with `MISSING` | A code matching `^[a-z][a-z0-9_]{0,63}$`, for example `request_timed_out` | +| `description` | no | Up to 256 bytes; how the value was derived | + +A `series` entry has the same `id`, `unit` and `description`, plus: + +| Field | Required | Description | +| --- | --- | --- | +| `axis` | yes | What the series is measured along: an object with its own `id` and `unit`. Axis ids are not entry ids and may repeat across series | +| `points` | yes | The ordered points. Each has `at`, a finite number that is strictly greater than the previous point's, and `value` / `availability` / `reason` exactly as in a scalar | + +Typical axes are `{"id": "requested_context_tokens", "unit": "token"}` for a context +sweep, `{"id": "step", "unit": "1"}` for agent steps and +`{"id": "elapsed", "unit": "s"}` for a time series. A series has one point per step. +Raw repeats and per-chunk timings belong in `artifacts.files`. + +Positions are compared as double-precision numbers, which is how most JSON readers +see them. Two positions that are equal once read as a float64, such as +`9007199254740992` and `9007199254740993`, are the same position, and the series is +rejected. Each stored `at` still keeps the spelling the engine sent. + +The engine computes every value. skill-up never derives a scalar from a series, and +never sums or averages measurements across turns, repeats or runs. + +#### Units + +`unit` is an opaque, case-sensitive label. skill-up checks its shape and compares it +exactly; it never converts units, so the same `id` with a different unit is a +different measurement. Use these spellings where they apply, so that results from +different engines can be compared: + +| Quantity | Spelling | +| --- | --- | +| Time | `s`, `ms` | +| Tokens | `token` | +| Throughput | `tok/s` | +| Size | `byte` | +| Ratio | `%` | +| Cost | `usd` | +| Count or dimensionless value | `1` | + +#### Missing and non-finite values + +An entry or a point carries exactly one of two things: + +- a `value`, optionally with `"availability": "AVAILABLE"`; +- `"availability": "MISSING"` with a `reason`, and no `value`. + +A missing value is stored as missing. It is never written as `0`, interpolated, or +dropped. A JSON `null` is read as an omitted field, for `measurements` itself and for +every optional field inside it. + +JSON has no `NaN` or `Infinity`. A serializer that writes them as bare tokens — +Python's `json.dumps` does so by default — produces a document that is not JSON, so +skill-up cannot read **any** field of the `SessionResult` and the case is reported as +a result error. Serialize with `allow_nan=False` (or the equivalent), and report a +value that came out non-finite as `MISSING` with a reason such as `fit_diverged`. A +number that is valid JSON but too large for a float64, such as `1e999`, rejects only +its own entry. + +#### Validation + +The engine is not trusted, so the object is parsed strictly. Values are never +truncated or clamped: a cut series would silently change its meaning, so it is +rejected instead. + +A **whole-object defect** rejects the entire `measurements` object: + +- `schema_version` is missing or not `1`; +- the value is not a JSON object, or `scalars` / `series` is not an array; +- a JSON object repeats a key, at any level; +- a field outside this contract appears, at any level; +- `provenance` is missing or invalid; +- a whole-object limit is exceeded (see [Result bounds](#result-bounds)). + +An **entry defect** rejects only that scalar or series; valid siblings are kept: + +- an invalid `id` or `unit`; +- an `id` carried by more than one entry — every entry carrying it is rejected, + because the value is ambiguous; +- a `value` that is not a finite number; +- a `value` together with `MISSING`, or neither a `value` nor `MISSING`; +- `MISSING` without a valid `reason`, or a `reason` on an available value; +- a bad point (`at` is not a finite number or does not increase when read as a + float64, or the value is invalid) — it rejects its whole series; +- a series over the point limit, or a `description` over its limit. + +Every rejection is recorded as a diagnostic: + +| Field | Description | +| --- | --- | +| `scope` | `object` when the whole object was rejected, `entry` when one scalar or series was | +| `code` | A stable reason code, listed below | +| `path` | Where the defect is, for example `series[0].points[3]` or `provenance.method` | +| `id` | The rejected entry's id, when that id is itself valid | +| `detail` | A short hint written by skill-up | + +A diagnostic never repeats engine text that failed validation. + +Whole-object codes: `invalid_json`, `payload_too_large`, `not_an_object`, +`duplicate_key`, `unknown_field`, `invalid_structure`, `unsupported_schema_version`, +`invalid_provenance`, `too_many_entries`, `too_many_points`. + +Entry codes: `invalid_entry`, `invalid_id`, `duplicate_id`, `invalid_unit`, +`description_too_long`, `invalid_value`, `invalid_availability`, `conflicting_value`, +`missing_value`, `invalid_reason`, `invalid_axis`, `invalid_point`, `too_many_points`. + +#### Where measurements are stored + +`result.json` and `report.json` carry two fields: + +- `engine_measurements`: the validated measurements, with a `source` block that + skill-up adds; +- `engine_measurement_diagnostics`: the rejections. + +A single-turn case carries them on the case result. A multi-turn case carries them on +the turn result whose `SessionResult` reported them; nothing is carried over or +merged between turns. Both fields are omitted when the engine sent no `measurements`, +so results without measurements are unchanged. + +```json +{ + "case_id": "decode-sweep", + "status": "PASS", + "engine_measurements": { + "schema_version": 1, + "source": {"engine": "tps-harness", "transport": "local", "trust": "engine_reported"}, + "provenance": {"producer": "dsh-eval-harness", "producer_version": "e90c255"}, + "scalars": [ + {"id": "baseline_decode_tps", "unit": "tok/s", "value": 200.0, "availability": "AVAILABLE"} + ], + "series": [ + { + "id": "decode_tps", + "unit": "tok/s", + "axis": {"id": "requested_context_tokens", "unit": "token"}, + "points": [ + {"at": 8192, "value": 178.2, "availability": "AVAILABLE"}, + {"at": 262144, "availability": "MISSING", "reason": "request_timed_out"} + ] + } + ] + }, + "engine_measurement_diagnostics": [ + {"scope": "entry", "code": "invalid_unit", "path": "scalars[1]", "id": "broken_unit"} + ] +} +``` + +`source` records the configured `engine.name` and the transport that delivered the +result. The case, the run and the turn are given by where the block sits in the file. +`availability` is always written out, and numbers keep the spelling the engine sent. + +When anything is rejected, skill-up also logs one warning for that result, naming the +first diagnostic's code and path. + +Only the engine under test is recorded. A custom engine that runs as an `agent_judge` +engine may send the field; it is validated the same way, but nothing is stored. + +Measurements do not appear in `grading.json`, `benchmark.json`, the JUnit, HTML and +Markdown reports, OTel attributes, or the JSONL evaluation-event stream. Built-in +agents do not report them. A skill-up version that predates this contract ignores the +field, so an engine can send `measurements` to any version. + ## Error handling A Custom Engine call failure falls into three categories: @@ -907,6 +1198,12 @@ If the Engine returns a valid `SessionResult` with `exit_code != 0`, the runner keep that `SessionResult` and mark the case as an execution error. `stderr` and `final_message` should enter the report to aid debugging. +A defect inside `measurements` is none of these. The field is informational, so an +invalid object or entry is recorded as a diagnostic and the case keeps the verdict it +would have had without the field. The one exception is a document that is not JSON at +all, for example one containing a bare `NaN`: it is a result error like any other +unparseable result. See [Measurements contract](#measurements-contract). + ## Security constraints skill-up does not trust the custom engine command or its returned `SessionResult`. @@ -940,6 +1237,12 @@ The hardening below is enforced in code; treat each item as part of the contract configured model-layer API key and every value passed via `engine.custom.env` (≥ 8 characters) are replaced with `***REDACTED***` before the result leaves the agent. +- Every string inside `measurements` is masked the same way before it is validated + or stored. Free text (`provenance` fields, `description`) is stored redacted. An + `id` or `reason` that embeds a secret no longer matches its pattern once masked, + so that entry is rejected, and the diagnostic does not repeat the text. A `unit` + that embeds one is stored redacted, or rejected when it no longer fits the + pattern. - kwargs keys that collide with a built-in template variable (`model`, `case_id`, `max_turns`, `workspace`, …) are rejected at validation; rename them. - `SessionInput` carries no `custom.kwargs` map. The local transport writes that @@ -980,6 +1283,20 @@ The hardening below is enforced in code; treat each item as part of the contract logged and skipped without failing the run. The download writes to the report's artifact directory, not the workspace, so it bypasses the `f.Path` workspace confinement by construction. +- `measurements` is bounded by the limits below. Nothing is truncated to fit: going + over a limit rejects the whole object or the entry concerned, and leaves a + diagnostic. Bulkier raw data belongs in `artifacts.files`. + +| Limit | Value | On overflow | +| --- | --- | --- | +| Serialized `measurements` object | 1 MiB | The whole object is rejected | +| Entries (`scalars` and `series` together) | 64 | The whole object is rejected | +| Points in one series | 1,000 | That series is rejected | +| Points in one result, counted as sent | 10,000 | The whole object is rejected | +| `provenance.producer` | 64 characters | The whole object is rejected | +| `provenance.subject`, `provenance.producer_version` | 512 bytes | The whole object is rejected | +| `provenance.method` | 2 KiB | The whole object is rejected | +| `description` of an entry | 256 bytes | That entry is rejected | ### Process and time bounds @@ -1015,6 +1332,11 @@ The hardening below is enforced in code; treat each item as part of the contract agent; when it does not, it requires `engine.custom` and validates the transport and required fields. - `internal/agent/custom.go` implements `CustomAgent`. +- `internal/measurement` validates the optional `measurements` object and defines its + stored form. `CustomAgent.parseSessionResult` hands it the raw field, so a defect + there cannot fail the decode of the fields that grading depends on. The evaluator + clears measurements from the aggregated multi-turn session, and the runner copies + them onto `report.CaseResult` or `report.CaseTurnResult`. - `internal/agent/factory.go` matches built-in agents first; when there is no match and `engine.custom` exists, it creates a `CustomAgent`; when there is no match and the custom config is missing, it reports diff --git a/docs/guide/writing-evals.md b/docs/guide/writing-evals.md index d50f840d..c0bd3039 100644 --- a/docs/guide/writing-evals.md +++ b/docs/guide/writing-evals.md @@ -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 diff --git a/docs/zh/guide/writing-evals.md b/docs/zh/guide/writing-evals.md index 50ca05e1..b4b1cb37 100644 --- a/docs/zh/guide/writing-evals.md +++ b/docs/zh/guide/writing-evals.md @@ -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 配置说明 diff --git a/e2e/custom_engine_measurements_test.go b/e2e/custom_engine_measurements_test.go new file mode 100644 index 00000000..52a8dccf --- /dev/null +++ b/e2e/custom_engine_measurements_test.go @@ -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/ 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) + } + } +} diff --git a/e2e/testdata/custom-engine/measured-session-result.json b/e2e/testdata/custom-engine/measured-session-result.json new file mode 100644 index 00000000..2c61793f --- /dev/null +++ b/e2e/testdata/custom-engine/measured-session-result.json @@ -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"} + ] + } + ] + } +} diff --git a/e2e/testdata/custom-engine/measuring-agent.sh b/e2e/testdata/custom-engine/measuring-agent.sh new file mode 100755 index 00000000..80159d0e --- /dev/null +++ b/e2e/testdata/custom-engine/measuring-agent.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# custom-engine/measuring-agent.sh — a deterministic mock for a Custom Engine +# that reports runtime measurements. It prints the SessionResult stored next +# to this script, which carries one valid scalar, one scalar with an invalid +# unit, and one series with a missing point. The HTTP transport test serves +# the same file, so both transports are checked against one fixture. +set -euo pipefail + +INPUT_FILE="${1:-}" +if [[ -z "$INPUT_FILE" || ! -f "$INPUT_FILE" ]]; then + echo "measuring-agent.sh: SessionInput file not provided or missing (got: '${INPUT_FILE:-}')" >&2 + exit 1 +fi + +cat "$(dirname "$0")/measured-session-result.json" diff --git a/internal/agent/README.md b/internal/agent/README.md index 3e89d722..96c7864e 100644 --- a/internal/agent/README.md +++ b/internal/agent/README.md @@ -119,6 +119,8 @@ type SessionResult struct { Stderr string Transcript transcript.Transcript Artifacts *SessionArtifacts + Measurements *measurement.Set // Custom Engine only: validated runtime measurements, never graded + MeasurementDiagnostics []measurement.Diagnostic // every measurement object or entry that validation rejected } ``` diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 6e23a85e..fe999231 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -16,6 +16,7 @@ import ( "github.com/alibaba/skill-up/internal/credential" "github.com/alibaba/skill-up/internal/customengine" "github.com/alibaba/skill-up/internal/logging" + "github.com/alibaba/skill-up/internal/measurement" "github.com/alibaba/skill-up/internal/observability" "github.com/alibaba/skill-up/internal/platform" "github.com/alibaba/skill-up/internal/runtime" @@ -72,6 +73,14 @@ type SessionResult struct { Transcript transcript.Transcript `json:"transcript,omitempty"` Artifacts *SessionArtifacts `json:"artifacts,omitempty"` PromptDelivery *PromptDeliveryMetadata `json:"prompt_delivery,omitempty"` + // Measurements holds the runtime measurements a Custom Engine reported, + // after validation and masking. They are informational: nothing in grading + // reads them. Both measurement fields stay out of the SessionResult JSON + // form, so the validating parser is the only way to populate them. + Measurements *measurement.Set `json:"-"` + // MeasurementDiagnostics records every measurement object or entry that + // validation rejected. + MeasurementDiagnostics []measurement.Diagnostic `json:"-"` } // SessionResumer is an optional interface that agents may implement to support diff --git a/internal/agent/custom.go b/internal/agent/custom.go index f6ecece2..1fe870c7 100644 --- a/internal/agent/custom.go +++ b/internal/agent/custom.go @@ -18,6 +18,7 @@ import ( "github.com/alibaba/skill-up/internal/customengine" "github.com/alibaba/skill-up/internal/logging" + "github.com/alibaba/skill-up/internal/measurement" "github.com/alibaba/skill-up/internal/runtime" "github.com/alibaba/skill-up/pkg/transcript" ) @@ -571,6 +572,9 @@ type parsedSessionResult struct { Stderr string `json:"stderr"` Transcript transcript.Transcript `json:"transcript"` Artifacts *SessionArtifacts `json:"artifacts"` + // Measurements is kept raw: it is validated on its own, so a defect in it + // can never fail the decode of the fields that grading depends on. + Measurements json.RawMessage `json:"measurements"` } func (a *CustomAgent) parseSessionResult(ctx context.Context, rt Runtime, opts ExecOptions, raw string, durationMs int64, messages []transcript.Message) (*SessionResult, error) { @@ -642,9 +646,32 @@ func (a *CustomAgent) parseSessionResult(ctx context.Context, rt Runtime, opts E if res.DurationMs == 0 { res.DurationMs = durationMs } + res.Measurements, res.MeasurementDiagnostics = a.parseMeasurements(ctx, parsed.Measurements) return res, nil } +// parseMeasurements validates the engine's optional runtime measurements. They +// are informational, so a rejection is recorded as a diagnostic and logged; it +// never fails the run or changes how the result is graded. Engine-supplied text +// goes through maskAPIKey, the same as final_message and stderr. +func (a *CustomAgent) parseMeasurements(ctx context.Context, raw json.RawMessage) (*measurement.Set, []measurement.Diagnostic) { + transport := "" + if a.Cfg.Custom != nil { + transport = a.Cfg.Custom.Transport + } + set, diagnostics := measurement.Parse(raw, measurement.Options{ + Engine: a.Name(), + Transport: transport, + Mask: a.maskAPIKey, + }) + if len(diagnostics) > 0 { + logging.WarnContextf(ctx, + "CustomAgent %q: rejected %d engine measurement item(s), first: %s at %q", + a.Name(), len(diagnostics), diagnostics[0].Code, diagnostics[0].Path) + } + return set, diagnostics +} + // deriveTurns infers a turn count from a transcript. It prefers the highest // explicit Message.Turn value; when no message carries Turn (the // design-example transcript only sets role/content) it falls back to the diff --git a/internal/agent/custom_measurements_test.go b/internal/agent/custom_measurements_test.go new file mode 100644 index 00000000..cd5a2510 --- /dev/null +++ b/internal/agent/custom_measurements_test.go @@ -0,0 +1,268 @@ +package agent + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "strings" + "sync/atomic" + "testing" + + "github.com/alibaba/skill-up/internal/config" + "github.com/alibaba/skill-up/internal/measurement" + "github.com/alibaba/skill-up/pkg/transcript" +) + +const ( + // plainSessionResult is the result every measurement test builds on. + plainSessionResult = `{"exit_code":0,"final_message":"sweep finished","turns":1}` + + validMeasurements = `{"schema_version":1,"provenance":{"producer":"harness"},` + + `"scalars":[{"id":"baseline_decode_tps","unit":"tok/s","value":200.0}],` + + `"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"}]}]}` +) + +// withMeasurements returns plainSessionResult with a measurements member. +func withMeasurements(measurements string) string { + return strings.TrimSuffix(plainSessionResult, "}") + `,"measurements":` + measurements + `}` +} + +// localEngineReturning builds a local engine that prints body as its result. +func localEngineReturning(t *testing.T, rt Runtime, body string) *config.CustomEngineConfig { + t.Helper() + writeWorkspaceFile(t, rt, "engine-result.json", body) + return &config.CustomEngineConfig{ + Transport: "local", + Local: &config.CustomLocalConfig{Command: "cat", Args: []string{"engine-result.json"}}, + } +} + +func wantValidMeasurements(transport string) *measurement.Set { + return &measurement.Set{ + SchemaVersion: 1, + Source: measurement.Source{Engine: "my-agent", Transport: transport, Trust: measurement.TrustEngineReported}, + Provenance: measurement.Provenance{Producer: "harness"}, + 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"}, + }, + }}, + } +} + +func TestCustomAgent_RunLocal_ReportsMeasurements(t *testing.T) { + t.Parallel() + rt := newCustomTestRuntime(t) + ag := customLocalAgent(localEngineReturning(t, rt, withMeasurements(validMeasurements))) + + res, err := ag.Run(t.Context(), rt, ExecOptions{}, userMessages()) + if err != nil { + t.Fatalf("Run: %v", err) + } + if want := wantValidMeasurements("local"); !reflect.DeepEqual(res.Measurements, want) { + t.Fatalf("measurements = %+v; want %+v", res.Measurements, want) + } + if len(res.MeasurementDiagnostics) != 0 { + t.Fatalf("diagnostics = %+v; want none", res.MeasurementDiagnostics) + } +} + +func TestCustomAgent_RunHTTP_ReportsMeasurements(t *testing.T) { + t.Parallel() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, withMeasurements(validMeasurements)) + })) + defer srv.Close() + + rt := newCustomTestRuntime(t) + res, err := httpAgent(httpEngine(srv.URL), "").Run(t.Context(), rt, ExecOptions{}, userMessages()) + if err != nil { + t.Fatalf("Run: %v", err) + } + if want := wantValidMeasurements("http"); !reflect.DeepEqual(res.Measurements, want) { + t.Fatalf("measurements = %+v; want %+v", res.Measurements, want) + } + if len(res.MeasurementDiagnostics) != 0 { + t.Fatalf("diagnostics = %+v; want none", res.MeasurementDiagnostics) + } +} + +// TestCustomAgent_MeasurementsNeverChangeTheRunOutcome pins the rule that +// measurements are informational: whatever the engine puts in the field, the +// fields grading depends on are the same as when the field is absent. +func TestCustomAgent_MeasurementsNeverChangeTheRunOutcome(t *testing.T) { + t.Parallel() + rt := newCustomTestRuntime(t) + baseline, err := customLocalAgent(localEngineReturning(t, rt, plainSessionResult)).Run(t.Context(), rt, ExecOptions{}, userMessages()) + if err != nil { + t.Fatalf("baseline Run: %v", err) + } + if baseline.Measurements != nil || baseline.MeasurementDiagnostics != nil { + t.Fatalf("a result without measurements carries %+v / %+v", baseline.Measurements, baseline.MeasurementDiagnostics) + } + + tests := []struct { + name string + measurements string + wantSet bool + wantDiagnostics []measurement.Diagnostic + }{ + {name: "null", measurements: `null`}, + {name: "valid", measurements: validMeasurements, wantSet: true}, + {name: "not an object", measurements: `[1,2]`, wantDiagnostics: []measurement.Diagnostic{ + {Scope: measurement.ScopeObject, Code: measurement.CodeNotAnObject}, + }}, + {name: "unsupported schema version", measurements: `{"schema_version":9,"provenance":{"producer":"harness"}}`, wantDiagnostics: []measurement.Diagnostic{ + {Scope: measurement.ScopeObject, Code: measurement.CodeUnsupportedSchemaVersion, Path: "schema_version"}, + }}, + {name: "one bad entry", measurements: `{"schema_version":1,"provenance":{"producer":"harness"},"scalars":[{"id":"ok","unit":"ms","value":1},{"id":"bad","unit":"ms","value":1e999}]}`, wantSet: true, wantDiagnostics: []measurement.Diagnostic{ + {Scope: measurement.ScopeEntry, Code: measurement.CodeInvalidValue, Path: "scalars[1]", ID: "bad"}, + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + caseRT := newCustomTestRuntime(t) + res, err := customLocalAgent(localEngineReturning(t, caseRT, withMeasurements(tt.measurements))).Run(t.Context(), caseRT, ExecOptions{}, userMessages()) + if err != nil { + t.Fatalf("Run: %v; measurements must never fail a run", err) + } + if res.ExitCode != baseline.ExitCode || res.FinalMessage != baseline.FinalMessage || res.Turns != baseline.Turns || + res.Stderr != baseline.Stderr || !reflect.DeepEqual(res.Transcript, baseline.Transcript) { + t.Errorf("graded fields changed\n got: %#v\nwant: %#v", res, baseline) + } + if (res.Measurements != nil) != tt.wantSet { + t.Errorf("measurements = %+v; want present=%t", res.Measurements, tt.wantSet) + } + if !sameDiagnostics(res.MeasurementDiagnostics, tt.wantDiagnostics) { + t.Errorf("diagnostics = %+v; want %+v", res.MeasurementDiagnostics, tt.wantDiagnostics) + } + }) + } +} + +// sameDiagnostics compares the contract fields of diagnostics; Detail is a +// human hint and free to be reworded. +func sameDiagnostics(got, want []measurement.Diagnostic) bool { + stripped := make([]measurement.Diagnostic, 0, len(got)) + for _, diagnostic := range got { + diagnostic.Detail = "" + stripped = append(stripped, diagnostic) + } + return slices.Equal(stripped, want) +} + +func TestCustomAgent_FailedRunKeepsReportedMeasurements(t *testing.T) { + t.Parallel() + rt := newCustomTestRuntime(t) + body := `{"exit_code":3,"final_message":"sweep aborted","measurements":` + validMeasurements + `}` + + res, err := customLocalAgent(localEngineReturning(t, rt, body)).Run(t.Context(), rt, ExecOptions{}, userMessages()) + if err == nil || res.ExitCode != 3 { + t.Fatalf("err = %v, exit code = %d; want the engine-reported failure", err, res.ExitCode) + } + if want := wantValidMeasurements("local"); !reflect.DeepEqual(res.Measurements, want) { + t.Fatalf("measurements = %+v; want %+v", res.Measurements, want) + } +} + +func TestCustomAgent_RunLocal_TextFormatCarriesNoMeasurements(t *testing.T) { + t.Parallel() + rt := newCustomTestRuntime(t) + custom := localEngineReturning(t, rt, withMeasurements(validMeasurements)) + custom.ResponseFormat = customResponseText + + res, err := customLocalAgent(custom).Run(t.Context(), rt, ExecOptions{}, userMessages()) + if err != nil { + t.Fatalf("Run: %v", err) + } + if res.Measurements != nil || res.MeasurementDiagnostics != nil { + t.Fatalf("a text response carries %+v / %+v; want none", res.Measurements, res.MeasurementDiagnostics) + } +} + +func TestCustomAgent_MasksMeasurementText(t *testing.T) { + t.Parallel() + const apiKey = "sk-measurement-api-key-0001" //nolint:gosec // fake credential fixture + const envToken = "ghp_measurementtoken_xxxxxx" //nolint:gosec // fake credential fixture + measurements := `{"schema_version":1,"provenance":{"producer":"harness","subject":"endpoint key ` + apiKey + `","method":"auth ` + envToken + `"},` + + `"scalars":[{"id":"ttft","unit":"ms","value":12,"description":"measured with ` + envToken + `"},` + + `{"id":"leaky","unit":"` + apiKey + `","value":1}]}` + rt := newCustomTestRuntime(t) + custom := localEngineReturning(t, rt, withMeasurements(measurements)) + custom.Env = map[string]string{"MY_TOKEN": envToken} + ag := NewCustomAgent(Config{Name: "my-agent", APIKey: apiKey, Custom: custom}) + + res, err := ag.Run(t.Context(), rt, ExecOptions{}, userMessages()) + if err != nil { + t.Fatalf("Run: %v", err) + } + encoded, err := json.Marshal(struct { + Set *measurement.Set `json:"set"` + Diagnostics []measurement.Diagnostic `json:"diagnostics"` + }{res.Measurements, res.MeasurementDiagnostics}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if strings.Contains(string(encoded), apiKey) || strings.Contains(string(encoded), envToken) { + t.Fatalf("a secret survived in the measurements: %s", encoded) + } + want := measurement.Provenance{Producer: "harness", Subject: "endpoint key ***REDACTED***", Method: "auth ***REDACTED***"} + if res.Measurements == nil || res.Measurements.Provenance != want { + t.Fatalf("provenance = %+v; want %+v", res.Measurements, want) + } + if got := res.Measurements.Scalars[0].Description; got != "measured with ***REDACTED***" { + t.Errorf("description = %q; want it masked like stderr", got) + } +} + +func TestCustomAgent_RunTurnHTTP_KeepsMeasurementsOnTheTurnThatReportedThem(t *testing.T) { + t.Parallel() + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if calls.Add(1) == 1 { + _, _ = io.WriteString(w, `{"exit_code":0,"session_id":"s1","final_message":"one","measurements":{"schema_version":1,"provenance":{"producer":"harness"},"scalars":[{"id":"ttft","unit":"ms","value":11}]}}`) + return + } + _, _ = io.WriteString(w, `{"exit_code":0,"session_id":"s1","final_message":"two"}`) + })) + defer srv.Close() + + custom := httpEngine(srv.URL) + custom.ConversationMode = "stateful" + ag, err := DetectAgent("my-agent", Config{Name: "my-agent", Custom: custom}) + if err != nil { + t.Fatalf("DetectAgent: %v", err) + } + resumer, ok := ag.(SessionResumer) + if !ok { + t.Fatalf("agent type %T does not implement SessionResumer", ag) + } + rt := newCustomTestRuntime(t) + message := transcript.Message{Role: transcript.RoleUser, Content: "go"} + + first, err := resumer.RunTurn(t.Context(), rt, ExecOptions{}, message, "") + if err != nil { + t.Fatalf("turn 1: %v", err) + } + second, err := resumer.RunTurn(t.Context(), rt, ExecOptions{}, message, first.SessionID) + if err != nil { + t.Fatalf("turn 2: %v", err) + } + if first.Measurements == nil || len(first.Measurements.Scalars) != 1 || first.Measurements.Scalars[0].Value != "11" { + t.Fatalf("turn 1 measurements = %+v; want the scalar it reported", first.Measurements) + } + if second.Measurements != nil || second.MeasurementDiagnostics != nil { + t.Fatalf("turn 2 measurements = %+v; a turn that reported none must carry none", second.Measurements) + } +} diff --git a/internal/evaluator/multiturn.go b/internal/evaluator/multiturn.go index 4ae184f7..6d30161f 100644 --- a/internal/evaluator/multiturn.go +++ b/internal/evaluator/multiturn.go @@ -965,6 +965,10 @@ func buildAggregateResult(state *multiTurnState, lastResult *agent.SessionResult } } agg := *lastResult + // Engine measurements belong to the turn that reported them. The copy above + // would otherwise present the last turn's measurements as the whole case's. + agg.Measurements = nil + agg.MeasurementDiagnostics = nil agg.Transcript = state.transcript agg.InputTokens = state.inputTokens agg.OutputTokens = state.outputTokens diff --git a/internal/evaluator/multiturn_measurements_test.go b/internal/evaluator/multiturn_measurements_test.go new file mode 100644 index 00000000..38fca86d --- /dev/null +++ b/internal/evaluator/multiturn_measurements_test.go @@ -0,0 +1,91 @@ +package evaluator + +import ( + "context" + "encoding/json" + "testing" + + "github.com/alibaba/skill-up/internal/agent" + "github.com/alibaba/skill-up/internal/config" + "github.com/alibaba/skill-up/internal/measurement" + "github.com/alibaba/skill-up/internal/runtime" + "github.com/alibaba/skill-up/pkg/transcript" +) + +func turnMeasurements(value json.Number) *measurement.Set { + return &measurement.Set{ + SchemaVersion: measurement.SchemaVersion, + Provenance: measurement.Provenance{Producer: "harness"}, + Scalars: []measurement.Scalar{{ID: "ttft", Unit: "ms", Value: value, Availability: measurement.AvailabilityAvailable}}, + } +} + +// measuringResumer reports different engine measurements on each turn, and a +// rejection on the last one. +func measuringResumer() *mockResumerAgent { + call := 0 + return &mockResumerAgent{ + mockAgent: mockAgent{name: "measuring"}, + runTurnFunc: func(_ context.Context, _ runtime.Runtime, _ agent.ExecOptions, msg transcript.Message, _ string) (*agent.SessionResult, error) { + call++ + result := &agent.SessionResult{ + SessionID: "session-1", + FinalMessage: "reply", + Transcript: transcript.Transcript{ + {Role: transcript.RoleUser, Content: msg.Content}, + {Role: transcript.RoleAssistant, Content: "reply"}, + }, + } + if call == 1 { + result.Measurements = turnMeasurements("11") + return result, nil + } + result.Measurements = turnMeasurements("22") + result.MeasurementDiagnostics = []measurement.Diagnostic{ + {Scope: measurement.ScopeEntry, Code: measurement.CodeInvalidUnit, Path: "scalars[1]", ID: "bad"}, + } + return result, nil + }, + } +} + +// TestExecuteMultiTurn_MeasurementsStayOnTheTurnThatReportedThem covers both +// ways a resumer returns results: turn by turn, and as the session so far. +func TestExecuteMultiTurn_MeasurementsStayOnTheTurnThatReportedThem(t *testing.T) { + t.Parallel() + cumulative := measuringResumer() + agents := map[string]agent.Agent{ + "incremental results": &strictIncrementalMockResumerAgent{mockResumerAgent: measuringResumer()}, + "cumulative results": cumulative, + } + for name, ag := range agents { + t.Run(name, func(t *testing.T) { + t.Parallel() + caseCfg := &config.CaseConfig{ID: "sweep", Input: config.Input{Turns: []config.Turn{ + {Role: "user", Content: "first"}, + {Role: "user", Content: "second"}, + }}} + e := newTestEvaluator(EvalOptions{Agent: ag, EvalCfg: &config.EvalConfig{}}) + turns, aggregate, err := e.executeMultiTurn(t.Context(), &mockRuntime{workspace: t.TempDir()}, caseCfg, ag, agent.ExecOptions{ArtifactDir: t.TempDir()}) + if err != nil { + t.Fatalf("executeMultiTurn: %v", err) + } + if len(turns) != 2 { + t.Fatalf("turns = %d; want 2", len(turns)) + } + first, second := turns[0].SessionResult, turns[1].SessionResult + if first.Measurements == nil || first.Measurements.Scalars[0].Value != "11" || first.MeasurementDiagnostics != nil { + t.Errorf("turn 1 = %+v / %+v; want only its own measurements", first.Measurements, first.MeasurementDiagnostics) + } + if second.Measurements == nil || second.Measurements.Scalars[0].Value != "22" || len(second.MeasurementDiagnostics) != 1 { + t.Errorf("turn 2 = %+v / %+v; want its own measurements and diagnostic", second.Measurements, second.MeasurementDiagnostics) + } + if aggregate.Measurements != nil || aggregate.MeasurementDiagnostics != nil { + t.Errorf("aggregate = %+v / %+v; the last turn's measurements must not become the case's", aggregate.Measurements, aggregate.MeasurementDiagnostics) + } + if aggregate.FinalMessage != "reply" || len(aggregate.Transcript) != 4 { + t.Errorf("aggregate = %#v; the rest of the aggregate must be unchanged", aggregate) + } + }) + } +} diff --git a/internal/measurement/decode.go b/internal/measurement/decode.go new file mode 100644 index 00000000..d10ba75b --- /dev/null +++ b/internal/measurement/decode.go @@ -0,0 +1,107 @@ +package measurement + +import ( + "bytes" + "encoding/json" + "errors" + "io" +) + +// maxDepth bounds nesting while decoding. The contract nests five levels at +// most (object → series → entry → points → point), so anything deeper is +// already a structural defect and is not worth decoding. +const maxDepth = 8 + +var ( + errDuplicateKey = errors.New("duplicate object key") + errTooDeep = errors.New("nesting exceeds the measurements contract") + errMalformed = errors.New("malformed measurements value") +) + +// decodeStrict decodes one JSON value into maps, slices, strings, booleans, +// nil and json.Number. encoding/json would keep the last of two equal object +// keys and would fail a whole struct decode on one out-of-range number, so the +// value is walked token by token instead: a repeated key is an error, and +// numbers stay literals for the validator to judge one by one. +func decodeStrict(data []byte) (any, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + value, err := decodeValue(decoder, 0) + if err != nil { + return nil, err + } + if _, err := decoder.Token(); !errors.Is(err, io.EOF) { + return nil, errMalformed + } + return value, nil +} + +func decodeValue(decoder *json.Decoder, depth int) (any, error) { + token, err := decoder.Token() + if err != nil { + return nil, err + } + delim, isDelim := token.(json.Delim) + if !isDelim { + return token, nil + } + if depth >= maxDepth { + return nil, errTooDeep + } + if delim == '{' { + return decodeObject(decoder, depth+1) + } + return decodeArray(decoder, depth+1) +} + +func decodeObject(decoder *json.Decoder, depth int) (map[string]any, error) { + object := make(map[string]any) + for decoder.More() { + keyToken, err := decoder.Token() + if err != nil { + return nil, err + } + key, ok := keyToken.(string) + if !ok { + return nil, errMalformed + } + if _, exists := object[key]; exists { + return nil, errDuplicateKey + } + value, err := decodeValue(decoder, depth) + if err != nil { + return nil, err + } + object[key] = value + } + if _, err := decoder.Token(); err != nil { + return nil, err + } + return object, nil +} + +func decodeArray(decoder *json.Decoder, depth int) ([]any, error) { + items := make([]any, 0) + for decoder.More() { + value, err := decodeValue(decoder, depth) + if err != nil { + return nil, err + } + items = append(items, value) + } + if _, err := decoder.Token(); err != nil { + return nil, err + } + return items, nil +} + +func decodeErrorCode(err error) string { + switch { + case errors.Is(err, errDuplicateKey): + return CodeDuplicateKey + case errors.Is(err, errTooDeep): + return CodeInvalidStructure + default: + return CodeInvalidJSON + } +} diff --git a/internal/measurement/limits_test.go b/internal/measurement/limits_test.go new file mode 100644 index 00000000..16f6c59d --- /dev/null +++ b/internal/measurement/limits_test.go @@ -0,0 +1,155 @@ +package measurement + +import ( + "strconv" + "strings" + "testing" + "unicode/utf8" +) + +// paddedDocument returns a valid measurements object of exactly size bytes. +// The padding is JSON whitespace inside the object, which counts toward the +// serialized size the same way any other byte does. +func paddedDocument(size int) []byte { + doc := document(`"scalars":[` + keptScalar + `]`) + return append([]byte("{"+strings.Repeat(" ", size-len(doc))), doc[1:]...) +} + +// scalarList renders a scalars field holding n uniquely named entries. +func scalarList(n int) string { + items := make([]string, n) + for i := range n { + items[i] = `{"id":"m` + strconv.Itoa(i) + `","unit":"ms","value":1}` + } + return `"scalars":[` + strings.Join(items, ",") + `]` +} + +// seriesList renders a series field with one uniquely named series per element +// of sizes, holding that many points. +func seriesList(sizes ...int) string { + items := make([]string, len(sizes)) + for i, size := range sizes { + items[i] = `{"id":"s` + strconv.Itoa(i) + `","unit":"ms",` + testAxis + `,"points":` + points(size) + `}` + } + return `"series":[` + strings.Join(items, ",") + `]` +} + +// fullSeriesSizes returns the sizes of enough full series to reach +// MaxTotalPoints exactly, followed by extra. +func fullSeriesSizes(extra ...int) []int { + sizes := make([]int, 0, MaxTotalPoints/MaxSeriesPoints+len(extra)) + for range MaxTotalPoints / MaxSeriesPoints { + sizes = append(sizes, MaxSeriesPoints) + } + return append(sizes, extra...) +} + +func scalarWith(field, value string) []byte { + return document(`"scalars":[{"id":"a","unit":"ms","value":1,"` + field + `":"` + value + `"}]`) +} + +//nolint:funlen // table-driven test cases drive the line count. +func TestParseAcceptsEveryLimitAtItsBoundary(t *testing.T) { + longID := "a" + strings.Repeat("b", 63) + longUnit := strings.Repeat("u", 32) + longReason := "r" + strings.Repeat("e", 63) + tests := []struct { + name string + raw []byte + intact func(set *Set) bool + }{ + {"payload at the byte limit", paddedDocument(MaxPayloadBytes), func(set *Set) bool { + return len(set.Scalars) == 1 + }}, + {"entries at the limit", document(scalarList(MaxEntries)), func(set *Set) bool { + return len(set.Scalars) == MaxEntries + }}, + {"entries at the limit across both lists", document(scalarList(MaxEntries-1) + `,"series":[` + seriesEntry(testAxis+`,"points":[]`) + `]`), func(set *Set) bool { + return len(set.Scalars) == MaxEntries-1 && len(set.Series) == 1 + }}, + {"series points at the limit", document(`"series":[` + seriesEntry(testAxis+`,"points":`+points(MaxSeriesPoints)) + `]`), func(set *Set) bool { + return len(set.Series) == 1 && len(set.Series[0].Points) == MaxSeriesPoints + }}, + {"result points at the limit", document(seriesList(fullSeriesSizes()...)), func(set *Set) bool { + return len(set.Series) == MaxTotalPoints/MaxSeriesPoints + }}, + {"producer at the character limit", withProvenance(`{"producer":"` + strings.Repeat("é", MaxProducerChars) + `"}`), func(set *Set) bool { + return utf8.RuneCountInString(set.Provenance.Producer) == MaxProducerChars + }}, + {"producer_version at the byte limit", withProvenance(`{"producer":"p","producer_version":"` + strings.Repeat("v", MaxSubjectBytes) + `"}`), func(set *Set) bool { + return len(set.Provenance.ProducerVersion) == MaxSubjectBytes + }}, + {"subject at the byte limit", withProvenance(`{"producer":"p","subject":"` + strings.Repeat("s", MaxSubjectBytes) + `"}`), func(set *Set) bool { + return len(set.Provenance.Subject) == MaxSubjectBytes + }}, + {"method at the byte limit", withProvenance(`{"producer":"p","method":"` + strings.Repeat("m", MaxMethodBytes) + `"}`), func(set *Set) bool { + return len(set.Provenance.Method) == MaxMethodBytes + }}, + {"description at the byte limit", scalarWith("description", strings.Repeat("d", MaxDescriptionBytes)), func(set *Set) bool { + return len(set.Scalars) == 1 && len(set.Scalars[0].Description) == MaxDescriptionBytes + }}, + {"id at the length limit", document(`"scalars":[{"id":"` + longID + `","unit":"ms","value":1}]`), func(set *Set) bool { + return len(set.Scalars) == 1 && set.Scalars[0].ID == longID + }}, + {"unit at the length limit", document(`"scalars":[{"id":"a","unit":"` + longUnit + `","value":1}]`), func(set *Set) bool { + return len(set.Scalars) == 1 && set.Scalars[0].Unit == longUnit + }}, + {"reason at the length limit", document(`"scalars":[{"id":"a","unit":"ms","availability":"MISSING","reason":"` + longReason + `"}]`), func(set *Set) bool { + return len(set.Scalars) == 1 && set.Scalars[0].Reason == longReason + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + set, diagnostics := parseForTest(tt.raw) + if set == nil || len(diagnostics) != 0 { + t.Fatalf("a value at its limit was rejected: diagnostics = %+v", diagnostics) + } + if !tt.intact(set) { + t.Fatalf("a value at its limit was altered: %+v", set) + } + }) + } +} + +func TestParseRejectsOnePastEachWholeObjectLimit(t *testing.T) { + tests := []struct { + name string + raw []byte + wantCode string + wantPath string + }{ + {"payload one byte over", paddedDocument(MaxPayloadBytes + 1), CodePayloadTooLarge, ""}, + {"one entry over", document(scalarList(MaxEntries + 1)), CodeTooManyEntries, ""}, + {"one entry over across both lists", document(scalarList(MaxEntries) + `,"series":[` + seriesEntry(testAxis+`,"points":[]`) + `]`), CodeTooManyEntries, ""}, + {"one result point over", document(seriesList(fullSeriesSizes(1)...)), CodeTooManyPoints, "series"}, + {"producer one character over", withProvenance(`{"producer":"` + strings.Repeat("é", MaxProducerChars+1) + `"}`), CodeInvalidProvenance, "provenance.producer"}, + {"producer_version one byte over", withProvenance(`{"producer":"p","producer_version":"` + strings.Repeat("v", MaxSubjectBytes+1) + `"}`), CodeInvalidProvenance, "provenance.producer_version"}, + {"subject one byte over", withProvenance(`{"producer":"p","subject":"` + strings.Repeat("s", MaxSubjectBytes+1) + `"}`), CodeInvalidProvenance, "provenance.subject"}, + {"method one byte over", withProvenance(`{"producer":"p","method":"` + strings.Repeat("m", MaxMethodBytes+1) + `"}`), CodeInvalidProvenance, "provenance.method"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + set, diagnostics := parseForTest(tt.raw) + if set != nil { + t.Fatalf("set = %+v; want nil one past a whole-object limit", set) + } + want := []Diagnostic{{Scope: ScopeObject, Code: tt.wantCode, Path: tt.wantPath}} + if !equalIgnoringDetail(diagnostics, want) { + t.Fatalf("diagnostics = %+v; want %+v", diagnostics, want) + } + }) + } +} + +func TestParseRejectsOnePastEachEntryLimit(t *testing.T) { + const path = "scalars[1]" + tests := []entryCase{ + {"id one character over", `{"id":"a` + strings.Repeat("b", 64) + `","unit":"ms","value":1}`, CodeInvalidID, path, ""}, + {"unit one character over", `{"id":"b","unit":"` + strings.Repeat("u", 33) + `","value":1}`, CodeInvalidUnit, path, "b"}, + {"reason one character over", `{"id":"b","unit":"ms","availability":"MISSING","reason":"r` + strings.Repeat("e", 64) + `"}`, CodeInvalidReason, path, "b"}, + {"description one byte over", `{"id":"b","unit":"ms","value":1,"description":"` + strings.Repeat("d", MaxDescriptionBytes+1) + `"}`, CodeDescriptionTooLong, path, "b"}, + } + runEntryCases(t, tests, func(entry string) []byte { + return document(`"scalars":[` + keptScalar + `,` + entry + `]`) + }) +} diff --git a/internal/measurement/measurement.go b/internal/measurement/measurement.go new file mode 100644 index 00000000..a705a9de --- /dev/null +++ b/internal/measurement/measurement.go @@ -0,0 +1,269 @@ +// Package measurement validates and models the optional runtime measurements a +// custom engine reports in its SessionResult. +// +// Measurements describe what happened during execution — decode throughput at +// given context lengths, time to first token, and the like. They are +// informational and never take part in grading. The engine is untrusted, so the +// payload is parsed strictly: a defect in the object as a whole rejects all of +// it, a defect in one entry rejects only that entry, and every rejection leaves +// a Diagnostic. Nothing is truncated, clamped, or defaulted to zero. +package measurement + +import ( + "bytes" + "encoding/json" + "strconv" +) + +// SchemaVersion is the only measurements schema version this build accepts. +const SchemaVersion = 1 + +// Size limits. Exceeding one rejects the whole object or the entry concerned; +// see the limit table in docs/design/custom-engine.md. +const ( + // MaxPayloadBytes caps the serialized measurements object. + MaxPayloadBytes = 1 << 20 + // MaxEntries caps scalars and series taken together. + MaxEntries = 64 + // MaxSeriesPoints caps the points of one series. + MaxSeriesPoints = 1000 + // MaxTotalPoints caps the points of all series in one result. + MaxTotalPoints = 10000 + // MaxProducerChars caps provenance.producer, counted in characters. + MaxProducerChars = 64 + // MaxSubjectBytes caps provenance.subject and provenance.producer_version. + MaxSubjectBytes = 512 + // MaxMethodBytes caps provenance.method. + MaxMethodBytes = 2 << 10 + // MaxDescriptionBytes caps the description of one entry. + MaxDescriptionBytes = 256 +) + +// Availability states of a scalar or a series point. +const ( + // AvailabilityAvailable marks an entry or point that carries a value. + AvailabilityAvailable = "AVAILABLE" + // AvailabilityMissing marks an entry or point whose value is absent. + AvailabilityMissing = "MISSING" +) + +// TrustEngineReported marks values skill-up recorded without verifying them. +const TrustEngineReported = "engine_reported" + +// Diagnostic scopes: how much one rejection removed. +const ( + // ScopeObject means the whole measurements object was rejected. + ScopeObject = "object" + // ScopeEntry means one scalar or one series was rejected. + ScopeEntry = "entry" +) + +// Diagnostic codes. They are part of the result.json contract. +const ( + // CodeInvalidJSON reports a value that is not well-formed JSON. + CodeInvalidJSON = "invalid_json" + // CodePayloadTooLarge reports an object over MaxPayloadBytes. + CodePayloadTooLarge = "payload_too_large" + // CodeNotAnObject reports a measurements value that is not a JSON object. + CodeNotAnObject = "not_an_object" + // CodeDuplicateKey reports a JSON object that repeats a key, at any level. + CodeDuplicateKey = "duplicate_key" + // CodeUnknownField reports a field outside the contract, at any level. + CodeUnknownField = "unknown_field" + // CodeInvalidStructure reports a list that is not an array, or nesting + // deeper than the contract allows. + CodeInvalidStructure = "invalid_structure" + // CodeUnsupportedSchemaVersion reports a missing or unsupported schema_version. + CodeUnsupportedSchemaVersion = "unsupported_schema_version" + // CodeInvalidProvenance reports a missing or invalid provenance block. + CodeInvalidProvenance = "invalid_provenance" + // CodeTooManyEntries reports more than MaxEntries entries. + CodeTooManyEntries = "too_many_entries" + // CodeTooManyPoints reports a series over MaxSeriesPoints (entry scope) or + // a result over MaxTotalPoints (object scope). + CodeTooManyPoints = "too_many_points" + // CodeInvalidEntry reports an entry that is not an object or that carries a + // field of the wrong type. + CodeInvalidEntry = "invalid_entry" + // CodeInvalidID reports a missing id or one outside the id pattern. + CodeInvalidID = "invalid_id" + // CodeDuplicateID reports an id carried by more than one entry. + CodeDuplicateID = "duplicate_id" + // CodeInvalidUnit reports a missing unit or one outside the unit pattern. + CodeInvalidUnit = "invalid_unit" + // CodeDescriptionTooLong reports a description over MaxDescriptionBytes. + CodeDescriptionTooLong = "description_too_long" + // CodeInvalidValue reports a value that is not a finite JSON number. + CodeInvalidValue = "invalid_value" + // CodeInvalidAvailability reports an availability other than AVAILABLE or MISSING. + CodeInvalidAvailability = "invalid_availability" + // CodeConflictingValue reports a value given together with MISSING. + CodeConflictingValue = "conflicting_value" + // CodeMissingValue reports an entry or point with neither a value nor MISSING. + CodeMissingValue = "missing_value" + // CodeInvalidReason reports MISSING without a valid reason code, or a + // reason attached to an available value. + CodeInvalidReason = "invalid_reason" + // CodeInvalidAxis reports a series without a valid axis id and unit. + CodeInvalidAxis = "invalid_axis" + // CodeInvalidPoint reports a point that is not an object, or whose position + // is not a finite number strictly greater than the previous one. + CodeInvalidPoint = "invalid_point" +) + +// Set is the validated set of measurements one SessionResult reported. +type Set struct { + SchemaVersion int `json:"schema_version"` + Source Source `json:"source"` + Provenance Provenance `json:"provenance"` + Scalars []Scalar `json:"scalars,omitempty"` + Series []Series `json:"series,omitempty"` +} + +// Source is recorded by skill-up: the engine and transport that delivered the +// measurements. Trust is always TrustEngineReported, because skill-up does not +// verify what an engine measured. +type Source struct { + Engine string `json:"engine"` + Transport string `json:"transport"` + Trust string `json:"trust"` +} + +// Provenance is the engine's own account of how the values were produced. +type Provenance struct { + Producer string `json:"producer"` + ProducerVersion string `json:"producer_version,omitempty"` + MeasuredAt string `json:"measured_at,omitempty"` + Subject string `json:"subject,omitempty"` + Method string `json:"method,omitempty"` +} + +// Scalar is one value for the whole session, or for the turn that reported it. +// Value keeps the engine's number literal and is empty when Availability is +// AvailabilityMissing. +type Scalar struct { + ID string `json:"id"` + Unit string `json:"unit"` + Value json.Number `json:"value,omitempty"` + Availability string `json:"availability"` + Reason string `json:"reason,omitempty"` + Description string `json:"description,omitempty"` +} + +// Series is an ordered list of points along a declared axis. +type Series struct { + ID string `json:"id"` + Unit string `json:"unit"` + Description string `json:"description,omitempty"` + Axis Axis `json:"axis"` + Points []Point `json:"points"` +} + +// Axis names what a series is measured along. +type Axis struct { + ID string `json:"id"` + Unit string `json:"unit"` +} + +// Point is one step of a series. At is its position on the axis. It keeps the +// engine's literal, but positions are ordered as float64 values: two literals +// that convert to the same float64 are the same position. +type Point struct { + At json.Number `json:"at"` + Value json.Number `json:"value,omitempty"` + Availability string `json:"availability"` + Reason string `json:"reason,omitempty"` +} + +// Diagnostic records one rejection. Path locates it inside the measurements +// object (series[0].points[3]); ID is the rejected entry's id when that id is +// itself valid. No field ever echoes engine-supplied text that failed +// validation. +type Diagnostic struct { + Scope string `json:"scope"` + Code string `json:"code"` + Path string `json:"path,omitempty"` + ID string `json:"id,omitempty"` + Detail string `json:"detail,omitempty"` +} + +// Options carries what skill-up knows about the engine that reported. +type Options struct { + // Engine is the configured engine name, recorded as the source. + Engine string + // Transport is the custom engine transport that delivered the result. + Transport string + // Mask redacts secrets from engine-supplied text before it is validated or + // stored. Nil leaves text unchanged. + Mask func(string) string +} + +// Parse validates the raw measurements value of a SessionResult. +// +// It returns the accepted measurements — nil when the engine sent none or when +// the object as a whole was rejected — and one Diagnostic per rejection. A JSON +// null counts as "not sent", the same as an omitted field. +func Parse(raw []byte, opts Options) (*Set, []Diagnostic) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) { + return nil, nil + } + if len(trimmed) > MaxPayloadBytes { + return nil, []Diagnostic{*rejectObject(CodePayloadTooLarge, "", + "serialized measurements exceed "+strconv.Itoa(MaxPayloadBytes)+" bytes")} + } + tree, err := decodeStrict(trimmed) + if err != nil { + return nil, []Diagnostic{*rejectObject(decodeErrorCode(err), "", "")} + } + root, ok := tree.(map[string]any) + if !ok { + return nil, []Diagnostic{*rejectObject(CodeNotAnObject, "", "")} + } + + p := parser{mask: opts.Mask} + if p.mask == nil { + p.mask = func(text string) string { return text } + } + provenance, scalars, series, rejection := p.parseObject(root) + if rejection != nil { + return nil, []Diagnostic{*rejection} + } + + set := &Set{ + SchemaVersion: SchemaVersion, + Source: Source{Engine: opts.Engine, Transport: opts.Transport, Trust: TrustEngineReported}, + Provenance: provenance, + } + var diagnostics []Diagnostic + counts := p.idCounts(scalars, series) + for index, item := range scalars { + scalar, entryRejection := p.parseScalar(index, item, counts) + if entryRejection != nil { + diagnostics = append(diagnostics, *entryRejection) + continue + } + set.Scalars = append(set.Scalars, scalar) + } + for index, item := range series { + entry, entryRejection := p.parseSeries(index, item, counts) + if entryRejection != nil { + diagnostics = append(diagnostics, *entryRejection) + continue + } + set.Series = append(set.Series, entry) + } + return set, diagnostics +} + +func rejectObject(code, path, detail string) *Diagnostic { + return &Diagnostic{Scope: ScopeObject, Code: code, Path: path, Detail: detail} +} + +func rejectEntry(code, path, id, detail string) *Diagnostic { + return &Diagnostic{Scope: ScopeEntry, Code: code, Path: path, ID: id, Detail: detail} +} + +func indexPath(list string, index int) string { + return list + "[" + strconv.Itoa(index) + "]" +} diff --git a/internal/measurement/measurement_test.go b/internal/measurement/measurement_test.go new file mode 100644 index 00000000..57040796 --- /dev/null +++ b/internal/measurement/measurement_test.go @@ -0,0 +1,502 @@ +package measurement + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "slices" + "strconv" + "strings" + "testing" +) + +const ( + keptScalar = `{"id":"kept","unit":"ms","value":1}` + testAxis = `"axis":{"id":"requested_context_tokens","unit":"token"}` +) + +// document wraps members (the scalars and series fields) in an otherwise valid +// measurements object. +func document(members string) []byte { + const head = `{"schema_version":1,"provenance":{"producer":"harness"}` + if members == "" { + return []byte(head + "}") + } + return []byte(head + "," + members + "}") +} + +// withProvenance builds a measurements object around one provenance body. +func withProvenance(provenance string) []byte { + return []byte(`{"schema_version":1,"provenance":` + provenance + `}`) +} + +// seriesEntry builds a series named "s" from its remaining fields. +func seriesEntry(fields string) string { + return `{"id":"s","unit":"tok/s",` + fields + `}` +} + +// points renders n valid points at positions 1..n. +func points(n int) string { + items := make([]string, n) + for i := range n { + items[i] = `{"at":` + strconv.Itoa(i+1) + `,"value":1}` + } + return "[" + strings.Join(items, ",") + "]" +} + +func parseForTest(raw []byte) (*Set, []Diagnostic) { + return Parse(raw, Options{Engine: "tps-harness", Transport: "local"}) +} + +func TestParseWorkedExample(t *testing.T) { + raw, err := os.ReadFile(filepath.Join("testdata", "decode_sweep.json")) + if err != nil { + t.Fatalf("read worked example: %v", err) + } + got, diagnostics := parseForTest(raw) + if len(diagnostics) != 0 { + t.Fatalf("worked example produced diagnostics: %+v", diagnostics) + } + timedOut := Point{At: "262144", Availability: AvailabilityMissing, Reason: "request_timed_out"} + axis := Axis{ID: "requested_context_tokens", Unit: "token"} + want := &Set{ + SchemaVersion: 1, + Source: Source{Engine: "tps-harness", Transport: "local", Trust: TrustEngineReported}, + Provenance: Provenance{ + Producer: "dsh-eval-harness", + ProducerVersion: "e90c255", + MeasuredAt: "2026-11-17T08:00:00Z", + Subject: "provider=example model=example-model (the deployment as measured, not the architecture)", + Method: "Streaming requests at nominal context steps; a per-request nonce defeats prefix caching; temperature 0, max_tokens 256; median of 3 repeats per step.", + }, + Scalars: []Scalar{ + {ID: "baseline_decode_tps", Unit: "tok/s", Value: "200.0", Availability: AvailabilityAvailable, Description: "1/a of the least-squares fit tps(n) = 1/(a + b*n)"}, + {ID: "half_speed_context", Unit: "token", Value: "67000", Availability: AvailabilityAvailable, Description: "context length where the fitted speed is half of baseline"}, + }, + Series: []Series{ + { + ID: "decode_tps", Unit: "tok/s", Axis: axis, + Description: "median decode speed at each requested context length", + Points: []Point{ + {At: "8192", Value: "178.2", Availability: AvailabilityAvailable}, + {At: "16384", Value: "160.7", Availability: AvailabilityAvailable}, + {At: "32768", Value: "134.3", Availability: AvailabilityAvailable}, + {At: "65536", Value: "101.1", Availability: AvailabilityAvailable}, + {At: "131072", Value: "67.7", Availability: AvailabilityAvailable}, + timedOut, + }, + }, + { + ID: "observed_input_tokens", Unit: "token", Axis: axis, + Description: "input tokens the provider reported for each request", + Points: []Point{ + {At: "8192", Value: "8201", Availability: AvailabilityAvailable}, + {At: "16384", Value: "16390", Availability: AvailabilityAvailable}, + {At: "32768", Value: "32779", Availability: AvailabilityAvailable}, + {At: "65536", Value: "65541", Availability: AvailabilityAvailable}, + {At: "131072", Value: "131080", Availability: AvailabilityAvailable}, + timedOut, + }, + }, + }, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("worked example mismatch\n got: %+v\nwant: %+v", got, want) + } +} + +func TestParseTreatsAbsentAndNullAsNotSent(t *testing.T) { + for _, raw := range []string{"", " \n", "null", " null "} { + set, diagnostics := parseForTest([]byte(raw)) + if set != nil || diagnostics != nil { + t.Errorf("Parse(%q) = %+v, %+v; want nil, nil", raw, set, diagnostics) + } + } +} + +func TestParseAcceptsAnObjectWithoutEntries(t *testing.T) { + for _, raw := range [][]byte{document(""), document(`"scalars":[],"series":[]`), document(`"scalars":null,"series":null`)} { + set, diagnostics := parseForTest(raw) + if set == nil || len(diagnostics) != 0 { + t.Fatalf("Parse(%s) = %+v, %+v; want an empty set and no diagnostics", raw, set, diagnostics) + } + if len(set.Scalars) != 0 || len(set.Series) != 0 || set.Provenance.Producer != "harness" { + t.Errorf("Parse(%s) = %+v; want only provenance", raw, set) + } + } +} + +//nolint:funlen // table-driven test cases drive the line count. +func TestParseRejectsTheWholeObject(t *testing.T) { + tests := []struct { + name string + raw []byte + wantCode string + wantPath string + }{ + {"array", []byte(`[]`), CodeNotAnObject, ""}, + {"string", []byte(`"text"`), CodeNotAnObject, ""}, + {"number", []byte(`42`), CodeNotAnObject, ""}, + {"boolean", []byte(`true`), CodeNotAnObject, ""}, + {"truncated JSON", []byte(`{"schema_version":1`), CodeInvalidJSON, ""}, + {"trailing value", []byte(`{} {}`), CodeInvalidJSON, ""}, + {"duplicate key at the root", []byte(`{"schema_version":1,"schema_version":1,"provenance":{"producer":"p"}}`), CodeDuplicateKey, ""}, + {"duplicate key in provenance", withProvenance(`{"producer":"p","producer":"q"}`), CodeDuplicateKey, ""}, + {"duplicate key in an entry", document(`"scalars":[{"id":"a","unit":"ms","value":1,"unit":"s"}]`), CodeDuplicateKey, ""}, + {"duplicate key in a point", document(`"series":[` + seriesEntry(testAxis+`,"points":[{"at":1,"value":1,"value":2}]`) + `]`), CodeDuplicateKey, ""}, + {"unknown field at the root", document(`"extra":{}`), CodeUnknownField, ""}, + {"unknown field in provenance", withProvenance(`{"producer":"p","host":"h"}`), CodeUnknownField, "provenance"}, + {"unknown field in a scalar", document(`"scalars":[` + keptScalar + `,{"id":"b","unit":"ms","value":1,"extra":1}]`), CodeUnknownField, "scalars[1]"}, + {"unknown field in a series", document(`"series":[` + seriesEntry(testAxis+`,"points":[],"extra":1`) + `]`), CodeUnknownField, "series[0]"}, + {"unknown field in an axis", document(`"series":[` + seriesEntry(`"axis":{"id":"step","unit":"1","scale":"log"},"points":[]`) + `]`), CodeUnknownField, "series[0].axis"}, + {"unknown field in a point", document(`"series":[` + seriesEntry(testAxis+`,"points":[{"at":1,"value":1},{"at":2,"value":1,"note":"x"}]`) + `]`), CodeUnknownField, "series[0].points[1]"}, + {"schema_version missing", []byte(`{"provenance":{"producer":"p"}}`), CodeUnsupportedSchemaVersion, "schema_version"}, + {"schema_version unsupported", []byte(`{"schema_version":2,"provenance":{"producer":"p"}}`), CodeUnsupportedSchemaVersion, "schema_version"}, + {"schema_version as a string", []byte(`{"schema_version":"1","provenance":{"producer":"p"}}`), CodeUnsupportedSchemaVersion, "schema_version"}, + {"schema_version null", []byte(`{"schema_version":null,"provenance":{"producer":"p"}}`), CodeUnsupportedSchemaVersion, "schema_version"}, + {"provenance missing", []byte(`{"schema_version":1}`), CodeInvalidProvenance, "provenance"}, + {"provenance null", withProvenance(`null`), CodeInvalidProvenance, "provenance"}, + {"provenance not an object", withProvenance(`"harness"`), CodeInvalidProvenance, "provenance"}, + {"producer missing", withProvenance(`{}`), CodeInvalidProvenance, "provenance.producer"}, + {"producer empty", withProvenance(`{"producer":""}`), CodeInvalidProvenance, "provenance.producer"}, + {"producer blank", withProvenance(`{"producer":" "}`), CodeInvalidProvenance, "provenance.producer"}, + {"producer not a string", withProvenance(`{"producer":5}`), CodeInvalidProvenance, "provenance.producer"}, + {"measured_at not RFC 3339", withProvenance(`{"producer":"p","measured_at":"yesterday"}`), CodeInvalidProvenance, "provenance.measured_at"}, + {"method not a string", withProvenance(`{"producer":"p","method":[]}`), CodeInvalidProvenance, "provenance.method"}, + {"scalars not an array", document(`"scalars":{}`), CodeInvalidStructure, ""}, + {"series not an array", document(`"series":"decode_tps"`), CodeInvalidStructure, ""}, + {"nesting too deep", document(`"scalars":[[[[[[[[[1]]]]]]]]]`), CodeInvalidStructure, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + set, diagnostics := parseForTest(tt.raw) + if set != nil { + t.Fatalf("set = %+v; want nil when the whole object is rejected", set) + } + want := []Diagnostic{{Scope: ScopeObject, Code: tt.wantCode, Path: tt.wantPath}} + if !equalIgnoringDetail(diagnostics, want) { + t.Fatalf("diagnostics = %+v; want %+v", diagnostics, want) + } + }) + } +} + +// equalIgnoringDetail compares diagnostics on the fields that are part of the +// contract; Detail is a human hint and free to be reworded. +func equalIgnoringDetail(got, want []Diagnostic) bool { + stripped := make([]Diagnostic, 0, len(got)) + for _, diagnostic := range got { + diagnostic.Detail = "" + stripped = append(stripped, diagnostic) + } + return slices.Equal(stripped, want) +} + +type entryCase struct { + name string + entry string + wantCode string + wantPath string + wantID string +} + +// runEntryCases checks that each defective entry is rejected alone: the valid +// sibling scalar survives and exactly one entry-scope diagnostic is recorded. +func runEntryCases(t *testing.T, tests []entryCase, build func(entry string) []byte) { + t.Helper() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + set, diagnostics := parseForTest(build(tt.entry)) + if set == nil { + t.Fatalf("set = nil, diagnostics = %+v; an entry defect must not reject the object", diagnostics) + } + if len(set.Scalars) != 1 || set.Scalars[0].ID != "kept" || len(set.Series) != 0 { + t.Errorf("accepted entries = %+v / %+v; want only the valid sibling", set.Scalars, set.Series) + } + want := []Diagnostic{{Scope: ScopeEntry, Code: tt.wantCode, Path: tt.wantPath, ID: tt.wantID}} + if !equalIgnoringDetail(diagnostics, want) { + t.Errorf("diagnostics = %+v; want %+v", diagnostics, want) + } + }) + } +} + +//nolint:funlen // table-driven test cases drive the line count. +func TestParseRejectsOnlyTheDefectiveScalar(t *testing.T) { + const path = "scalars[1]" + long := strings.Repeat("a", 65) + tests := []entryCase{ + {"not an object", `5`, CodeInvalidEntry, path, ""}, + {"id missing", `{"unit":"ms","value":1}`, CodeInvalidID, path, ""}, + {"id not a string", `{"id":7,"unit":"ms","value":1}`, CodeInvalidID, path, ""}, + {"id with upper case", `{"id":"Bad","unit":"ms","value":1}`, CodeInvalidID, path, ""}, + {"id starting with a digit", `{"id":"1st","unit":"ms","value":1}`, CodeInvalidID, path, ""}, + {"id one past the length limit", `{"id":"` + long + `","unit":"ms","value":1}`, CodeInvalidID, path, ""}, + {"unit missing", `{"id":"b","value":1}`, CodeInvalidUnit, path, "b"}, + {"unit empty", `{"id":"b","unit":"","value":1}`, CodeInvalidUnit, path, "b"}, + {"unit with a space", `{"id":"b","unit":"tok per s","value":1}`, CodeInvalidUnit, path, "b"}, + {"unit one past the length limit", `{"id":"b","unit":"` + strings.Repeat("u", 33) + `","value":1}`, CodeInvalidUnit, path, "b"}, + {"description not a string", `{"id":"b","unit":"ms","value":1,"description":5}`, CodeInvalidEntry, path, "b"}, + {"description one past the limit", `{"id":"b","unit":"ms","value":1,"description":"` + strings.Repeat("d", MaxDescriptionBytes+1) + `"}`, CodeDescriptionTooLong, path, "b"}, + {"value as a string", `{"id":"b","unit":"ms","value":"1"}`, CodeInvalidValue, path, "b"}, + {"value as a boolean", `{"id":"b","unit":"ms","value":true}`, CodeInvalidValue, path, "b"}, + {"value as an object", `{"id":"b","unit":"ms","value":{}}`, CodeInvalidValue, path, "b"}, + {"value not finite", `{"id":"b","unit":"ms","value":1e999}`, CodeInvalidValue, path, "b"}, + {"value not finite, negative", `{"id":"b","unit":"ms","value":-1e999}`, CodeInvalidValue, path, "b"}, + {"value together with MISSING", `{"id":"b","unit":"ms","value":1,"availability":"MISSING","reason":"timeout"}`, CodeConflictingValue, path, "b"}, + {"neither value nor MISSING", `{"id":"b","unit":"ms"}`, CodeMissingValue, path, "b"}, + {"null value without MISSING", `{"id":"b","unit":"ms","value":null}`, CodeMissingValue, path, "b"}, + {"AVAILABLE without a value", `{"id":"b","unit":"ms","availability":"AVAILABLE"}`, CodeMissingValue, path, "b"}, + {"availability in lower case", `{"id":"b","unit":"ms","value":1,"availability":"available"}`, CodeInvalidAvailability, path, "b"}, + {"availability not a string", `{"id":"b","unit":"ms","value":1,"availability":1}`, CodeInvalidAvailability, path, "b"}, + {"MISSING without a reason", `{"id":"b","unit":"ms","availability":"MISSING"}`, CodeInvalidReason, path, "b"}, + {"MISSING with a malformed reason", `{"id":"b","unit":"ms","availability":"MISSING","reason":"Timed-Out"}`, CodeInvalidReason, path, "b"}, + {"MISSING with a non-string reason", `{"id":"b","unit":"ms","availability":"MISSING","reason":7}`, CodeInvalidReason, path, "b"}, + {"reason on an available value", `{"id":"b","unit":"ms","value":1,"reason":"ok"}`, CodeInvalidReason, path, "b"}, + } + runEntryCases(t, tests, func(entry string) []byte { + return document(`"scalars":[` + keptScalar + `,` + entry + `]`) + }) +} + +//nolint:funlen // table-driven test cases drive the line count. +func TestParseRejectsOnlyTheDefectiveSeries(t *testing.T) { + const path = "series[0]" + withPoints := func(list string) string { return seriesEntry(testAxis + `,"points":` + list) } + tests := []entryCase{ + {"not an object", `"decode_tps"`, CodeInvalidEntry, path, ""}, + {"id invalid", `{"id":"S","unit":"tok/s",` + testAxis + `,"points":[]}`, CodeInvalidID, path, ""}, + {"unit invalid", `{"id":"s","unit":"tok per s",` + testAxis + `,"points":[]}`, CodeInvalidUnit, path, "s"}, + {"axis missing", seriesEntry(`"points":[]`), CodeInvalidAxis, path, "s"}, + {"axis not an object", seriesEntry(`"axis":"step","points":[]`), CodeInvalidAxis, path, "s"}, + {"axis id invalid", seriesEntry(`"axis":{"id":"Context","unit":"token"},"points":[]`), CodeInvalidAxis, path, "s"}, + {"axis unit missing", seriesEntry(`"axis":{"id":"step"},"points":[]`), CodeInvalidAxis, path, "s"}, + {"points missing", seriesEntry(testAxis), CodeInvalidEntry, path, "s"}, + {"points not an array", seriesEntry(testAxis + `,"points":{}`), CodeInvalidEntry, path, "s"}, + {"one past the series point limit", withPoints(points(MaxSeriesPoints + 1)), CodeTooManyPoints, path, "s"}, + {"point not an object", withPoints(`[1]`), CodeInvalidPoint, "series[0].points[0]", "s"}, + {"at missing", withPoints(`[{"value":1}]`), CodeInvalidPoint, "series[0].points[0]", "s"}, + {"at as a string", withPoints(`[{"at":"8192","value":1}]`), CodeInvalidPoint, "series[0].points[0]", "s"}, + {"at not finite", withPoints(`[{"at":1e999,"value":1}]`), CodeInvalidPoint, "series[0].points[0]", "s"}, + {"at repeated", withPoints(`[{"at":1,"value":1},{"at":1,"value":2}]`), CodeInvalidPoint, "series[0].points[1]", "s"}, + {"at decreasing", withPoints(`[{"at":1,"value":1},{"at":2,"value":1},{"at":1.5,"value":1}]`), CodeInvalidPoint, "series[0].points[2]", "s"}, + {"point value as a string", withPoints(`[{"at":1,"value":"fast"}]`), CodeInvalidValue, "series[0].points[0]", "s"}, + {"point value not finite", withPoints(`[{"at":1,"value":1},{"at":2,"value":1e999}]`), CodeInvalidValue, "series[0].points[1]", "s"}, + {"point with neither value nor MISSING", withPoints(`[{"at":1}]`), CodeMissingValue, "series[0].points[0]", "s"}, + {"point MISSING without a reason", withPoints(`[{"at":1,"availability":"MISSING"}]`), CodeInvalidReason, "series[0].points[0]", "s"}, + {"point value together with MISSING", withPoints(`[{"at":1,"value":1,"availability":"MISSING","reason":"timeout"}]`), CodeConflictingValue, "series[0].points[0]", "s"}, + } + runEntryCases(t, tests, func(entry string) []byte { + return document(`"scalars":[` + keptScalar + `],"series":[` + entry + `]`) + }) +} + +func TestParseRejectsEveryEntryCarryingADuplicatedID(t *testing.T) { + raw := document(`"scalars":[{"id":"x","unit":"ms","value":1},` + keptScalar + `,{"id":"x","unit":"bogus unit","value":2}],` + + `"series":[{"id":"x","unit":"tok/s",` + testAxis + `,"points":[]}]`) + set, diagnostics := parseForTest(raw) + if set == nil || len(set.Scalars) != 1 || set.Scalars[0].ID != "kept" || len(set.Series) != 0 { + t.Fatalf("set = %+v; want only the uniquely named sibling", set) + } + want := []Diagnostic{ + {Scope: ScopeEntry, Code: CodeDuplicateID, Path: "scalars[0]", ID: "x"}, + {Scope: ScopeEntry, Code: CodeDuplicateID, Path: "scalars[2]", ID: "x"}, + {Scope: ScopeEntry, Code: CodeDuplicateID, Path: "series[0]", ID: "x"}, + } + if !equalIgnoringDetail(diagnostics, want) { + t.Fatalf("diagnostics = %+v; want %+v", diagnostics, want) + } +} + +func TestParseAllowsAnAxisIDToRepeatAcrossSeries(t *testing.T) { + raw := document(`"series":[{"id":"a","unit":"ms",` + testAxis + `,"points":` + points(2) + `},{"id":"b","unit":"ms",` + testAxis + `,"points":` + points(2) + `}]`) + set, diagnostics := parseForTest(raw) + if set == nil || len(set.Series) != 2 || len(diagnostics) != 0 { + t.Fatalf("set = %+v, diagnostics = %+v; an axis id is not an entry id", set, diagnostics) + } +} + +// TestParseOrdersSeriesPositionsAsFloat64 pins how positions are compared. +// 9007199254740993 is 2^53+1: it has no float64 of its own and reads as 2^53, +// so it repeats the position before it. The same holds for a decimal that +// differs from its neighbor only past float64 precision. 2^53+2 is the next +// float64, so it is a new position, and its literal is kept as sent. +func TestParseOrdersSeriesPositionsAsFloat64(t *testing.T) { + withPositions := func(first, second string) []byte { + return document(`"series":[` + seriesEntry(testAxis+`,"points":[{"at":`+first+`,"value":1},{"at":`+second+`,"value":2}]`) + `]`) + } + + want := []Diagnostic{{Scope: ScopeEntry, Code: CodeInvalidPoint, Path: "series[0].points[1]", ID: "s"}} + for _, pair := range [][2]string{ + {"9007199254740992", "9007199254740993"}, + {"0.1", "0.10000000000000000001"}, + } { + set, diagnostics := parseForTest(withPositions(pair[0], pair[1])) + if set == nil || len(set.Series) != 0 || !equalIgnoringDetail(diagnostics, want) { + t.Errorf("at %s then %s: set = %+v, diagnostics = %+v; want the series rejected with %+v", pair[0], pair[1], set, diagnostics, want) + } + } + + set, diagnostics := parseForTest(withPositions("9007199254740992", "9007199254740994")) + if set == nil || len(diagnostics) != 0 || len(set.Series) != 1 || len(set.Series[0].Points) != 2 { + t.Fatalf("positions distinct as float64: set = %+v, diagnostics = %+v; want the series accepted", set, diagnostics) + } + got := []Point{set.Series[0].Points[0], set.Series[0].Points[1]} + wantPoints := []Point{ + {At: "9007199254740992", Value: "1", Availability: AvailabilityAvailable}, + {At: "9007199254740994", Value: "2", Availability: AvailabilityAvailable}, + } + if !slices.Equal(got, wantPoints) { + t.Fatalf("points = %+v; want the engine's literals %+v", got, wantPoints) + } +} + +func TestParseKeepsMissingValuesMissing(t *testing.T) { + raw := document(`"scalars":[{"id":"ttft","unit":"ms","availability":"MISSING","reason":"not_streamed"},{"id":"retries","unit":"1","value":0}],` + + `"series":[` + seriesEntry(testAxis+`,"points":[{"at":8192,"value":0.0},{"at":16384,"availability":"MISSING","reason":"request_timed_out"}]`) + `]`) + set, diagnostics := parseForTest(raw) + if set == nil || len(diagnostics) != 0 { + t.Fatalf("set = %+v, diagnostics = %+v", set, diagnostics) + } + wantScalars := []Scalar{ + {ID: "ttft", Unit: "ms", Availability: AvailabilityMissing, Reason: "not_streamed"}, + {ID: "retries", Unit: "1", Value: "0", Availability: AvailabilityAvailable}, + } + wantPoints := []Point{ + {At: "8192", Value: "0.0", Availability: AvailabilityAvailable}, + {At: "16384", Availability: AvailabilityMissing, Reason: "request_timed_out"}, + } + if !reflect.DeepEqual(set.Scalars, wantScalars) || !reflect.DeepEqual(set.Series[0].Points, wantPoints) { + t.Fatalf("scalars = %+v, points = %+v", set.Scalars, set.Series[0].Points) + } + + encoded, err := json.Marshal(set) + if err != nil { + t.Fatalf("marshal: %v", err) + } + for _, want := range []string{ + `{"id":"ttft","unit":"ms","availability":"MISSING","reason":"not_streamed"}`, + `{"id":"retries","unit":"1","value":0,"availability":"AVAILABLE"}`, + `{"at":8192,"value":0.0,"availability":"AVAILABLE"}`, + `{"at":16384,"availability":"MISSING","reason":"request_timed_out"}`, + } { + if !strings.Contains(string(encoded), want) { + t.Errorf("encoded set lacks %s\n%s", want, encoded) + } + } +} + +func TestParseKeepsNumberLiteralsAndRoundTrips(t *testing.T) { + raw := document(`"scalars":[{"id":"a","unit":"tok/s","value":200.0},{"id":"b","unit":"token","value":67000},` + + `{"id":"c","unit":"s","value":-1.5e-3},{"id":"d","unit":"byte","value":9007199254740993}]`) + set, diagnostics := parseForTest(raw) + if set == nil || len(diagnostics) != 0 { + t.Fatalf("set = %+v, diagnostics = %+v", set, diagnostics) + } + literals := []string{"200.0", "67000", "-1.5e-3", "9007199254740993"} + for i, want := range literals { + if got := set.Scalars[i].Value.String(); got != want { + t.Errorf("scalar %d value = %s; want the engine's literal %s", i, got, want) + } + } + + encoded, err := json.Marshal(set) + if err != nil { + t.Fatalf("marshal: %v", err) + } + var decoded Set + if err := json.Unmarshal(encoded, &decoded); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if !reflect.DeepEqual(&decoded, set) { + t.Fatalf("round trip changed the set\n got: %+v\nwant: %+v", &decoded, set) + } +} + +func TestParseTreatsNullFieldsAsOmitted(t *testing.T) { + raw := []byte(`{"schema_version":1,"provenance":{"producer":"harness","producer_version":null,"measured_at":null,"subject":null,"method":null},` + + `"scalars":[{"id":"a","unit":"ms","value":1,"availability":null,"reason":null,"description":null},` + + `{"id":"b","unit":"ms","value":null,"availability":"MISSING","reason":"not_measured"}],"series":null}`) + set, diagnostics := parseForTest(raw) + if set == nil || len(diagnostics) != 0 { + t.Fatalf("set = %+v, diagnostics = %+v", set, diagnostics) + } + want := []Scalar{ + {ID: "a", Unit: "ms", Value: "1", Availability: AvailabilityAvailable}, + {ID: "b", Unit: "ms", Availability: AvailabilityMissing, Reason: "not_measured"}, + } + if !reflect.DeepEqual(set.Scalars, want) { + t.Fatalf("scalars = %+v; want %+v", set.Scalars, want) + } +} + +func TestParseMasksEngineText(t *testing.T) { + const secret = "s3cr3t-token-value" + mask := func(text string) string { return strings.ReplaceAll(text, secret, "***REDACTED***") } + raw := []byte(`{"schema_version":1,"provenance":{"producer":"harness ` + secret + `","producer_version":"` + secret + `","subject":"key=` + secret + `","method":"used ` + secret + `"},` + + `"scalars":[{"id":"a","unit":"ms","value":1,"description":"saw ` + secret + `"},` + + `{"id":"s3cr3t-token-value","unit":"ms","value":1},` + + `{"id":"c","unit":"` + secret + `","value":1},` + + `{"id":"d","unit":"ms","availability":"MISSING","reason":"s3cr3t_token_value"}]}`) + maskReason := func(text string) string { + return strings.ReplaceAll(mask(text), "s3cr3t_token_value", "***REDACTED***") + } + set, diagnostics := Parse(raw, Options{Engine: "e", Transport: "http", Mask: maskReason}) + encoded, err := json.Marshal(struct { + Set *Set `json:"set"` + Diagnostics []Diagnostic `json:"diagnostics"` + }{set, diagnostics}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if strings.Contains(string(encoded), secret) || strings.Contains(string(encoded), "s3cr3t_token_value") { + t.Fatalf("a secret survived masking: %s", encoded) + } + wantProvenance := Provenance{ + Producer: "harness ***REDACTED***", ProducerVersion: "***REDACTED***", + Subject: "key=***REDACTED***", Method: "used ***REDACTED***", + } + if set == nil || set.Provenance != wantProvenance { + t.Fatalf("provenance = %+v; want %+v", set, wantProvenance) + } + wantScalars := []Scalar{ + {ID: "a", Unit: "ms", Value: "1", Availability: AvailabilityAvailable, Description: "saw ***REDACTED***"}, + {ID: "c", Unit: "***REDACTED***", Value: "1", Availability: AvailabilityAvailable}, + } + if !reflect.DeepEqual(set.Scalars, wantScalars) { + t.Errorf("scalars = %+v; want %+v", set.Scalars, wantScalars) + } + wantDiagnostics := []Diagnostic{ + {Scope: ScopeEntry, Code: CodeInvalidID, Path: "scalars[1]"}, + {Scope: ScopeEntry, Code: CodeInvalidReason, Path: "scalars[3]", ID: "d"}, + } + if !equalIgnoringDetail(diagnostics, wantDiagnostics) { + t.Errorf("diagnostics = %+v; want %+v", diagnostics, wantDiagnostics) + } +} + +func TestDiagnosticsNeverEchoRejectedText(t *testing.T) { + const marker = "ENGINE-CONTROLLED-TEXT" + inputs := [][]byte{ + document(`"scalars":[{"id":"` + marker + `","unit":"ms","value":1}]`), + document(`"scalars":[{"id":"a","unit":"` + marker + ` unit","value":1}]`), + document(`"scalars":[{"id":"a","unit":"ms","availability":"MISSING","reason":"` + marker + `"}]`), + document(`"scalars":[{"id":"a","unit":"ms","value":"` + marker + `"}]`), + document(`"` + marker + `":1`), + withProvenance(`{"producer":"p","measured_at":"` + marker + `"}`), + } + for _, raw := range inputs { + _, diagnostics := parseForTest(raw) + if len(diagnostics) != 1 { + t.Fatalf("Parse(%s) diagnostics = %+v; want exactly one", raw, diagnostics) + } + encoded, err := json.Marshal(diagnostics) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if strings.Contains(string(encoded), marker) { + t.Errorf("diagnostic echoes rejected engine text: %s", encoded) + } + } +} diff --git a/internal/measurement/testdata/decode_sweep.json b/internal/measurement/testdata/decode_sweep.json new file mode 100644 index 00000000..0fdd3b7e --- /dev/null +++ b/internal/measurement/testdata/decode_sweep.json @@ -0,0 +1,54 @@ +{ + "schema_version": 1, + "provenance": { + "producer": "dsh-eval-harness", + "producer_version": "e90c255", + "measured_at": "2026-11-17T08:00:00Z", + "subject": "provider=example model=example-model (the deployment as measured, not the architecture)", + "method": "Streaming requests at nominal context steps; a per-request nonce defeats prefix caching; temperature 0, max_tokens 256; median of 3 repeats per step." + }, + "scalars": [ + { + "id": "baseline_decode_tps", + "unit": "tok/s", + "value": 200.0, + "description": "1/a of the least-squares fit tps(n) = 1/(a + b*n)" + }, + { + "id": "half_speed_context", + "unit": "token", + "value": 67000, + "description": "context length where the fitted speed is half of baseline" + } + ], + "series": [ + { + "id": "decode_tps", + "unit": "tok/s", + "description": "median decode speed at each requested context length", + "axis": {"id": "requested_context_tokens", "unit": "token"}, + "points": [ + {"at": 8192, "value": 178.2}, + {"at": 16384, "value": 160.7}, + {"at": 32768, "value": 134.3}, + {"at": 65536, "value": 101.1}, + {"at": 131072, "value": 67.7}, + {"at": 262144, "availability": "MISSING", "reason": "request_timed_out"} + ] + }, + { + "id": "observed_input_tokens", + "unit": "token", + "description": "input tokens the provider reported for each request", + "axis": {"id": "requested_context_tokens", "unit": "token"}, + "points": [ + {"at": 8192, "value": 8201}, + {"at": 16384, "value": 16390}, + {"at": 32768, "value": 32779}, + {"at": 65536, "value": 65541}, + {"at": 131072, "value": 131080}, + {"at": 262144, "availability": "MISSING", "reason": "request_timed_out"} + ] + } + ] +} diff --git a/internal/measurement/validate.go b/internal/measurement/validate.go new file mode 100644 index 00000000..4fedbf0d --- /dev/null +++ b/internal/measurement/validate.go @@ -0,0 +1,467 @@ +package measurement + +import ( + "encoding/json" + "math" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +var ( + // idPattern is the judge-id pattern; measurement ids live in their own + // namespace but follow the same spelling rules. + idPattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,63}$`) + // unitPattern accepts an opaque, case-sensitive unit label. skill-up never + // converts units, so the label is only checked for shape. + unitPattern = regexp.MustCompile(`^[A-Za-z0-9/%._^*-]{1,32}$`) + reasonPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) +) + +const ( + fieldSchemaVersion = "schema_version" + fieldProvenance = "provenance" + fieldScalars = "scalars" + fieldSeries = "series" + fieldID = "id" + fieldUnit = "unit" + fieldValue = "value" + fieldAvailability = "availability" + fieldReason = "reason" + fieldDescription = "description" + fieldAxis = "axis" + fieldPoints = "points" + fieldAt = "at" + fieldProducer = "producer" + fieldMeasuredAt = "measured_at" +) + +var ( + rootFields = fieldSet(fieldSchemaVersion, fieldProvenance, fieldScalars, fieldSeries) + provenanceFields = fieldSet(fieldProducer, "producer_version", fieldMeasuredAt, "subject", "method") + scalarFields = fieldSet(fieldID, fieldUnit, fieldValue, fieldAvailability, fieldReason, fieldDescription) + seriesFields = fieldSet(fieldID, fieldUnit, fieldDescription, fieldAxis, fieldPoints) + axisFields = fieldSet(fieldID, fieldUnit) + pointFields = fieldSet(fieldAt, fieldValue, fieldAvailability, fieldReason) +) + +func fieldSet(names ...string) map[string]struct{} { + set := make(map[string]struct{}, len(names)) + for _, name := range names { + set[name] = struct{}{} + } + return set +} + +// parser validates one decoded measurements object. mask is applied to every +// engine-supplied string before it is checked, so a label that embeds a secret +// either fails its pattern or is stored redacted — never stored verbatim. +type parser struct { + mask func(string) string +} + +// parseObject runs the checks that reject the object as a whole and returns its +// validated provenance and its raw entry lists. +func (p parser) parseObject(root map[string]any) (provenance Provenance, scalars, series []any, rejection *Diagnostic) { + if path, found := unknownFieldPath(root); found { + return Provenance{}, nil, nil, rejectObject(CodeUnknownField, path, "") + } + if !supportedSchemaVersion(root[fieldSchemaVersion]) { + return Provenance{}, nil, nil, rejectObject(CodeUnsupportedSchemaVersion, fieldSchemaVersion, + "schema_version must be "+strconv.Itoa(SchemaVersion)) + } + provenance, rejection = p.parseProvenance(root[fieldProvenance]) + if rejection != nil { + return Provenance{}, nil, nil, rejection + } + scalars, scalarsOK := entryList(root[fieldScalars]) + series, seriesOK := entryList(root[fieldSeries]) + if !scalarsOK || !seriesOK { + return Provenance{}, nil, nil, rejectObject(CodeInvalidStructure, "", "scalars and series must be arrays") + } + if rejection = checkCounts(scalars, series); rejection != nil { + return Provenance{}, nil, nil, rejection + } + return provenance, scalars, series, nil +} + +// unknownFieldPath returns the path of the first object carrying a field +// outside the contract. Objects are visited in a fixed order — the root, then +// provenance, scalars and series by index — so the result does not depend on +// map iteration order. +func unknownFieldPath(root map[string]any) (path string, found bool) { + if hasUnknownField(root, rootFields) { + return "", true + } + if provenance, ok := root[fieldProvenance].(map[string]any); ok && hasUnknownField(provenance, provenanceFields) { + return fieldProvenance, true + } + scalars, _ := root[fieldScalars].([]any) + for index, item := range scalars { + if entry, ok := item.(map[string]any); ok && hasUnknownField(entry, scalarFields) { + return indexPath(fieldScalars, index), true + } + } + series, _ := root[fieldSeries].([]any) + for index, item := range series { + entry, ok := item.(map[string]any) + if !ok { + continue + } + if entryPath, entryFound := unknownSeriesFieldPath(indexPath(fieldSeries, index), entry); entryFound { + return entryPath, true + } + } + return "", false +} + +func unknownSeriesFieldPath(path string, entry map[string]any) (unknownPath string, found bool) { + if hasUnknownField(entry, seriesFields) { + return path, true + } + if axis, ok := entry[fieldAxis].(map[string]any); ok && hasUnknownField(axis, axisFields) { + return path + "." + fieldAxis, true + } + points, _ := entry[fieldPoints].([]any) + for index, item := range points { + if point, ok := item.(map[string]any); ok && hasUnknownField(point, pointFields) { + return indexPath(path+"."+fieldPoints, index), true + } + } + return "", false +} + +func hasUnknownField(object map[string]any, allowed map[string]struct{}) bool { + for name := range object { + if _, ok := allowed[name]; !ok { + return true + } + } + return false +} + +func supportedSchemaVersion(value any) bool { + _, parsed, ok := finiteNumber(value) + return ok && parsed == SchemaVersion +} + +// parseProvenance validates the engine's provenance block. Length limits apply +// to the text as the engine sent it; the stored text is the masked form. +func (p parser) parseProvenance(value any) (Provenance, *Diagnostic) { + object, ok := value.(map[string]any) + if !ok { + return Provenance{}, rejectObject(CodeInvalidProvenance, fieldProvenance, "provenance is required and must be an object") + } + var out Provenance + fields := []struct { + name string + dest *string + maxBytes int + }{ + {fieldProducer, &out.Producer, 0}, + {"producer_version", &out.ProducerVersion, MaxSubjectBytes}, + {fieldMeasuredAt, &out.MeasuredAt, 0}, + {"subject", &out.Subject, MaxSubjectBytes}, + {"method", &out.Method, MaxMethodBytes}, + } + for _, field := range fields { + text, isText := optionalText(object, field.name) + if !isText { + return Provenance{}, rejectObject(CodeInvalidProvenance, fieldProvenance+"."+field.name, "must be a string") + } + if field.maxBytes > 0 && len(text) > field.maxBytes { + return Provenance{}, rejectObject(CodeInvalidProvenance, fieldProvenance+"."+field.name, + "must be at most "+strconv.Itoa(field.maxBytes)+" bytes") + } + *field.dest = text + } + if strings.TrimSpace(out.Producer) == "" || utf8.RuneCountInString(out.Producer) > MaxProducerChars { + return Provenance{}, rejectObject(CodeInvalidProvenance, fieldProvenance+"."+fieldProducer, + "producer is required and must be 1 to "+strconv.Itoa(MaxProducerChars)+" characters") + } + for _, field := range fields { + *field.dest = p.mask(*field.dest) + } + if out.MeasuredAt != "" { + if _, err := time.Parse(time.RFC3339, out.MeasuredAt); err != nil { + return Provenance{}, rejectObject(CodeInvalidProvenance, fieldProvenance+"."+fieldMeasuredAt, "must be an RFC 3339 timestamp") + } + } + return out, nil +} + +// optionalText reads an optional string field. An absent field and a JSON null +// both read as the empty string. +func optionalText(object map[string]any, name string) (text string, ok bool) { + value, present := object[name] + if !present || value == nil { + return "", true + } + text, ok = value.(string) + return text, ok +} + +// entryList reads the scalars or series list. An absent field and a JSON null +// both read as an empty list. +func entryList(value any) (items []any, ok bool) { + if value == nil { + return nil, true + } + items, ok = value.([]any) + return items, ok +} + +// checkCounts enforces the whole-object limits. Points are counted as the +// engine sent them, before any series is validated or rejected. +func checkCounts(scalars, series []any) *Diagnostic { + if len(scalars)+len(series) > MaxEntries { + return rejectObject(CodeTooManyEntries, "", "scalars and series together exceed "+strconv.Itoa(MaxEntries)+" entries") + } + total := 0 + for _, item := range series { + entry, ok := item.(map[string]any) + if !ok { + continue + } + points, _ := entry[fieldPoints].([]any) + total += len(points) + } + if total > MaxTotalPoints { + return rejectObject(CodeTooManyPoints, fieldSeries, "series together exceed "+strconv.Itoa(MaxTotalPoints)+" points") + } + return nil +} + +// idCounts counts how many entries carry each well-formed id, across scalars +// and series together. An id carried more than once is ambiguous, so every +// entry carrying it is rejected. +func (p parser) idCounts(lists ...[]any) map[string]int { + counts := make(map[string]int) + for _, list := range lists { + for _, item := range list { + entry, ok := item.(map[string]any) + if !ok { + continue + } + if id, valid := p.label(entry[fieldID], idPattern); valid { + counts[id]++ + } + } + } + return counts +} + +// label reads a required string that must match pattern once masked. +func (p parser) label(value any, pattern *regexp.Regexp) (label string, ok bool) { + raw, isText := value.(string) + if !isText { + return "", false + } + masked := p.mask(raw) + return masked, pattern.MatchString(masked) +} + +// entryHead is what a scalar and a series have in common. +type entryHead struct { + id string + unit string + description string +} + +func (p parser) parseHead(path string, entry map[string]any, counts map[string]int) (entryHead, *Diagnostic) { + id, ok := p.label(entry[fieldID], idPattern) + if !ok { + return entryHead{}, rejectEntry(CodeInvalidID, path, "", "") + } + if counts[id] > 1 { + return entryHead{}, rejectEntry(CodeDuplicateID, path, id, "") + } + unit, ok := p.label(entry[fieldUnit], unitPattern) + if !ok { + return entryHead{}, rejectEntry(CodeInvalidUnit, path, id, "") + } + description, ok := optionalText(entry, fieldDescription) + if !ok { + return entryHead{}, rejectEntry(CodeInvalidEntry, path, id, "description must be a string") + } + if len(description) > MaxDescriptionBytes { + return entryHead{}, rejectEntry(CodeDescriptionTooLong, path, id, "") + } + return entryHead{id: id, unit: unit, description: p.mask(description)}, nil +} + +func (p parser) parseScalar(index int, item any, counts map[string]int) (Scalar, *Diagnostic) { + path := indexPath(fieldScalars, index) + entry, ok := item.(map[string]any) + if !ok { + return Scalar{}, rejectEntry(CodeInvalidEntry, path, "", "entry must be an object") + } + head, rejection := p.parseHead(path, entry, counts) + if rejection != nil { + return Scalar{}, rejection + } + observed, code := p.parseObservation(entry) + if code != "" { + return Scalar{}, rejectEntry(code, path, head.id, "") + } + return Scalar{ + ID: head.id, Unit: head.unit, Description: head.description, + Value: observed.value, Availability: observed.availability, Reason: observed.reason, + }, nil +} + +func (p parser) parseSeries(index int, item any, counts map[string]int) (Series, *Diagnostic) { + path := indexPath(fieldSeries, index) + entry, ok := item.(map[string]any) + if !ok { + return Series{}, rejectEntry(CodeInvalidEntry, path, "", "entry must be an object") + } + head, rejection := p.parseHead(path, entry, counts) + if rejection != nil { + return Series{}, rejection + } + axis, ok := p.parseAxis(entry[fieldAxis]) + if !ok { + return Series{}, rejectEntry(CodeInvalidAxis, path, head.id, "") + } + rawPoints, ok := entry[fieldPoints].([]any) + if !ok { + return Series{}, rejectEntry(CodeInvalidEntry, path, head.id, "points must be an array") + } + if len(rawPoints) > MaxSeriesPoints { + return Series{}, rejectEntry(CodeTooManyPoints, path, head.id, "") + } + points, defect := p.parsePoints(rawPoints) + if defect != nil { + return Series{}, rejectEntry(defect.code, indexPath(path+"."+fieldPoints, defect.index), head.id, defect.detail) + } + return Series{ID: head.id, Unit: head.unit, Description: head.description, Axis: axis, Points: points}, nil +} + +func (p parser) parseAxis(value any) (Axis, bool) { + object, ok := value.(map[string]any) + if !ok { + return Axis{}, false + } + id, ok := p.label(object[fieldID], idPattern) + if !ok { + return Axis{}, false + } + unit, ok := p.label(object[fieldUnit], unitPattern) + return Axis{ID: id, Unit: unit}, ok +} + +// pointDefect describes the first bad point of a series; one bad point rejects +// the series, because a series with a hole no longer means what was measured. +type pointDefect struct { + index int + code string + detail string +} + +// parsePoints validates the points of one series in order. Positions are +// compared as float64 values, which is how most JSON consumers read numbers. +// Two literals that are distinct as decimals but convert to the same float64 +// (9007199254740992 and 9007199254740993) are therefore the same position, and +// the series is rejected rather than stored with two points that such a +// consumer could not tell apart. +func (p parser) parsePoints(rawPoints []any) ([]Point, *pointDefect) { + points := make([]Point, 0, len(rawPoints)) + previous := math.Inf(-1) + for index, item := range rawPoints { + point, at, defect := p.parsePoint(item) + if defect == nil && at <= previous { + defect = &pointDefect{code: CodeInvalidPoint, detail: "at must be strictly increasing when read as a float64"} + } + if defect != nil { + defect.index = index + return nil, defect + } + previous = at + points = append(points, point) + } + return points, nil +} + +func (p parser) parsePoint(item any) (point Point, at float64, defect *pointDefect) { + object, ok := item.(map[string]any) + if !ok { + return Point{}, 0, &pointDefect{code: CodeInvalidPoint, detail: "point must be an object"} + } + position, at, ok := finiteNumber(object[fieldAt]) + if !ok { + return Point{}, 0, &pointDefect{code: CodeInvalidPoint, detail: "at must be a finite number"} + } + observed, code := p.parseObservation(object) + if code != "" { + return Point{}, 0, &pointDefect{code: code} + } + return Point{At: position, Value: observed.value, Availability: observed.availability, Reason: observed.reason}, at, nil +} + +// observation is the value part shared by a scalar and a point. +type observation struct { + value json.Number + availability string + reason string +} + +// parseObservation applies the value grammar shared by scalars and points: a +// finite number, optionally tagged AVAILABLE, or MISSING with a reason code and +// no value. It returns a diagnostic code when the grammar is violated. A +// missing value is kept as missing; it is never turned into a number. +func (p parser) parseObservation(object map[string]any) (observation, string) { + availability, code := availabilityOf(object) + if code != "" { + return observation{}, code + } + rawValue := object[fieldValue] + switch { + case availability == AvailabilityMissing && rawValue != nil: + return observation{}, CodeConflictingValue + case availability == AvailabilityMissing: + reason, ok := p.label(object[fieldReason], reasonPattern) + if !ok { + return observation{}, CodeInvalidReason + } + return observation{availability: AvailabilityMissing, reason: reason}, "" + case rawValue == nil: + return observation{}, CodeMissingValue + case object[fieldReason] != nil: + return observation{}, CodeInvalidReason + } + value, _, ok := finiteNumber(rawValue) + if !ok { + return observation{}, CodeInvalidValue + } + return observation{value: value, availability: AvailabilityAvailable}, "" +} + +func availabilityOf(object map[string]any) (availability, code string) { + value := object[fieldAvailability] + if value == nil { + return "", "" + } + text, ok := value.(string) + if !ok || (text != AvailabilityAvailable && text != AvailabilityMissing) { + return "", CodeInvalidAvailability + } + return text, "" +} + +// finiteNumber reports whether value is a JSON number that fits a finite +// float64. It returns the engine's literal so the stored value is exactly what +// was reported. +func finiteNumber(value any) (literal json.Number, parsed float64, ok bool) { + number, isNumber := value.(json.Number) + if !isNumber { + return "", 0, false + } + parsed, err := strconv.ParseFloat(number.String(), 64) + if err != nil || math.IsInf(parsed, 0) || math.IsNaN(parsed) { + return "", 0, false + } + return number, parsed, true +} diff --git a/internal/report/html.go b/internal/report/html.go index 34e6c7c9..8a983df9 100644 --- a/internal/report/html.go +++ b/internal/report/html.go @@ -261,7 +261,17 @@ func caseTurnResultsToEmbedded(turns []CaseTurnResult) []embeddedTurn { } out := make([]embeddedTurn, len(turns)) for i, tr := range turns { - out[i] = embeddedTurn(tr) + // Copied field by field: engine measurements on a turn are not part of + // the HTML report's embedded data. + out[i] = embeddedTurn{ + TurnNumber: tr.TurnNumber, + Content: tr.Content, + Source: tr.Source, + Response: tr.Response, + Status: tr.Status, + Reason: tr.Reason, + StopReason: tr.StopReason, + } } return out } diff --git a/internal/report/reporter.go b/internal/report/reporter.go index a6b492e6..94fb84f3 100644 --- a/internal/report/reporter.go +++ b/internal/report/reporter.go @@ -7,6 +7,7 @@ import ( "time" "github.com/alibaba/skill-up/internal/judge" + "github.com/alibaba/skill-up/internal/measurement" ) // Reporter writes evaluation output to a chosen format. @@ -162,6 +163,13 @@ type CaseResult struct { ObservedModel string `json:"observed_model,omitempty"` // model explicitly reported by the agent ObservedVersion string `json:"observed_version,omitempty"` // CLI version reported by static runtime inspection TurnResults []CaseTurnResult `json:"turn_results,omitempty"` // per-turn outcomes; nil for single-turn + + // EngineMeasurements holds the runtime measurements a custom engine + // reported for this case, and EngineMeasurementDiagnostics every rejection + // among them. A multi-turn case carries them on the turn that reported them + // instead. Both are informational and never affect Status. + EngineMeasurements *measurement.Set `json:"engine_measurements,omitempty"` + EngineMeasurementDiagnostics []measurement.Diagnostic `json:"engine_measurement_diagnostics,omitempty"` } // CaseTurnResult holds the outcome of a single turn for reporting purposes. @@ -173,6 +181,11 @@ type CaseTurnResult struct { Status string `json:"status"` Reason string `json:"reason,omitempty"` StopReason string `json:"stop_reason,omitempty"` + + // EngineMeasurements and EngineMeasurementDiagnostics are the measurements + // this turn's SessionResult reported; they are never merged across turns. + EngineMeasurements *measurement.Set `json:"engine_measurements,omitempty"` + EngineMeasurementDiagnostics []measurement.Diagnostic `json:"engine_measurement_diagnostics,omitempty"` } // BenchmarkResult is the top-level structure for benchmark.json. diff --git a/internal/runner/runner.go b/internal/runner/runner.go index 8b4fafe8..6d06ddf6 100644 --- a/internal/runner/runner.go +++ b/internal/runner/runner.go @@ -831,6 +831,12 @@ func evalResultToCaseResult(res *evaluator.EvalResult) report.CaseResult { ObservedVersion: res.Version, TurnResults: evalTurnResultsToReport(res.TurnResults), } + // A multi-turn case keeps engine measurements on the turn that reported + // them; only a single-turn case carries them on the case itself. + if res.SessionResult != nil && len(res.TurnResults) == 0 { + cr.EngineMeasurements = res.Measurements + cr.EngineMeasurementDiagnostics = res.MeasurementDiagnostics + } judgeSession := res.JudgeSession if judgeSession == nil && res.Grading != nil { judgeSession = res.Grading.JudgeSession @@ -871,6 +877,10 @@ func evalTurnResultsToReport(turns []evaluator.TurnResult) []report.CaseTurnResu Reason: tr.Reason, StopReason: tr.StopReason, } + if tr.SessionResult != nil { + out[i].EngineMeasurements = tr.SessionResult.Measurements + out[i].EngineMeasurementDiagnostics = tr.SessionResult.MeasurementDiagnostics + } } return out } diff --git a/internal/runner/runner_measurements_test.go b/internal/runner/runner_measurements_test.go new file mode 100644 index 00000000..a09b2a83 --- /dev/null +++ b/internal/runner/runner_measurements_test.go @@ -0,0 +1,283 @@ +package runner + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/alibaba/skill-up/internal/agent" + "github.com/alibaba/skill-up/internal/config" + "github.com/alibaba/skill-up/internal/credential" + "github.com/alibaba/skill-up/internal/evaluator" + "github.com/alibaba/skill-up/internal/judge" + "github.com/alibaba/skill-up/internal/measurement" + "github.com/alibaba/skill-up/internal/report" +) + +func fixtureGrading(status judge.Status) *judge.Result { + passed := 0 + if status == judge.StatusPass { + passed = 1 + } + return &judge.Result{ + Status: status, + AssertionResults: []judge.AssertionResult{{Text: "output correct", Passed: status == judge.StatusPass, Evidence: "checked"}}, + Summary: judge.ResultSummary{Passed: passed, Failed: 1 - passed, Total: 1, PassRate: float64(passed)}, + } +} + +// fixtureMetrics returns the named-metric state a judge leaves on a case: one +// planned slot with an accepted score. +func fixtureMetrics() *judge.MetricsEnvelope { + score := 0.8 + return &judge.MetricsEnvelope{ + JudgeID: "quality", + Metrics: []judge.MetricResult{{MetricID: "correctness", Availability: judge.Available, Value: &score, Evidence: []string{"matched"}}}, + Quality: judge.QualityNotConfigured, + Coverage: judge.Coverage{Planned: 1, Available: 1}, + } +} + +// plainResults returns three evaluated cases — a passing single-turn case that +// also carries judge-reported named metrics, a failing single-turn case and a +// passing two-turn case — none of which carries engine measurements. +func plainResults() []evaluator.EvalResult { + return []evaluator.EvalResult{ + { + CaseID: "single", CaseName: "Single turn", Prompt: "run the sweep", Status: judge.StatusPass, + SessionResult: &agent.SessionResult{FinalMessage: "sweep finished", DurationMs: 1500, Turns: 1, InputTokens: 10, OutputTokens: 5}, + TurnsTotal: 1, Configuration: "with_skill", Grading: fixtureGrading(judge.StatusPass), + Execution: &judge.ExecutionMetadata{Stage: judge.StageFinished, Completion: judge.CompletionFinished, Cause: judge.CauseNone}, + Metrics: fixtureMetrics(), + }, + { + CaseID: "rejected", CaseName: "Rejected measurements", Prompt: "run it", Status: judge.StatusFail, + SessionResult: &agent.SessionResult{FinalMessage: "wrong answer", DurationMs: 800, Turns: 1, InputTokens: 7, OutputTokens: 3}, + TurnsTotal: 1, Configuration: "with_skill", Grading: fixtureGrading(judge.StatusFail), + }, + { + CaseID: "multi", CaseName: "Two turns", Prompt: "first", Status: judge.StatusPass, + SessionResult: &agent.SessionResult{FinalMessage: "second reply", DurationMs: 2000, Turns: 2, InputTokens: 20, OutputTokens: 8}, + TurnsTotal: 2, Configuration: "with_skill", Grading: fixtureGrading(judge.StatusPass), + TurnResults: []evaluator.TurnResult{ + {TurnNumber: 1, Content: "first", Response: "first reply", Status: evaluator.TurnCompleted, SessionResult: &agent.SessionResult{FinalMessage: "first reply"}}, + {TurnNumber: 2, Content: "second", Response: "second reply", Status: evaluator.TurnCompleted, SessionResult: &agent.SessionResult{FinalMessage: "second reply"}}, + }, + }, + } +} + +func fixtureMeasurements(value json.Number) *measurement.Set { + return &measurement.Set{ + SchemaVersion: measurement.SchemaVersion, + Source: measurement.Source{Engine: "tps-harness", Transport: "local", Trust: measurement.TrustEngineReported}, + Provenance: measurement.Provenance{Producer: "harness"}, + Scalars: []measurement.Scalar{ + {ID: "ttft", Unit: "ms", Value: value, Availability: measurement.AvailabilityAvailable}, + {ID: "decode_tps", Unit: "tok/s", Availability: measurement.AvailabilityMissing, Reason: "not_streamed"}, + }, + } +} + +// measuredResults returns plainResults with engine measurements attached: valid +// ones on the single-turn case, a whole-object rejection on the failing case, +// and per-turn measurements on the two-turn case. The two-turn case also gets +// measurements on its aggregate session, which must not surface on the case. +func measuredResults() []evaluator.EvalResult { + results := plainResults() + results[0].Measurements = fixtureMeasurements("11") + results[1].MeasurementDiagnostics = []measurement.Diagnostic{{Scope: measurement.ScopeObject, Code: measurement.CodeNotAnObject}} + multi := &results[2] + multi.Measurements = fixtureMeasurements("99") + multi.TurnResults[0].SessionResult.Measurements = fixtureMeasurements("21") + multi.TurnResults[1].SessionResult.Measurements = fixtureMeasurements("22") + multi.TurnResults[1].SessionResult.MeasurementDiagnostics = []measurement.Diagnostic{ + {Scope: measurement.ScopeEntry, Code: measurement.CodeInvalidUnit, Path: "scalars[2]", ID: "bad"}, + } + return results +} + +// writeFixtureResults writes results with every report format and returns the +// iteration directory. +func writeFixtureResults(t *testing.T, results []evaluator.EvalResult) string { + t.Helper() + r := NewRunner(&config.EvalConfig{}, nil, nil, credential.ResolvedAgentConfig{}) + if err := r.InitWorkspace(t.TempDir(), "test-skill", 1); err != nil { + t.Fatalf("InitWorkspace: %v", err) + } + if err := r.WriteResults(t.Context(), results, "test-skill", "/path/to/skill", 1, []string{"json", "junit", "html"}, time.Time{}, time.Time{}); err != nil { + t.Fatalf("WriteResults: %v", err) + } + return r.workspace.IterationDir() +} + +func readFixtureFile(t *testing.T, dir, name string) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(name))) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + return data +} + +func readReportInput(t *testing.T, dir, name string) report.Input { + t.Helper() + var input report.Input + if err := json.Unmarshal(readFixtureFile(t, dir, name), &input); err != nil { + t.Fatalf("parse %s: %v", name, err) + } + return input +} + +func scalarValue(set *measurement.Set) string { + if set == nil || len(set.Scalars) == 0 { + return "" + } + return set.Scalars[0].Value.String() +} + +func TestWriteResults_EngineMeasurementsLandWhereTheyWereReported(t *testing.T) { + dir := writeFixtureResults(t, measuredResults()) + for _, name := range []string{"result.json", "report.json"} { + input := readReportInput(t, dir, name) + if len(input.CaseResults) != 3 { + t.Fatalf("%s: case results = %d; want 3", name, len(input.CaseResults)) + } + single, rejected, multi := input.CaseResults[0], input.CaseResults[1], input.CaseResults[2] + + if !reflect.DeepEqual(single.EngineMeasurements, fixtureMeasurements("11")) || single.EngineMeasurementDiagnostics != nil { + t.Errorf("%s: single-turn case = %+v / %+v; want its measurements on the case", name, single.EngineMeasurements, single.EngineMeasurementDiagnostics) + } + if rejected.EngineMeasurements != nil || len(rejected.EngineMeasurementDiagnostics) != 1 || + rejected.EngineMeasurementDiagnostics[0].Code != measurement.CodeNotAnObject { + t.Errorf("%s: rejected case = %+v / %+v; want only the diagnostic", name, rejected.EngineMeasurements, rejected.EngineMeasurementDiagnostics) + } + if multi.EngineMeasurements != nil || multi.EngineMeasurementDiagnostics != nil { + t.Errorf("%s: multi-turn case carries %+v on the case; want them on its turns only", name, multi.EngineMeasurements) + } + if len(multi.TurnResults) != 2 { + t.Fatalf("%s: turn results = %d; want 2", name, len(multi.TurnResults)) + } + first, second := multi.TurnResults[0], multi.TurnResults[1] + if scalarValue(first.EngineMeasurements) != "21" || first.EngineMeasurementDiagnostics != nil { + t.Errorf("%s: turn 1 = %+v / %+v; want its own measurements", name, first.EngineMeasurements, first.EngineMeasurementDiagnostics) + } + if scalarValue(second.EngineMeasurements) != "22" || len(second.EngineMeasurementDiagnostics) != 1 { + t.Errorf("%s: turn 2 = %+v / %+v; want its own measurements and diagnostic", name, second.EngineMeasurements, second.EngineMeasurementDiagnostics) + } + } +} + +func TestWriteResults_MissingMeasurementIsWrittenWithoutAValue(t *testing.T) { + dir := writeFixtureResults(t, measuredResults()) + data := readFixtureFile(t, dir, "result.json") + var compact bytes.Buffer + if err := json.Compact(&compact, data); err != nil { + t.Fatalf("compact result.json: %v", err) + } + want := `{"id":"decode_tps","unit":"tok/s","availability":"MISSING","reason":"not_streamed"}` + if !strings.Contains(compact.String(), want) { + t.Fatalf("result.json lacks the missing scalar as %s", want) + } +} + +// stripMeasurements removes the two engine measurement fields from a decoded +// JSON document, at every level. +func stripMeasurements(value any) any { + switch typed := value.(type) { + case map[string]any: + delete(typed, "engine_measurements") + delete(typed, "engine_measurement_diagnostics") + for key, item := range typed { + typed[key] = stripMeasurements(item) + } + case []any: + for i, item := range typed { + typed[i] = stripMeasurements(item) + } + } + return value +} + +func decodeJSON(t *testing.T, data []byte) any { + t.Helper() + var value any + if err := json.Unmarshal(data, &value); err != nil { + t.Fatalf("decode JSON: %v", err) + } + return value +} + +// TestWriteResults_MeasurementsChangeNothingElse writes the same cases with and +// without engine measurements. A run without them must not mention them at all, +// and a run with them must differ from it only by the two measurement fields: +// verdicts, token counts, grading, judge-reported named-metric states, the +// benchmark and the derived reports stay identical, also when the measurements +// were rejected. +func TestWriteResults_MeasurementsChangeNothingElse(t *testing.T) { + plainDir := writeFixtureResults(t, plainResults()) + measuredDir := writeFixtureResults(t, measuredResults()) + + for _, name := range []string{"result.json", "report.json"} { + plain := readFixtureFile(t, plainDir, name) + if bytes.Contains(plain, []byte("engine_measurement")) { + t.Errorf("%s mentions engine measurements although no engine reported any", name) + } + if !bytes.Contains(plain, []byte(`"metric_quality_state"`)) { + t.Fatalf("%s lacks the named-metric state; the comparison below would not cover it", name) + } + measured := readFixtureFile(t, measuredDir, name) + if !bytes.Contains(measured, []byte(`"engine_measurements"`)) || !bytes.Contains(measured, []byte(`"engine_measurement_diagnostics"`)) { + t.Fatalf("%s lacks the measurement fields; the comparison below would be vacuous", name) + } + if !reflect.DeepEqual(stripMeasurements(decodeJSON(t, measured)), decodeJSON(t, plain)) { + t.Errorf("%s differs beyond the measurement fields", name) + } + } + + identical := []string{ + "report.xml", + "report.html", + "benchmark.md", + "single/with_skill/evaluation.json", + "single/with_skill/grading.json", + "rejected/with_skill/grading.json", + "multi/with_skill/grading.json", + } + for _, name := range identical { + if !bytes.Equal(readFixtureFile(t, plainDir, name), readFixtureFile(t, measuredDir, name)) { + t.Errorf("%s differs between a run with and a run without measurements", name) + } + } + + plainBenchmark := benchmarkWithoutTimestamp(t, plainDir) + measuredBenchmark := benchmarkWithoutTimestamp(t, measuredDir) + if !reflect.DeepEqual(plainBenchmark, measuredBenchmark) { + t.Errorf("benchmark.json differs between a run with and a run without measurements") + } +} + +// benchmarkWithoutTimestamp decodes benchmark.json and drops the wall-clock +// timestamp, the one field that differs between any two writes. +func benchmarkWithoutTimestamp(t *testing.T, dir string) any { + t.Helper() + value := decodeJSON(t, readFixtureFile(t, dir, "benchmark.json")) + document, ok := value.(map[string]any) + if !ok { + t.Fatalf("benchmark.json is not an object") + } + metadata, ok := document["metadata"].(map[string]any) + if !ok { + t.Fatalf("benchmark.json has no metadata object") + } + if _, present := metadata["timestamp"]; !present { + t.Fatalf("benchmark.json metadata has no timestamp") + } + delete(metadata, "timestamp") + return value +}