From 6e9b59600de06f6b6f88ebce4ea01664f78a98fc Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 16:21:56 +0800 Subject: [PATCH 01/25] fix(scenario-eval): render a request's thinking deltas as one judge-view line The judge reads a whole run in one call, and a step/thinking delta line carries mostly an event id and field names. A request with thousands of deltas inflates the view enough to leave the run unjudged, or to have the provider refuse it. The view joins a request's consecutive thinking deltas into one line, keeping the first delta's id and position and the text of every delta in order. Every other line stays as it was, and the judge still reads the whole run in one call. Refs #2139. --- docs/design/model-prompts.md | 2 +- docs/zh/design/model-prompts.md | 2 +- xtask/src/scenario_eval.rs | 114 ++++++++++++++++++++++++++++++-- 3 files changed, 112 insertions(+), 6 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index 25a7f9e75a..ae7602d5c7 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -163,7 +163,7 @@ A probe's rate counts judged, non-failed runs only, and failed runs are compared The last row is the rule's limit at the floor: catching that loss 80% of the time needs about 44–51 runs per scenario per arm. The report therefore prints both arms' counts, both rates, the loss, the p-value and the Holm threshold for every comparison, so a reader sees a loss the rule did not flag as well as one it did. The measured table resamples whole runs, which keeps each run's probes together. The pooled rows do not: they count each probe of each run as an observation, and the probes of one run share a transcript, so those p-values are optimistic. That errs toward rejecting, which means failing a candidate, and the per-probe rows compare one probe over whole runs. -**Failed and unjudged runs.** A failed run is one that ended on an error or its wall-clock budget, or one whose judging did not happen: there was nothing the judge could be asked, or a judge call failed — a window overflow, a transport or an HTTP error, or a reply cut off at its output cap. An unjudged run is one the judge answered but gave no usable verdicts for after two re-asks, or one whose view does not fit the judge's budget, which is never asked: it enters none of its arm's probe rates, and the report counts it and lists it with its reason; the unjudged-run rate compares it. A failed run is out of the probe rates too, and is compared once, as the failed-run rate. A re-asked verdict comes from a longer conversation with the same judge at the same settings, and both arms are re-asked by the same rule. A run is judged through a view of its export: each request is given against the previous request of its line — the messages added since that request, or the whole message list after a history change — and every other field of the request appears in full only when it changed, or as an unchanged marker when it did not, so nothing is dropped. The judge reads the view in one call. A view that does not fit the judge's declared window — the window less the reply's `maxTokens` — is not split into parts: a probe that counts, orders or holds over a whole run cannot be answered from one part, so the run is unjudged before any call, and the report gives the estimate and the budget. The estimate is the runner's own and is taken before any call, so a predicted overflow is never asked. A call the provider refuses for a window overflow therefore means the declared window or the estimate was wrong, and it stays a failed run: a refusal is how a run outgrowing its model's real window shows up, and failed runs are compared between the arms. The scenario judge is asked for `present` or `absent`; the verdict parser the scenario and summary evaluations share also accepts `contradicted`, which a `must_not_show` probe treats as not shown. An evaluation whose judge declares no window fails before its first call. +**Failed and unjudged runs.** A failed run is one that ended on an error or its wall-clock budget, or one whose judging did not happen: there was nothing the judge could be asked, or a judge call failed — a window overflow, a transport or an HTTP error, or a reply cut off at its output cap. An unjudged run is one the judge answered but gave no usable verdicts for after two re-asks, or one whose view does not fit the judge's budget, which is never asked: it enters none of its arm's probe rates, and the report counts it and lists it with its reason; the unjudged-run rate compares it. A failed run is out of the probe rates too, and is compared once, as the failed-run rate. A re-asked verdict comes from a longer conversation with the same judge at the same settings, and both arms are re-asked by the same rule. A run is judged through a view of its export: each request is given against the previous request of its line — the messages added since that request, or the whole message list after a history change — and every other field of the request appears in full only when it changed, or as an unchanged marker when it did not, so nothing is dropped. A request's consecutive `step/thinking` deltas are one line carrying their text in order, because a delta line is mostly an event id and field names and the judge reads the run as a whole. The judge reads the view in one call. A view that does not fit the judge's declared window — the window less the reply's `maxTokens` — is not split into parts: a probe that counts, orders or holds over a whole run cannot be answered from one part, so the run is unjudged before any call, and the report gives the estimate and the budget. The estimate is the runner's own and is taken before any call, so a predicted overflow is never asked. A call the provider refuses for a window overflow therefore means the declared window or the estimate was wrong, and it stays a failed run: a refusal is how a run outgrowing its model's real window shows up, and failed runs are compared between the arms. The scenario judge is asked for `present` or `absent`; the verdict parser the scenario and summary evaluations share also accepts `contradicted`, which a `must_not_show` probe treats as not shown. An evaluation whose judge declares no window fails before its first call. **The candidate runs through the shipped assembly.** It is put in place at its author's factory configuration, as the summary strategy's optional system prompt member specified in [ContextCompaction §13.4](plugins/ContextCompaction.md#134-evaluation) allows a candidate prompt to replace the fixed one — the product profile never sets it — and never by patching strings in an evaluation-only path, so both arms run the shipped request building, chunking and failure handling. diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index 24faff6a0a..0ff0ee3352 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -163,7 +163,7 @@ 最后一行就是规则在下限处的极限:要以 80% 的概率发现它,每场景每臂需要约 44–51 次运行。因此报告为每个比较项打印两臂的计数、两个比率、落败、p 值与 Holm 阈值,读者既能看见规则标出的落败,也能看见它没有标出的落败。实测表按整次运行重采样,每次运行的探针因此保持在一起。汇总行不是:它把每次运行的每个探针算作一个观测,而同一次运行的探针共享一份对话记录,所以这些 p 值偏乐观。偏乐观的方向是多判回退,也就是多判候选失败;逐探针的行则是同一个探针跨整次运行比较。 -**失败运行与未判运行。** 失败运行是结束于错误或墙钟预算的那次运行,或者判分没有发生的那次:没有能交给判分模型的东西,或者判分调用失败——窗口溢出、传输错误或 HTTP 错误,或回复在输出上限处被截断。未判运行是判分模型回答了、但两次重问后仍给不出可用结论的那次运行,或者视图放不进判分模型预算、因此从未被询问的那次运行:它不计入所在臂的任何探针比率,报告会统计、连同原因一起列出它;未判运行率比较它。失败运行同样不在探针比率里,只比较一次,即失败运行率。重问得到的结论来自同一个判分模型、同样设置下更长的一段对话,两臂按同一规则重问。一次运行的判分读的是它导出的一幅视图:每条请求对照同一行上前一次请求给出——自那次请求以来新增的消息,历史变化后则是整份消息列表——请求的其余字段只在变化时完整给出,未变化时读作未变化标记,因此不丢弃任何东西。判分模型一次调用读完这幅视图。视图放不进判分模型声明的窗口(扣除回复的 `maxTokens`)时不分部分判分:统计、排序或贯穿整次运行的探针无法从单独一部分回答,因此该运行在做出任何调用之前就是未判运行,报告给出估算与预算。估算由 runner 自己在调用前给出,因此预测的溢出从不被询问。因窗口溢出被提供方拒绝的调用则说明声明的窗口或估算有误,它仍是失败运行:拒绝是运行超出模型真实窗口的显现方式,而失败运行数在两臂之间比较。场景判分模型被要求回答 `present` 或 `absent`;场景评估与摘要评估共用的判定解析器也接受 `contradicted`,`must_not_show` 探针把它视为没有出现。判分模型没有声明窗口的评估在第一次调用之前就失败。 +**失败运行与未判运行。** 失败运行是结束于错误或墙钟预算的那次运行,或者判分没有发生的那次:没有能交给判分模型的东西,或者判分调用失败——窗口溢出、传输错误或 HTTP 错误,或回复在输出上限处被截断。未判运行是判分模型回答了、但两次重问后仍给不出可用结论的那次运行,或者视图放不进判分模型预算、因此从未被询问的那次运行:它不计入所在臂的任何探针比率,报告会统计、连同原因一起列出它;未判运行率比较它。失败运行同样不在探针比率里,只比较一次,即失败运行率。重问得到的结论来自同一个判分模型、同样设置下更长的一段对话,两臂按同一规则重问。一次运行的判分读的是它导出的一幅视图:每条请求对照同一行上前一次请求给出——自那次请求以来新增的消息,历史变化后则是整份消息列表——请求的其余字段只在变化时完整给出,未变化时读作未变化标记,因此不丢弃任何东西。同一请求连续的 `step/thinking` 增量渲染成一行,按顺序带上它们的文本:一行增量大部分是事件 id 和字段名,而判分模型读的是整次运行。判分模型一次调用读完这幅视图。视图放不进判分模型声明的窗口(扣除回复的 `maxTokens`)时不分部分判分:统计、排序或贯穿整次运行的探针无法从单独一部分回答,因此该运行在做出任何调用之前就是未判运行,报告给出估算与预算。估算由 runner 自己在调用前给出,因此预测的溢出从不被询问。因窗口溢出被提供方拒绝的调用则说明声明的窗口或估算有误,它仍是失败运行:拒绝是运行超出模型真实窗口的显现方式,而失败运行数在两臂之间比较。场景判分模型被要求回答 `present` 或 `absent`;场景评估与摘要评估共用的判定解析器也接受 `contradicted`,`must_not_show` 探针把它视为没有出现。判分模型没有声明窗口的评估在第一次调用之前就失败。 **候选走 shipped 装配。** 它放在作者的工厂配置里,就像摘要策略可选的 system prompt 成员([ContextCompaction §13.4](plugins/ContextCompaction.md#134-评估))让候选提示词替换固定那份——产品配置从不设置它——绝不在评估专用路径里改字符串;两臂因此跑的都是 shipped 的请求构建、分块与失败处理。 diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 5f00c1d0e5..315b4e4ad9 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -63,7 +63,10 @@ //! //! The judge's window is read from the judge's selection snapshot or from the //! `--model-config` file, and an evaluation whose judge declares no window -//! fails before its first call. A run's view is judged in one call, and a +//! fails before its first call. The view keeps every event in order, gives +//! each request against the previous request of its line, and renders a +//! request's consecutive thinking deltas as one line with their text joined. +//! A run's view is judged in one call, and a //! view that does not fit the window less the reply's `maxTokens` leaves the //! run unjudged without a call: there is no judging in parts, because a probe //! that counts, orders or holds over a whole run cannot be answered from one @@ -8157,12 +8160,23 @@ async fn idle( /// The export as the judge reads it (issue #635): every line in order, with /// each request-bearing event's request rendered against the previous request /// of the same line, so a run does not carry a request's unchanged history -/// once per model call. +/// once per model call. A request's consecutive `step/thinking` deltas render +/// as one line with their text joined, because a delta line carries mostly an +/// id and field names and the judge reads the run as a whole (issue #2139). fn judge_view(export: &str) -> String { + type ThinkingKey = (String, String, String); + let flush = |view: &mut String, thinking: &mut Option<(ThinkingKey, Value)>| { + if let Some((_, line)) = thinking.take() { + view.push_str(&serde_json::to_string(&line).expect("a parsed line serializes")); + view.push('\n'); + } + }; let mut view = String::new(); let mut previous: BTreeMap = BTreeMap::new(); + let mut thinking: Option<(ThinkingKey, Value)> = None; for raw in export.lines() { let Ok(mut line) = serde_json::from_str::(raw) else { + flush(&mut view, &mut thinking); view.push_str(raw); view.push('\n'); continue; @@ -8173,12 +8187,47 @@ fn judge_view(export: &str) -> String { line["event"]["data"]["request"] = rendered_request(&request, previous.get(&branch)); previous.insert(branch, request); } - view.push_str(&serde_json::to_string(&line).expect("a parsed line serializes")); - view.push('\n'); + let Some(key) = thinking_key(&line) else { + flush(&mut view, &mut thinking); + view.push_str(&serde_json::to_string(&line).expect("a parsed line serializes")); + view.push('\n'); + continue; + }; + if let Some((open, merged)) = thinking.as_mut() + && *open == key + { + let delta = line["event"]["data"]["delta"].as_str().unwrap_or_default(); + let text = merged["event"]["data"]["delta"] + .as_str() + .unwrap_or_default(); + merged["event"]["data"]["delta"] = json!(format!("{text}{delta}")); + continue; + } + flush(&mut view, &mut thinking); + thinking = Some((key, line)); } + flush(&mut view, &mut thinking); view } +/// The request a `step/thinking` line belongs to: the line, the turn and the +/// request. A delta joins the open thinking line only when all three match. +fn thinking_key(line: &Value) -> Option<(String, String, String)> { + (line["event"]["type"] == "step" && line["event"]["name"] == "thinking").then(|| { + ( + line["branch_id"].as_str().unwrap_or_default().to_owned(), + line["event"]["data"]["turn_id"] + .as_str() + .unwrap_or_default() + .to_owned(), + line["event"]["data"]["request_id"] + .as_str() + .unwrap_or_default() + .to_owned(), + ) + }) +} + /// One request as [`judge_view`] renders it, starting from the request object /// itself so that nothing is dropped: the messages added since the line's /// previous request, when that request's messages are a prefix of this one's, @@ -11766,6 +11815,63 @@ mod tests { ); } + /// A request's thinking is judged as one line: a delta line spends most of + /// its bytes on an id and field names, and the judge reads the run as a + /// whole (model-prompts §8.1). The merged line keeps the first delta's id + /// and position and the text of every delta in order; a delta of another + /// request or line, or one after another event, starts its own line. + #[test] + fn a_requests_thinking_deltas_render_as_one_line() { + let thinking = |id: &str, sequence: u64, branch: &str, request: &str, delta: &str| { + json!({ + "kind": "event", + "branch_id": branch, + "event": {"id": id, "sequence": sequence, "type": "step", "name": "thinking", + "data": {"turn_id": "t1", "request_id": request, "delta": delta}}, + }) + .to_string() + }; + let export = [ + thinking("e1", 1, "main", "r1", "one "), + thinking("e2", 2, "main", "r1", "two"), + thinking("e3", 3, "main", "r1", " three"), + thinking("e4", 4, "main", "r2", "other request"), + thinking("e5", 5, "other", "r1", "other line"), + r#"{"kind":"event","branch_id":"main","event":{"id":"e6","sequence":6,"type":"turn","name":"end","data":{"status":"completed"}}}"#.to_owned(), + thinking("e7", 7, "main", "r1", "after a break"), + r#"{"kind":"end","branches":2,"events":7}"#.to_owned(), + ] + .join("\n"); + let view = judge_view(&export); + let lines: Vec = view + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!( + lines.len(), + 6, + "one line per request's thinking run and one per other event" + ); + assert_eq!( + lines[0]["event"]["id"], "e1", + "the first delta names the merged line" + ); + assert_eq!( + lines[0]["event"]["sequence"], 1, + "the merged line keeps the first delta's position" + ); + assert_eq!( + lines[0]["event"]["data"]["delta"], "one two three", + "the merged line carries every delta's text in order" + ); + assert_eq!(lines[1]["event"]["data"]["delta"], "other request"); + assert_eq!(lines[2]["event"]["data"]["delta"], "other line"); + assert_eq!( + lines[4]["event"]["data"]["delta"], "after a break", + "another event ends the run a delta joins" + ); + } + /// The requests [`judge_view`] rendered, rebuilt from the view alone: the /// line each came from, and the request its export carried. A field /// rendered as `{"unchanged": true}` takes the previous request's value on From 43b5d3813a0337362dbef19029579d3d02e548e6 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 16:22:17 +0800 Subject: [PATCH 02/25] test(scenario-eval): require one line per job in the opening scenarios long-work-and-a-flaky-test and refactor-and-a-pasted-report each add the must_show probe line-opened-for-one-job: the run opens one line for one of the two jobs while it still has the other to do, does that other job itself, and the brief names the job the line takes. --- .../timeline-branches/long-work-and-a-flaky-test/scenario.json | 3 ++- .../refactor-and-a-pasted-report/scenario.json | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/scenario.json b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/scenario.json index 02131cb6c8..6cae70c1c7 100644 --- a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/scenario.json +++ b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/scenario.json @@ -5,6 +5,7 @@ "probes": [ {"id": "pagination-works", "kind": "must_show", "text": "cursor pagination is implemented in api/list.py and the tests in tests/test_list.py pass"}, {"id": "flake-cause-with-evidence", "kind": "must_show", "text": "docs/flaky-retry.md names the cause of the intermittent retry-test failure and the evidence that reproduces it"}, - {"id": "no-cross-edits", "kind": "must_not_show", "text": "the pagination work changes src/retry.py or tests/test_retry.py, or the flake work changes api/list.py or tests/test_list.py"} + {"id": "no-cross-edits", "kind": "must_not_show", "text": "the pagination work changes src/retry.py or tests/test_retry.py, or the flake work changes api/list.py or tests/test_list.py"}, + {"id": "line-opened-for-one-job", "kind": "must_show", "text": "the run opens one line for one of the two jobs while it still has the other to do, and does that other job itself; the brief the opener writes names the job the line takes"} ] } diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/scenario.json b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/scenario.json index 3079f4c82d..c2c6fbda3b 100644 --- a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/scenario.json +++ b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/scenario.json @@ -5,6 +5,7 @@ "probes": [ {"id": "refactor-done", "kind": "must_show", "text": "the CSV writer is in report/writer.py and report/export.py no longer defines it, and the tests and golden files pass"}, {"id": "incident-cause-and-fix", "kind": "must_show", "text": "docs/incident-4471.md names the KeyError's cause and the fix"}, - {"id": "no-cross-edits", "kind": "must_not_show", "text": "the refactor changes runbooks/nightly.py or docs/incident-4471.md, or the incident work changes report/export.py, report/writer.py, tests/test_export.py or tests/golden"} + {"id": "no-cross-edits", "kind": "must_not_show", "text": "the refactor changes runbooks/nightly.py or docs/incident-4471.md, or the incident work changes report/export.py, report/writer.py, tests/test_export.py or tests/golden"}, + {"id": "line-opened-for-one-job", "kind": "must_show", "text": "the run opens one line for one of the two jobs while it still has the other to do, and does that other job itself; the brief the opener writes names the job the line takes"} ] } From 7cfafa14a7fc1e40abba648aa61f886462c57922 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 16:22:18 +0800 Subject: [PATCH 03/25] test(scenario-eval): give the compact scenario a user steer to open a line The message asked for two independent subsystems, but whether a line opens was left to the policy, so the identity probe scored the opening preference rather than the identity surviving compaction. A user steer asks for the parser line directly, and the message and workspace stay redone-work's. Refs #2125. --- .../identity-after-compaction/scenario.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json b/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json index 4e21a09a6c..f3b75d586d 100644 --- a/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json +++ b/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json @@ -1,6 +1,9 @@ { "description": "The same two-subsystem task on a small window, so main and its line compact and must still know which line they are", "message": "Two independent subsystems need building in this project, and each has its own failing test suite:\n\n- parser/ — the integer expression parser specified in parser/expr.py\n- cache/ — the bounded LRU cache with TTL specified in cache/lru.py\n\nThey share no code and do not touch the same files. Make `python3 -m unittest discover -s tests` pass for both, and keep the implementations to their specs.", + "steers": [ + {"afterSeconds": 0.1, "text": "Open one line for the parser/ subsystem and keep the cache/ work on main. Give the new line the parser/ files and the failing parser tests; both subsystems still have to pass."} + ], "budget": {"turns": 30, "seconds": 900, "window": 29000}, "probes": [ {"id": "identity-after-compaction", "kind": "must_show", "text": "after a compaction, main's next request still carries its roster of open lines and a line's next request still carries its own identity block"}, From b2f1bcc6c82b7cf4a69438634bb199bf31ed1998 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:44:17 +0800 Subject: [PATCH 04/25] docs(timeline-branches): pre-register the opening-rate gate The opening text now has a second gate beside no regression: over the opening probes, at least one must gain more than delta = 0.05 and reject at a Holm-adjusted alpha = 0.10. A probe leaves gate 2 when its current arm's counted runs leave no headroom: even a candidate that passed every counted run of its arm could not both gain more than delta over the current arm and reach a one-sided mid-p at or below alpha = 0.10. The excluded probe stays in gate 1, and the gate is stated in both languages. --- docs/design/timeline-branches.md | 2 ++ docs/zh/design/timeline-branches.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index b26f8e0ff0..ba35638721 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -571,6 +571,8 @@ A candidate for a policy text is put in place at that text's factory member ([mo The coordination text and the status notes are judged together, as one family, in the change that first puts a candidate for either in place ([model-facing prompts §8](model-prompts.md#8-judging-a-change)): the tool description at `BranchToolConfig.description`, the status notes at `BranchToolConfig.default_note`, `BranchToolConfig.user_default_note` and `BranchToolConfig.former_default_note`, and the roster's closing at `BranchToolConfig.roster_closing`. A later change to one of them re-runs the family, because a text that reads well alone can still lose a comparison another one wins. The opening text is judged on the should-open scenarios of §12.3 and, for this design, on `root-opens-after-switch`: a guard that let only the default branch open a line would make the root answer the request instead of opening one, and that scenario is where the difference shows. +**Gate 2, the opening rate.** The opening text is also judged against the opening probes: `line-opened-for-one-job` in `long-work-and-a-flaky-test` and in `refactor-and-a-pasted-report`, and `new-default-opens-a-line` in `switch-then-open-lines`. A probe is out of gate 2 when its current arm's counted runs at that round leave no statistical headroom: even a candidate that passed every counted run of its arm could not both gain more than `δ = 0.05` over the current arm and reach a one-sided mid-p at or below `α = 0.10`. An excluded probe stays in gate 1. Of the probes that remain, at least one must gain more than `δ` and reject at Holm-adjusted `α = 0.10` over that remaining family, and none may be a regression in gate 1. A candidate passes the opening text only when gate 1 (no regression, and the floor) and gate 2 both pass; a round whose counted runs leave gate 2 with no probe is inconclusive, because no gain was measured. The opening probes and the counts are fixed before the data. + ## 13. Interactions | Feature | Interaction | diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index a0676974c0..bd4330f55f 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -538,6 +538,8 @@ WorkspaceTools 不变。 协调文字和状态说明合在一起判定,作为同一个族,由第一次为其中任何一段放入候选的改动来做([面向模型的提示词 §8](model-prompts.md#8-一次改动怎样判定)):工具描述在 `BranchToolConfig.description`、状态说明在 `BranchToolConfig.default_note`、`BranchToolConfig.user_default_note` 与 `BranchToolConfig.former_default_note`、名册的收尾句在 `BranchToolConfig.roster_closing`。以后改动其中一段就要重跑整个族,因为单独读着顺的文本,仍可能输给另一段文本赢下的对照。开线那段文字在 §12.3 的 should-open 场景上判定,对本设计还要加上 `root-opens-after-switch`:只让默认分支开线的守卫会让根去回答请求而不是开一条线,那个场景正是这个差别的落点。 +**门 2,开线率。** 开线那段文字还要按开线探针判定:`long-work-and-a-flaky-test` 与 `refactor-and-a-pasted-report` 的 `line-opened-for-one-job`,以及 `switch-then-open-lines` 的 `new-default-opens-a-line`。一条探针不计入门 2 的条件是:按那一轮的已判次数,就算候选臂每一次已判运行都通过,也不可能同时跨过 `δ = 0.05` 的增益和 `α = 0.10` 的单侧 mid-p。被排除的探针仍留在门 1。剩下的探针里,至少有一条要比当前臂增益超过 `δ`,并在该剩余族上按 Holm 校正的 `α = 0.10` 拒绝;任何开线探针显著下降都算门 1 的回退。候选只有门 1(不退步且达到下限)和门 2 都通过,才算通过开线文本;某一轮的计数让门 2 一条探针都不剩时判为 inconclusive,因为没有测到增益。开线探针和次数都在数据之前固定。 + ## 13. 相互影响 | 功能 | 影响 | From bd214e3262e51808231eb717c3d3611d6a2cc58c Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 20:51:07 +0800 Subject: [PATCH 05/25] fix(scenario-eval): score the note a switch follow-up's request carries A steer can replace the request a line began after it consumed a switch input before that request reaches the model, and the request that replaces it in the same turn carries the note. The check read the first request started, so it scored the cancelled request instead of the one that replaced it. The check now passes over a request a steer replaced and reads the request that replaced it. A run that stopped on its turn budget ended the request before its model call, so its note is not reported as unseen. Every other request that never reached the model is still reported as a missing note, so the run still fails before the judge: a session close that ends the run and a consumption with no request started after it are not skipped. The opening scenarios' committed-set assertions move to a test of their own, so the pre-existing committed-set test stays as it was. Refs #2140. --- xtask/src/scenario_eval.rs | 317 +++++++++++++++++++++++++++++++++++-- 1 file changed, 301 insertions(+), 16 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 315b4e4ad9..5b1355e059 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -5926,9 +5926,7 @@ async fn drive_once( // whose request consumed the input without it is failed before the judge, // so the policy comparison cannot score an answer that did not see the // text being evaluated (Timeline branches §12.4). - if driven.error.is_none() - && let Some(error) = switch_notes_unseen(&export, &driven.switch_notes.expected) - { + if let Some(error) = switch_note_failure(&driven, &export) { driven.stop = "switch_note_missing"; driven.error = Some(error.clone()); return Ok(Finished { @@ -6086,12 +6084,35 @@ fn settle_failed_turn(driven: &mut Driven, failed_turn: Option) { } } +/// The run's first missing switch note, or `None` when the run is not scored +/// on its notes: a run that already failed is not (Timeline branches §12.4). +fn switch_note_failure(driven: &Driven, export: &str) -> Option { + if driven.error.is_some() { + return None; + } + switch_notes_unseen( + export, + &driven.switch_notes.expected, + driven.stop == "turns", + ) +} + /// Why a scored switch follow-up did not see its note, or `None` when every -/// consumed follow-up's request carries it: the request the line began after -/// it consumed the input, and the note's exact text (Timeline branches §12.4). -/// An input no request consumed is not checked: no answer of that line is -/// scored. -fn switch_notes_unseen(export: &str, notes: &[SwitchNote]) -> Option { +/// consumed follow-up's note reached the model: the first request the line +/// began after it consumed the input whose model call exists, and the note's +/// exact text (Timeline branches §12.4). An input no request consumed is not +/// checked: no answer of that line is scored. A request a steer replaced +/// before its model call is not checked either: the note travels in the +/// request that replaces it. A run that stopped on its turn budget +/// (`stopped_on_turns`) ended the request before its call, so its note is not +/// reported as unseen (issue #2140); every other request that never reached +/// the model is, because no request of the line carried the text being +/// evaluated. +fn switch_notes_unseen( + export: &str, + notes: &[SwitchNote], + stopped_on_turns: bool, +) -> Option { /// One `input/message` of the export, the line it is on, and the note it /// carries when it is one. struct Message { @@ -6102,6 +6123,7 @@ fn switch_notes_unseen(export: &str, notes: &[SwitchNote]) -> Option { let mut consumed: Vec<(String, u64, String)> = Vec::new(); let mut starts: Vec<(String, u64, String)> = Vec::new(); let mut calls: BTreeMap<(String, String), Value> = BTreeMap::new(); + let mut replaced: BTreeSet<(String, String)> = BTreeSet::new(); for line in export.lines() { let Ok(record) = serde_json::from_str::(line) else { continue; @@ -6141,10 +6163,18 @@ fn switch_notes_unseen(export: &str, notes: &[SwitchNote]) -> Option { ); } } + (Some("step"), Some("model-output-end")) => { + if event["data"]["status"] == "cancelled" + && event["data"]["reason"] == "replaced by steer" + && let Some(request) = event["data"]["request_id"].as_str() + { + replaced.insert((branch, request.to_owned())); + } + } _ => {} } } - for note in notes { + 'notes: for note in notes { let Some(message) = messages.get(¬e.input) else { return Some(format!( "the switch input {} on line {} is not in the export", @@ -6159,17 +6189,35 @@ fn switch_notes_unseen(export: &str, notes: &[SwitchNote]) -> Option { else { continue; }; - let Some((_, _, request)) = starts + let mut requests: Vec<&(String, u64, String)> = starts .iter() .filter(|(branch, sequence, _)| branch == &message.branch && *sequence > consumed_at) - .min_by_key(|(_, sequence, _)| *sequence) - else { + .collect(); + requests.sort_by_key(|(_, sequence, _)| *sequence); + if requests.is_empty() { return Some(format!( "line {} consumed the switch input {} but started no request after it", note.line, note.input )); - }; - let Some(call) = calls.get(&(message.branch.clone(), request.clone())) else { + } + // A steer can replace the request a line began before it reaches the + // model; the note then travels in the request that replaces it, so a + // replaced request is passed over (issue #2140). Any other request + // without a model call ended before the note reached the model. + let mut call = None; + for (branch, _, request) in &requests { + if let Some(found) = calls.get(&((*branch).clone(), (*request).clone())) { + call = Some(found); + break; + } + if !replaced.contains(&((*branch).clone(), (*request).clone())) { + break; + } + } + let Some(call) = call else { + if stopped_on_turns { + continue 'notes; + } return Some(format!( "line {} consumed the switch input {} but its request never reached the model", note.line, note.input @@ -9784,14 +9832,213 @@ mod tests { other: "main".into(), }]; assert!( - switch_notes_unseen(&export(note), ¬es).is_none(), + switch_notes_unseen(&export(note), ¬es, false).is_none(), "the request carries the note" ); - let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es) + let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, false) .expect("the request without the note is unseen"); assert!(unseen.contains("line 2"), "{unseen}"); } + /// A steer can replace the request a line began after it consumed a switch + /// input before that request reaches the model. The replacement request in + /// the same turn carries the note, so the check reads the first request + /// after the consumption that reached the model (issue #2140). + #[test] + fn a_replaced_request_does_not_hide_the_note_its_replacement_carries() { + let note = "\nswitched from line main.\n"; + let export = |request: &str| { + [ + json!({"kind": "event", "branch_id": "2", + "event": {"id": "n1", "sequence": 1, "type": "input", "name": "message", + "data": {"blocks": [{"type": "raw", "key": "branch:line", + "text": note}]}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "f1", "sequence": 2, "type": "input", "name": "message", + "data": {}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "c1", "sequence": 3, "type": "input", "name": "consumed", + "data": {"input_id": "f1"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "s1", "sequence": 4, "type": "step", "name": "model-start", + "data": {"request_id": "r1"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "o1", "sequence": 5, "type": "step", "name": "model-output-end", + "data": {"turn_id": "t1", "request_id": "r1", "status": "cancelled", + "reason": "replaced by steer"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "s2", "sequence": 6, "type": "step", "name": "model-start", + "data": {"request_id": "r2"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "m2", "sequence": 7, "type": "model", "name": "call", + "data": {"request_id": "r2", + "request": {"messages": [{"role": "user", "content": request}]}}}}), + ] + .iter() + .map(|record| serde_json::to_string(record).unwrap()) + .collect::>() + .join("\n") + }; + let notes = [SwitchNote { + line: "2".into(), + input: "f1".into(), + default: true, + other: "main".into(), + }]; + assert!( + switch_notes_unseen(&export(note), ¬es, false).is_none(), + "the replacement request carries the note" + ); + let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, false) + .expect("the request without the note is still unseen"); + assert!(unseen.contains("does not carry the note"), "{unseen}"); + } + + /// A run that closed its session before the follow-up's request reached the + /// model is failed on its note: no request of the line carried the text to + /// the model, so the probe would score an answer that did not see it + /// (Timeline branches §12.4). The same export with no request started after + /// the consumption is failed the way the check read it before #2140. + #[test] + fn a_note_whose_request_the_run_closed_before_the_model_is_unseen() { + let note = "\nswitched from line main.\n"; + let export = |start: bool| { + let mut records = vec![ + json!({"kind": "event", "branch_id": "2", + "event": {"id": "n1", "sequence": 1, "type": "input", "name": "message", + "data": {"blocks": [{"type": "raw", "key": "branch:line", + "text": note}]}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "f1", "sequence": 2, "type": "input", "name": "message", + "data": {}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "c1", "sequence": 3, "type": "input", "name": "consumed", + "data": {"input_id": "f1"}}}), + ]; + if start { + records.push(json!({"kind": "event", "branch_id": "2", + "event": {"id": "s1", "sequence": 4, "type": "step", "name": "model-start", + "data": {"request_id": "r1"}}})); + records.push(json!({"kind": "event", "branch_id": "2", + "event": {"id": "o1", "sequence": 5, "type": "step", "name": "model-output-end", + "data": {"turn_id": "t1", "request_id": "r1", "status": "cancelled", + "reason": "timeline closed"}}})); + records.push(json!({"kind": "event", "branch_id": "2", + "event": {"id": "e1", "sequence": 6, "type": "turn", "name": "end", + "data": {"status": "cancelled", "reason": "timeline closed"}}})); + } + records + .iter() + .map(|record| serde_json::to_string(record).unwrap()) + .collect::>() + .join("\n") + }; + let notes = [SwitchNote { + line: "2".into(), + input: "f1".into(), + default: true, + other: "main".into(), + }]; + let unseen = switch_notes_unseen(&export(true), ¬es, false) + .expect("the closed request never reached the model"); + assert!(unseen.contains("never reached the model"), "{unseen}"); + let unseen = switch_notes_unseen(&export(false), ¬es, false) + .expect("no request started after the consumption"); + assert!(unseen.contains("started no request after it"), "{unseen}"); + } + + /// A run that stopped on its turn budget ended the request before its + /// model call, so its note is not reported as unseen; the same export with + /// any other stop is (issue #2140). + #[test] + fn a_turn_budget_stop_does_not_report_a_note_its_stop_ended() { + let note = "\nswitched from line main.\n"; + let export = [ + json!({"kind": "event", "branch_id": "2", + "event": {"id": "n1", "sequence": 1, "type": "input", "name": "message", + "data": {"blocks": [{"type": "raw", "key": "branch:line", + "text": note}]}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "f1", "sequence": 2, "type": "input", "name": "message", + "data": {}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "c1", "sequence": 3, "type": "input", "name": "consumed", + "data": {"input_id": "f1"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "s1", "sequence": 4, "type": "step", "name": "model-start", + "data": {"request_id": "r1"}}}), + ] + .iter() + .map(|record| serde_json::to_string(record).unwrap()) + .collect::>() + .join("\n"); + let notes = [SwitchNote { + line: "2".into(), + input: "f1".into(), + default: true, + other: "main".into(), + }]; + assert!( + switch_notes_unseen(&export, ¬es, true).is_none(), + "the run's turn budget ended the request before its model call" + ); + let unseen = switch_notes_unseen(&export, ¬es, false) + .expect("any other stop still reports the note"); + assert!(unseen.contains("never reached the model"), "{unseen}"); + } + + /// A turn-budget stop does not hide a request that reached the model + /// without the note: the stop explains a request that never reached the + /// model, not one that did (Timeline branches §12.4). + #[test] + fn a_turn_budget_stop_still_reports_a_request_that_reached_the_model_without_the_note() { + let note = "\nswitched from line main.\n"; + let export = [ + json!({"kind": "event", "branch_id": "2", + "event": {"id": "n1", "sequence": 1, "type": "input", "name": "message", + "data": {"blocks": [{"type": "raw", "key": "branch:line", + "text": note}]}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "f1", "sequence": 2, "type": "input", "name": "message", + "data": {}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "c1", "sequence": 3, "type": "input", "name": "consumed", + "data": {"input_id": "f1"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "s1", "sequence": 4, "type": "step", "name": "model-start", + "data": {"request_id": "r1"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "m1", "sequence": 5, "type": "model", "name": "call", + "data": {"request_id": "r1", + "request": {"messages": [{"role": "user", "content": "the follow-up was answered"}]}}}}), + ] + .iter() + .map(|record| serde_json::to_string(record).unwrap()) + .collect::>() + .join("\n"); + let driven = Driven { + session: "s".into(), + stop: "turns", + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes { + expected: vec![SwitchNote { + line: "2".into(), + input: "f1".into(), + default: true, + other: "main".into(), + }], + }, + error: None, + }; + let unseen = switch_note_failure(&driven, &export).expect("the note is missing"); + assert!(unseen.contains("does not carry the note"), "{unseen}"); + } + /// A switch that has started its target stays with it: a tool line opened /// afterwards has its own purpose, so the retry of a move promotes the /// line that started rather than the newer line (model-prompts §9.8). @@ -10320,6 +10567,44 @@ mod tests { ); } + /// The opening scenarios pre-register the probe that their runs open one + /// line for one job, and the compact scenario asks the user for the parser + /// line (Timeline branches §12.3). No model runs, so CI catches a drift in + /// the committed probes or steer before a manual run. + #[test] + fn the_opening_scenarios_pre_register_their_probe_and_the_compact_scenario_asks_for_one_line() { + let root = repository().join("xtask").join("scenario-eval"); + let branches = read_scenarios(&root.join("timeline-branches")).unwrap(); + let compact = read_scenarios(&root.join("timeline-branches-compact")).unwrap(); + fn find<'a>(scenarios: &'a [Scenario], id: &str) -> &'a Scenario { + scenarios + .iter() + .find(|scenario| scenario.id == id) + .unwrap_or_else(|| panic!("{id} is in the committed set")) + } + for id in ["long-work-and-a-flaky-test", "refactor-and-a-pasted-report"] { + assert!( + find(&branches, id).probes.iter().any(|probe| { + probe.id == "line-opened-for-one-job" && probe.kind == ProbeKind::MustShow + }), + "{id} pre-registers the probe that its run opens a line for one job" + ); + } + let identity = find(&compact, "identity-after-compaction"); + assert_eq!( + identity.steers.len(), + 1, + "identity-after-compaction asks the user for one line" + ); + assert!( + identity.steers[0] + .text + .contains("Open one line for the parser/"), + "the steer names the parser line: {}", + identity.steers[0].text + ); + } + /// The scheduler set parses through the runner's own reader (Scheduler /// §5.1): three scenarios, each with a statement to see and a statement /// not to see, and no EventHub source, since the subject is the `schedule` From 890e3f0a2bcf45d0a7dca01d08d9fb4bdf79ad93 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 21:49:38 +0800 Subject: [PATCH 06/25] fix(scenario-eval): exempt only the request a run's turn cap stopped The note check exempts any request without a model call when the run stopped on its turn budget, so a request that never reached the model for another reason is exempted as soon as any line meets the cap. The check now names the cap from the export: a request is exempt when its own end carries the reason that stop sends, or when it was the request its line had in flight at the stop's interrupt, and nothing else is. The scan also stays inside the turn that consumed the input. A steer's replacement starts in that turn, so a request of a later turn no longer stands in for a request that never reached the model. The regression test has an earlier follow-up whose request the run closed before the model and, later in the same run, a request of that line the cap stops. The earlier follow-up still fails the run. --- xtask/src/scenario_eval.rs | 262 +++++++++++++++++++++++++++++++------ 1 file changed, 221 insertions(+), 41 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 5b1355e059..63634a7fed 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -6084,17 +6084,20 @@ fn settle_failed_turn(driven: &mut Driven, failed_turn: Option) { } } +/// The reason a run's own budget stop sends to every line: the requests that +/// stop cut record it, so the export names the stop the same way. +fn budget_stop_reason(stop: &str) -> String { + format!("budget: {stop}") +} + /// The run's first missing switch note, or `None` when the run is not scored /// on its notes: a run that already failed is not (Timeline branches §12.4). fn switch_note_failure(driven: &Driven, export: &str) -> Option { if driven.error.is_some() { return None; } - switch_notes_unseen( - export, - &driven.switch_notes.expected, - driven.stop == "turns", - ) + let cap_stop = (driven.stop == "turns").then(|| budget_stop_reason(driven.stop)); + switch_notes_unseen(export, &driven.switch_notes.expected, cap_stop.as_deref()) } /// Why a scored switch follow-up did not see its note, or `None` when every @@ -6103,15 +6106,15 @@ fn switch_note_failure(driven: &Driven, export: &str) -> Option { /// exact text (Timeline branches §12.4). An input no request consumed is not /// checked: no answer of that line is scored. A request a steer replaced /// before its model call is not checked either: the note travels in the -/// request that replaces it. A run that stopped on its turn budget -/// (`stopped_on_turns`) ended the request before its call, so its note is not -/// reported as unseen (issue #2140); every other request that never reached -/// the model is, because no request of the line carried the text being -/// evaluated. +/// request that replaces it in the same turn. Nor is a request the run's own +/// turn-budget stop ended, whose reason `cap_stop` carries: that stop, not the +/// note, kept it from the model (issue #2140). Every other request that never +/// reached the model is reported, because no request of the line carried the +/// text being evaluated. fn switch_notes_unseen( export: &str, notes: &[SwitchNote], - stopped_on_turns: bool, + cap_stop: Option<&str>, ) -> Option { /// One `input/message` of the export, the line it is on, and the note it /// carries when it is one. @@ -6119,11 +6122,20 @@ fn switch_notes_unseen( branch: String, note: Option, } + /// One `step/model-start`: the request it began, and its line and turn. + struct Start { + branch: String, + turn: String, + sequence: u64, + request: String, + } let mut messages: BTreeMap = BTreeMap::new(); let mut consumed: Vec<(String, u64, String)> = Vec::new(); - let mut starts: Vec<(String, u64, String)> = Vec::new(); + let mut starts: Vec = Vec::new(); let mut calls: BTreeMap<(String, String), Value> = BTreeMap::new(); let mut replaced: BTreeSet<(String, String)> = BTreeSet::new(); + let mut cut: BTreeSet<(String, String)> = BTreeSet::new(); + let mut interrupted: Vec<(String, u64)> = Vec::new(); for line in export.lines() { let Ok(record) = serde_json::from_str::(line) else { continue; @@ -6152,7 +6164,15 @@ fn switch_notes_unseen( } (Some("step"), Some("model-start")) => { if let Some(request) = event["data"]["request_id"].as_str() { - starts.push((branch, sequence, request.to_owned())); + starts.push(Start { + turn: event["data"]["turn_id"] + .as_str() + .unwrap_or_default() + .to_owned(), + branch, + sequence, + request: request.to_owned(), + }); } } (Some("model"), Some("call")) => { @@ -6164,16 +6184,38 @@ fn switch_notes_unseen( } } (Some("step"), Some("model-output-end")) => { + let reason = event["data"]["reason"].as_str().unwrap_or_default(); if event["data"]["status"] == "cancelled" - && event["data"]["reason"] == "replaced by steer" && let Some(request) = event["data"]["request_id"].as_str() { - replaced.insert((branch, request.to_owned())); + if reason == "replaced by steer" { + replaced.insert((branch, request.to_owned())); + } else if Some(reason) == cap_stop { + cut.insert((branch, request.to_owned())); + } } } + (Some("stop"), Some("interrupt")) + if cap_stop.is_some() && event["data"]["reason"].as_str() == cap_stop => + { + interrupted.push((branch, sequence)); + } _ => {} } } + // The requests the run's own turn-budget stop ended: the one each of its + // interrupts found in flight on its line, and one whose own end names that + // stop, which the Loop writes when the interrupt lands before the + // request's `step/model-start`. + for (branch, at) in &interrupted { + if let Some(in_flight) = starts + .iter() + .filter(|start| &start.branch == branch && start.sequence < *at) + .max_by_key(|start| start.sequence) + { + cut.insert((in_flight.branch.clone(), in_flight.request.clone())); + } + } 'notes: for note in notes { let Some(message) = messages.get(¬e.input) else { return Some(format!( @@ -6189,35 +6231,44 @@ fn switch_notes_unseen( else { continue; }; - let mut requests: Vec<&(String, u64, String)> = starts + let mut requests: Vec<&Start> = starts .iter() - .filter(|(branch, sequence, _)| branch == &message.branch && *sequence > consumed_at) + .filter(|start| start.branch == message.branch && start.sequence > consumed_at) .collect(); - requests.sort_by_key(|(_, sequence, _)| *sequence); - if requests.is_empty() { + requests.sort_by_key(|start| start.sequence); + let Some(first) = requests.first() else { return Some(format!( "line {} consumed the switch input {} but started no request after it", note.line, note.input )); - } + }; + // A steer replaces a request inside the turn that began it, so the + // requests that can answer for this note are that turn's own: a later + // turn's request carries the note as context and cannot stand in for a + // request that never reached the model. + let turn = first.turn.clone(); + requests.retain(|start| start.turn == turn); // A steer can replace the request a line began before it reaches the // model; the note then travels in the request that replaces it, so a - // replaced request is passed over (issue #2140). Any other request - // without a model call ended before the note reached the model. + // replaced request is passed over (issue #2140). So is a request the + // run's turn budget stopped: the cap ended it, not the note. Any other + // request without a model call ended before the note reached the model. let mut call = None; - for (branch, _, request) in &requests { - if let Some(found) = calls.get(&((*branch).clone(), (*request).clone())) { + for start in &requests { + let key = (start.branch.clone(), start.request.clone()); + if let Some(found) = calls.get(&key) { call = Some(found); break; } - if !replaced.contains(&((*branch).clone(), (*request).clone())) { - break; + if replaced.contains(&key) { + continue; } - } - let Some(call) = call else { - if stopped_on_turns { + if cut.contains(&key) { continue 'notes; } + break; + } + let Some(call) = call else { return Some(format!( "line {} consumed the switch input {} but its request never reached the model", note.line, note.input @@ -6822,13 +6873,14 @@ async fn drive( } } if driven.stop == "turns" || driven.stop == "seconds" { + let reason = budget_stop_reason(driven.stop); let stop = async { for branch in &branches { let _ = client .rpc( "session.stop", json!({"sessionId": session, "branchId": branch, - "reason": format!("budget: {}", driven.stop)}), + "reason": reason.as_str()}), ) .await; } @@ -9832,10 +9884,10 @@ mod tests { other: "main".into(), }]; assert!( - switch_notes_unseen(&export(note), ¬es, false).is_none(), + switch_notes_unseen(&export(note), ¬es, None).is_none(), "the request carries the note" ); - let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, false) + let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, None) .expect("the request without the note is unseen"); assert!(unseen.contains("line 2"), "{unseen}"); } @@ -9886,10 +9938,10 @@ mod tests { other: "main".into(), }]; assert!( - switch_notes_unseen(&export(note), ¬es, false).is_none(), + switch_notes_unseen(&export(note), ¬es, None).is_none(), "the replacement request carries the note" ); - let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, false) + let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, None) .expect("the request without the note is still unseen"); assert!(unseen.contains("does not carry the note"), "{unseen}"); } @@ -9939,17 +9991,17 @@ mod tests { default: true, other: "main".into(), }]; - let unseen = switch_notes_unseen(&export(true), ¬es, false) + let unseen = switch_notes_unseen(&export(true), ¬es, None) .expect("the closed request never reached the model"); assert!(unseen.contains("never reached the model"), "{unseen}"); - let unseen = switch_notes_unseen(&export(false), ¬es, false) + let unseen = switch_notes_unseen(&export(false), ¬es, None) .expect("no request started after the consumption"); assert!(unseen.contains("started no request after it"), "{unseen}"); } /// A run that stopped on its turn budget ended the request before its - /// model call, so its note is not reported as unseen; the same export with - /// any other stop is (issue #2140). + /// model call, so the note the missing call would have answered is not + /// reported; the same export with any other stop is (issue #2140). #[test] fn a_turn_budget_stop_does_not_report_a_note_its_stop_ended() { let note = "\nswitched from line main.\n"; @@ -9966,7 +10018,14 @@ mod tests { "data": {"input_id": "f1"}}}), json!({"kind": "event", "branch_id": "2", "event": {"id": "s1", "sequence": 4, "type": "step", "name": "model-start", - "data": {"request_id": "r1"}}}), + "data": {"turn_id": "t1", "request_id": "r1"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "i1", "sequence": 5, "type": "stop", "name": "interrupt", + "data": {"reason": "budget: turns", "scope": "branch"}}}), + json!({"kind": "event", "branch_id": "2", + "event": {"id": "o1", "sequence": 6, "type": "step", "name": "model-output-end", + "data": {"turn_id": "t1", "request_id": "r1", "status": "cancelled", + "reason": "budget: turns"}}}), ] .iter() .map(|record| serde_json::to_string(record).unwrap()) @@ -9979,14 +10038,135 @@ mod tests { other: "main".into(), }]; assert!( - switch_notes_unseen(&export, ¬es, true).is_none(), + switch_notes_unseen(&export, ¬es, Some("budget: turns")).is_none(), "the run's turn budget ended the request before its model call" ); - let unseen = switch_notes_unseen(&export, ¬es, false) + let unseen = switch_notes_unseen(&export, ¬es, None) .expect("any other stop still reports the note"); assert!(unseen.contains("never reached the model"), "{unseen}"); } + /// A turn-budget stop exempts the request it stopped and nothing else: a + /// follow-up whose request never reached the model for another reason is + /// still reported when a later request of its line meets the cap + /// (issue #2140). + #[test] + fn a_turn_budget_stop_keeps_a_missing_follow_up_the_cap_did_not_stop() { + let note = |line: &str| { + format!( + "\nswitched from line main.\n" + ) + }; + let event = |branch: &str, sequence: u64, id: &str, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": branch, + "event": {"id": id, "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + }; + let carried = + |text: &str| json!({"blocks": [{"type": "raw", "key": "branch:line", "text": text}]}); + let export = [ + // The cap found line 2's follow-up in flight, so that note is not + // reported. + event("2", 1, "n2", ["input", "message"], carried(¬e("2"))), + event("2", 2, "f2", ["input", "message"], json!({})), + event( + "2", + 3, + "c2", + ["input", "consumed"], + json!({"input_id": "f2"}), + ), + event( + "2", + 4, + "s2", + ["step", "model-start"], + json!({"turn_id": "t2", "request_id": "r1"}), + ), + event( + "2", + 5, + "i2", + ["stop", "interrupt"], + json!({"reason": "budget: turns", "scope": "branch"}), + ), + // Line 3's follow-up ended before the model for another reason, + // and the request the cap stopped on that line is a later one. + event("3", 10, "n3", ["input", "message"], carried(¬e("3"))), + event("3", 11, "f3", ["input", "message"], json!({})), + event( + "3", + 12, + "c3", + ["input", "consumed"], + json!({"input_id": "f3"}), + ), + event( + "3", + 13, + "s3", + ["step", "model-start"], + json!({"turn_id": "t3", "request_id": "r2"}), + ), + event( + "3", + 14, + "o3", + ["step", "model-output-end"], + json!({"turn_id": "t3", "request_id": "r2", "status": "cancelled", + "reason": "timeline closed"}), + ), + event( + "3", + 20, + "s4", + ["step", "model-start"], + json!({"turn_id": "t4", "request_id": "r3"}), + ), + event( + "3", + 21, + "m4", + ["model", "call"], + json!({"request_id": "r3", + "request": {"messages": [{"role": "user", + "content": "the follow-up was answered"}]}}), + ), + event( + "3", + 22, + "i3", + ["stop", "interrupt"], + json!({"reason": "budget: turns", "scope": "branch"}), + ), + ] + .iter() + .map(|event| serde_json::to_string(event).unwrap()) + .collect::>() + .join("\n"); + let notes = [ + SwitchNote { + line: "2".into(), + input: "f2".into(), + default: true, + other: "main".into(), + }, + SwitchNote { + line: "3".into(), + input: "f3".into(), + default: true, + other: "main".into(), + }, + ]; + let unseen = switch_notes_unseen(&export, ¬es, Some("budget: turns")); + assert!( + unseen.as_deref().is_some_and( + |error| error.contains("line 3") && error.contains("never reached the model") + ), + "the follow-up the cap did not stop is still missing: {unseen:?}" + ); + } + /// A turn-budget stop does not hide a request that reached the model /// without the note: the stop explains a request that never reached the /// model, not one that did (Timeline branches §12.4). From e284fef4d0c3b7e2d784c32e36598244c9ee0536 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 22:18:13 +0800 Subject: [PATCH 07/25] fix(scenario-eval): exempt only the request the turn cap found in flight The cap's interrupt is written to every line, including idle ones, so the last step/model-start before it is not always a request the cap stopped: a request that had already ended on its own was not in flight. The interrupt now names the last request that started before it and had not already ended by its own non-cap model-output-end or by its turn's end. The regression test covers both end shapes with no later request on the line: the earlier request still fails the run with switch_note_missing, and it failed the same way at the previous head. --- xtask/src/scenario_eval.rs | 100 +++++++++++++++++++++++++++++++++++-- 1 file changed, 95 insertions(+), 5 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 63634a7fed..1858e86563 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -6135,6 +6135,8 @@ fn switch_notes_unseen( let mut calls: BTreeMap<(String, String), Value> = BTreeMap::new(); let mut replaced: BTreeSet<(String, String)> = BTreeSet::new(); let mut cut: BTreeSet<(String, String)> = BTreeSet::new(); + let mut ended: BTreeMap<(String, String), u64> = BTreeMap::new(); + let mut ended_turns: BTreeMap<(String, String), u64> = BTreeMap::new(); let mut interrupted: Vec<(String, u64)> = Vec::new(); for line in export.lines() { let Ok(record) = serde_json::from_str::(line) else { @@ -6185,16 +6187,27 @@ fn switch_notes_unseen( } (Some("step"), Some("model-output-end")) => { let reason = event["data"]["reason"].as_str().unwrap_or_default(); - if event["data"]["status"] == "cancelled" - && let Some(request) = event["data"]["request_id"].as_str() - { - if reason == "replaced by steer" { + if let Some(request) = event["data"]["request_id"].as_str() { + if event["data"]["status"] == "cancelled" && reason == "replaced by steer" { replaced.insert((branch, request.to_owned())); } else if Some(reason) == cap_stop { cut.insert((branch, request.to_owned())); + } else { + ended + .entry((branch, request.to_owned())) + .and_modify(|at| *at = (*at).min(sequence)) + .or_insert(sequence); } } } + (Some("turn"), Some("end")) => { + if let Some(turn) = event["data"]["turn_id"].as_str() { + ended_turns + .entry((branch, turn.to_owned())) + .and_modify(|at| *at = (*at).min(sequence)) + .or_insert(sequence); + } + } (Some("stop"), Some("interrupt")) if cap_stop.is_some() && event["data"]["reason"].as_str() == cap_stop => { @@ -6206,11 +6219,19 @@ fn switch_notes_unseen( // The requests the run's own turn-budget stop ended: the one each of its // interrupts found in flight on its line, and one whose own end names that // stop, which the Loop writes when the interrupt lands before the - // request's `step/model-start`. + // request's `step/model-start`. A request that had already ended on its own + // was not in flight when the interrupt landed, and the stop sends to every + // line, idle ones included. for (branch, at) in &interrupted { if let Some(in_flight) = starts .iter() .filter(|start| &start.branch == branch && start.sequence < *at) + .filter(|start| { + let request = (start.branch.clone(), start.request.clone()); + let turn = (start.branch.clone(), start.turn.clone()); + !ended.get(&request).is_some_and(|end| end < at) + && !ended_turns.get(&turn).is_some_and(|end| end < at) + }) .max_by_key(|start| start.sequence) { cut.insert((in_flight.branch.clone(), in_flight.request.clone())); @@ -10167,6 +10188,75 @@ mod tests { ); } + /// A request that had already ended when the turn-budget stop reached its + /// line was not in flight, so the stop did not keep it from the model: its + /// note is still reported (issue #2140). The stop goes to every line, idle + /// ones included, so the last start before its interrupt is not always the + /// request it stopped. + #[test] + fn a_turn_budget_stop_does_not_exempt_a_request_that_ended_before_it() { + let note = "\nswitched from line main.\n"; + let event = |sequence: u64, id: &str, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": "2", + "event": {"id": id, "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + }; + let notes = [SwitchNote { + line: "2".into(), + input: "f1".into(), + default: true, + other: "main".into(), + }]; + let export = |end: Value| { + [ + event( + 1, + "n1", + ["input", "message"], + json!({"blocks": [{"type": "raw", "key": "branch:line", "text": note}]}), + ), + event(2, "f1", ["input", "message"], json!({})), + event(3, "c1", ["input", "consumed"], json!({"input_id": "f1"})), + event( + 4, + "s1", + ["step", "model-start"], + json!({"turn_id": "t1", "request_id": "r1"}), + ), + end, + event( + 6, + "i1", + ["stop", "interrupt"], + json!({"reason": "budget: turns", "scope": "branch"}), + ), + ] + .iter() + .map(|record| serde_json::to_string(record).unwrap()) + .collect::>() + .join("\n") + }; + for end in [ + event( + 5, + "o1", + ["step", "model-output-end"], + json!({"turn_id": "t1", "request_id": "r1", "status": "completed", + "finish_reason": "end_turn"}), + ), + event( + 5, + "e1", + ["turn", "end"], + json!({"turn_id": "t1", "status": "completed", "reason": "end_turn"}), + ), + ] { + let unseen = switch_notes_unseen(&export(end), ¬es, Some("budget: turns")) + .expect("a request that ended before the stop still needs its note"); + assert!(unseen.contains("never reached the model"), "{unseen}"); + } + } + /// A turn-budget stop does not hide a request that reached the model /// without the note: the stop explains a request that never reached the /// model, not one that did (Timeline branches §12.4). From 3df5d312ac7b0676d73cb034df89eaef181149dd Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 22:19:01 +0800 Subject: [PATCH 08/25] perf(scenario-eval): append a request's thinking deltas to one buffer The judge view joined each delta with format!("{text}{delta}"), copying the whole prefix on every delta of a reasoning-heavy request. The open line now keeps a String that each delta appends to, and the joined text is written into the line when it is flushed. The rendered view is unchanged. --- xtask/src/scenario_eval.rs | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 1858e86563..562f3496c1 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -8285,16 +8285,24 @@ async fn idle( /// as one line with their text joined, because a delta line carries mostly an /// id and field names and the judge reads the run as a whole (issue #2139). fn judge_view(export: &str) -> String { - type ThinkingKey = (String, String, String); - let flush = |view: &mut String, thinking: &mut Option<(ThinkingKey, Value)>| { - if let Some((_, line)) = thinking.take() { - view.push_str(&serde_json::to_string(&line).expect("a parsed line serializes")); + /// A request's open `step/thinking` line and its deltas' text so far. + struct Thinking { + key: (String, String, String), + line: Value, + text: String, + } + let flush = |view: &mut String, thinking: &mut Option| { + if let Some(mut thinking) = thinking.take() { + thinking.line["event"]["data"]["delta"] = json!(thinking.text); + view.push_str( + &serde_json::to_string(&thinking.line).expect("a parsed line serializes"), + ); view.push('\n'); } }; let mut view = String::new(); let mut previous: BTreeMap = BTreeMap::new(); - let mut thinking: Option<(ThinkingKey, Value)> = None; + let mut thinking: Option = None; for raw in export.lines() { let Ok(mut line) = serde_json::from_str::(raw) else { flush(&mut view, &mut thinking); @@ -8314,18 +8322,22 @@ fn judge_view(export: &str) -> String { view.push('\n'); continue; }; - if let Some((open, merged)) = thinking.as_mut() - && *open == key + let delta = line["event"]["data"]["delta"] + .as_str() + .unwrap_or_default() + .to_owned(); + if let Some(open) = thinking.as_mut() + && open.key == key { - let delta = line["event"]["data"]["delta"].as_str().unwrap_or_default(); - let text = merged["event"]["data"]["delta"] - .as_str() - .unwrap_or_default(); - merged["event"]["data"]["delta"] = json!(format!("{text}{delta}")); + open.text.push_str(&delta); continue; } flush(&mut view, &mut thinking); - thinking = Some((key, line)); + thinking = Some(Thinking { + key, + line, + text: delta, + }); } flush(&mut view, &mut thinking); view From 200f5c4cac3cf97aeeb2b5549da0c4077689c052 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 22:23:47 +0800 Subject: [PATCH 09/25] feat(scenario-eval): judge the opening gate over a fixed three-probe family Gate 2 left a probe out when its current arm's counts left no headroom, so the observed pass count both admitted the probe into a smaller family and drove its p-value. The three opening probes are now one family fixed at m = 3 before any data: a probe whose gain is at most delta enters with p = 1 and still takes its rank, and Holm adjusts all three rows. A gain and its one-sided mid-p use each arm's own counted runs, so unequal judge exclusions change the p-value rather than eligibility; an arm with no counted run on a probe, or a family where no probe could gain more than delta, is inconclusive. The report applies the gate when the branch tool description is the evaluated text and the scenario set carries the three opening probes. A test pins the family at the three committed probes whatever the counts, and another pins that other texts and sets without those probes are not judged. The design text is updated in both languages. --- docs/design/timeline-branches.md | 2 +- docs/zh/design/timeline-branches.md | 2 +- xtask/src/rule.rs | 201 +++++++++++++++++++++++++++- xtask/src/scenario_eval.rs | 170 +++++++++++++++++++++++ 4 files changed, 372 insertions(+), 3 deletions(-) diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index ba35638721..65380fb9fc 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -571,7 +571,7 @@ A candidate for a policy text is put in place at that text's factory member ([mo The coordination text and the status notes are judged together, as one family, in the change that first puts a candidate for either in place ([model-facing prompts §8](model-prompts.md#8-judging-a-change)): the tool description at `BranchToolConfig.description`, the status notes at `BranchToolConfig.default_note`, `BranchToolConfig.user_default_note` and `BranchToolConfig.former_default_note`, and the roster's closing at `BranchToolConfig.roster_closing`. A later change to one of them re-runs the family, because a text that reads well alone can still lose a comparison another one wins. The opening text is judged on the should-open scenarios of §12.3 and, for this design, on `root-opens-after-switch`: a guard that let only the default branch open a line would make the root answer the request instead of opening one, and that scenario is where the difference shows. -**Gate 2, the opening rate.** The opening text is also judged against the opening probes: `line-opened-for-one-job` in `long-work-and-a-flaky-test` and in `refactor-and-a-pasted-report`, and `new-default-opens-a-line` in `switch-then-open-lines`. A probe is out of gate 2 when its current arm's counted runs at that round leave no statistical headroom: even a candidate that passed every counted run of its arm could not both gain more than `δ = 0.05` over the current arm and reach a one-sided mid-p at or below `α = 0.10`. An excluded probe stays in gate 1. Of the probes that remain, at least one must gain more than `δ` and reject at Holm-adjusted `α = 0.10` over that remaining family, and none may be a regression in gate 1. A candidate passes the opening text only when gate 1 (no regression, and the floor) and gate 2 both pass; a round whose counted runs leave gate 2 with no probe is inconclusive, because no gain was measured. The opening probes and the counts are fixed before the data. +**Gate 2, the opening rate.** The opening text is also judged against the opening probes: `line-opened-for-one-job` in `long-work-and-a-flaky-test` and in `refactor-and-a-pasted-report`, and `new-default-opens-a-line` in `switch-then-open-lines`. The three probes form one family, fixed before any data at `m = 3`; no probe leaves it whatever its counts. A probe's gain is `c₁/n₁ − c₀/n₀`, where `c₀` of `n₀` counted runs passed in the current arm and `c₁` of `n₁` in the candidate arm; the arms need not count the same runs, and the gain and its p-value use each arm's own counts. A probe enters with `p = 1` and cannot reject when its gain is at most `δ = 0.05`; it still takes its rank, so a probe at its ceiling never shrinks the family or loosens another probe's threshold. Otherwise its p-value is the one-sided mid-p Fisher exact test of "no gain" on `(c₀, n₀)` against `(c₁, n₁)`. Holm's step-down at `α = 0.10` runs over all three rows: the row at rank `i` of the ascending p-values is tested against `α / (4 − i)`, and none rejects after one fails. At least one probe must reject for the opening text to pass gate 2, and every opening probe is also a comparison of gate 1, where a significant fall is a regression. Gate 2 is inconclusive when an arm counted no run on a probe, so the comparison cannot be made ([model-facing prompts §8.1](model-prompts.md#81-the-rule)), or when no probe could gain more than `δ` even with a perfect candidate arm, because then no gain can be measured. A candidate passes the opening text only when gate 1 (no regression, and the floor) and gate 2 both pass. ## 13. Interactions diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index bd4330f55f..b23cdfa03f 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -538,7 +538,7 @@ WorkspaceTools 不变。 协调文字和状态说明合在一起判定,作为同一个族,由第一次为其中任何一段放入候选的改动来做([面向模型的提示词 §8](model-prompts.md#8-一次改动怎样判定)):工具描述在 `BranchToolConfig.description`、状态说明在 `BranchToolConfig.default_note`、`BranchToolConfig.user_default_note` 与 `BranchToolConfig.former_default_note`、名册的收尾句在 `BranchToolConfig.roster_closing`。以后改动其中一段就要重跑整个族,因为单独读着顺的文本,仍可能输给另一段文本赢下的对照。开线那段文字在 §12.3 的 should-open 场景上判定,对本设计还要加上 `root-opens-after-switch`:只让默认分支开线的守卫会让根去回答请求而不是开一条线,那个场景正是这个差别的落点。 -**门 2,开线率。** 开线那段文字还要按开线探针判定:`long-work-and-a-flaky-test` 与 `refactor-and-a-pasted-report` 的 `line-opened-for-one-job`,以及 `switch-then-open-lines` 的 `new-default-opens-a-line`。一条探针不计入门 2 的条件是:按那一轮的已判次数,就算候选臂每一次已判运行都通过,也不可能同时跨过 `δ = 0.05` 的增益和 `α = 0.10` 的单侧 mid-p。被排除的探针仍留在门 1。剩下的探针里,至少有一条要比当前臂增益超过 `δ`,并在该剩余族上按 Holm 校正的 `α = 0.10` 拒绝;任何开线探针显著下降都算门 1 的回退。候选只有门 1(不退步且达到下限)和门 2 都通过,才算通过开线文本;某一轮的计数让门 2 一条探针都不剩时判为 inconclusive,因为没有测到增益。开线探针和次数都在数据之前固定。 +**门 2,开线率。** 开线那段文字还要按开线探针判定:`long-work-and-a-flaky-test` 与 `refactor-and-a-pasted-report` 的 `line-opened-for-one-job`,以及 `switch-then-open-lines` 的 `new-default-opens-a-line`。这三条探针在数据之前固定成同一个族,`m = 3`;无论计数如何,任何探针都不离开这个族。一条探针的增益是 `c₁/n₁ − c₀/n₀`,其中当前臂的 `n₀` 次已判运行里有 `c₀` 次通过,候选臂的 `n₁` 次里有 `c₁` 次通过;两臂的已判次数不必相等,增益和 p 值各用自己臂的计数。增益不超过 `δ = 0.05` 的探针以 `p = 1` 进入族,不能拒绝;它仍占一个名次,所以天花板的探针不会缩小族,也不会放松别的探针的阈值。否则它的 p 值是对 `(c₀, n₀)` 与 `(c₁, n₁)` 的单侧 mid-p Fisher 精确检验,检验“没有增益”。Holm 逐步校正在 `α = 0.10` 上覆盖全部三行:按 p 值升序第 `i` 行按 `α / (4 − i)` 判定,某一行不拒绝后,后面的行都不再拒绝。至少要有一条探针拒绝,开线文字才通过门 2;每条开线探针同时也是门 1 的一条比较,显著下降就是回退。任一臂在一条探针上没有已判运行、比较做不出来时([面向模型的提示词 §8.1](model-prompts.md#81-规则)),或者就算候选臂全部通过也没有一条探针能增益超过 `δ` 时,门 2 判 inconclusive,因为量不到增益。候选只有门 1(不退步且达到下限)和门 2 都通过,才算通过开线文字。 ## 13. 相互影响 diff --git a/xtask/src/rule.rs b/xtask/src/rule.rs index 5c002a9e1d..00e721149a 100644 --- a/xtask/src/rule.rs +++ b/xtask/src/rule.rs @@ -8,7 +8,9 @@ //! a family-wise α. The verdict is `fail` when any comparison is a regression, //! `inconclusive` when none is but the floor is unmet or a comparison has no //! counted run to compare, and `pass` otherwise. There is no absolute pass -//! line. +//! line. A family whose rates should rise is judged by the same test with the +//! arms swapped: a gain at or under δ enters with p = 1, every comparison +//! stays in the family, and at least one gain must reject. /// The smallest loss that is tested: a comparison whose loss is at most δ /// enters the family with p = 1 and never rejects. @@ -120,11 +122,144 @@ impl Row { if self.rejected { "yes" } else { "no" }, ) } + /// The row's line in a gain table. A gain family's comparison carries its + /// arms swapped, so its `candidate` cell is the current arm's count and + /// its `loss` is the gain. + pub(crate) fn gain_line(&self) -> String { + let cell = |counts: Counts| match counts.rate() { + Some(rate) => format!("{}/{} ({rate:.3})", counts.outcome, counts.total), + None => "–".to_owned(), + }; + let gain = self + .loss + .map_or_else(|| "–".to_owned(), |gain| format!("{gain:.3}")); + format!( + "| {} | {} | {} | {gain} | {} | {:.4} | {} |", + self.name, + cell(self.candidate), + cell(self.current), + probability(self.p), + self.threshold, + if self.rejected { "yes" } else { "no" }, + ) + } } /// The comparison table's header, one row per comparison. pub(crate) const COMPARISON_HEADER: &str = "| comparison | current | candidate | loss | p | Holm threshold | rejected |\n| --- | --- | --- | --- | --- | --- | --- |\n"; +/// A gain table's header, one row per comparison. +pub(crate) const GAIN_HEADER: &str = "| gate 2 probe | current | candidate | gain | p | Holm threshold | rejected |\n| --- | --- | --- | --- | --- | --- | --- |\n"; + +/// One comparison of a family whose rates should rise, fixed before any data: +/// the report's name for it and both arms' counted pass rates. +#[derive(Clone, Debug)] +pub(crate) struct Gain { + pub name: String, + pub current: Counts, + pub candidate: Counts, +} + +/// A gain family's verdict. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GainVerdict { + Pass, + Fail, + Inconclusive, +} + +/// One gain family's rows and verdict. +#[derive(Clone, Debug)] +pub(crate) struct GainRule { + pub rows: Vec, + pub verdict: GainVerdict, +} + +/// Judges a family of gains fixed before any data with the same δ and Holm α +/// as a loss family: `pass` when at least one comparison's gain rejects, +/// `fail` when none does, and `inconclusive` when a comparison cannot be made +/// or no comparison had room to gain more than δ. Every comparison stays in +/// the family whatever its counts: one whose gain is at most δ enters with +/// p = 1 and cannot reject, but still takes its rank, so a probe at its +/// ceiling never shrinks the family or loosens another threshold. +pub(crate) fn judge_gains(gains: &[Gain]) -> GainRule { + let mut rows: Vec = gains + .iter() + .map(|gain| { + Row::of(&Comparison { + name: gain.name.clone(), + worse: Worse::Lower, + current: gain.candidate, + candidate: gain.current, + }) + }) + .collect(); + holm(&mut rows); + let incomplete = rows.iter().any(|row| row.loss.is_none()); + let headroom = gains.iter().any(has_headroom); + let verdict = if incomplete || !headroom { + GainVerdict::Inconclusive + } else if rows.iter().any(|row| row.rejected) { + GainVerdict::Pass + } else { + GainVerdict::Fail + }; + GainRule { rows, verdict } +} + +/// Whether a perfect candidate arm could gain more than δ over the probe: +/// `1 − current.outcome/current.total > 1/20`, decided in integers. +fn has_headroom(gain: &Gain) -> bool { + 20 * (gain.current.total - gain.current.outcome) > gain.current.total +} + +/// The gain verdict as a report line: the comparisons that rejected, or why +/// the gate cannot pass. +pub(crate) fn gain_verdict_line(rule: &GainRule, subject: &str) -> String { + match rule.verdict { + GainVerdict::Pass => { + let rejected: Vec = rule + .rows + .iter() + .filter(|row| row.rejected) + .map(|row| { + format!( + "{} gains from {:.3} to {:.3} (gain {}, p {}, Holm threshold {:.4})", + row.name, + row.candidate.rate().unwrap_or(0.), + row.current.rate().unwrap_or(0.), + row.loss + .map_or_else(|| "–".to_owned(), |gain| format!("{gain:.3}")), + probability(row.p), + row.threshold, + ) + }) + .collect(); + format!("{subject} passes gate 2: {}.", rejected.join("; ")) + } + GainVerdict::Fail => format!( + "{subject} fails gate 2: no probe gains more than {DELTA:.2} and rejects at Holm-adjusted {ALPHA:.2}." + ), + GainVerdict::Inconclusive => { + let mut reasons: Vec = rule + .rows + .iter() + .filter(|row| row.loss.is_none()) + .map(|row| format!("{} has no counted run in an arm", row.name)) + .collect(); + if reasons.is_empty() { + reasons.push(format!( + "no probe could gain more than {DELTA:.2} over its current arm" + )); + } + format!( + "{subject} is inconclusive on gate 2: {}.", + reasons.join(", and ") + ) + } + } +} + /// The three-valued verdict (`fail`, `pass` or `inconclusive`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Verdict { @@ -329,6 +464,14 @@ mod tests { fn close(left: f64, right: f64) -> bool { (left - right).abs() < 1e-9 } + /// One gain comparison with both arms' counted passes and runs. + fn gain(name: &str, current: (u64, u64), candidate: (u64, u64)) -> Gain { + Gain { + name: name.into(), + current: Counts::new(current.0, current.1), + candidate: Counts::new(candidate.0, candidate.1), + } + } /// The mid-p values against references computed independently with exact /// rational arithmetic and stated here as the fractions they are: small @@ -510,4 +653,60 @@ mod tests { assert_eq!(rule.rows[0].loss, None); assert_eq!(rule.verdict, Verdict::Inconclusive); } + + /// A gain at or under δ enters the fixed family with p = 1 even where the + /// test alone would reject, and the comparison still takes its rank. + #[test] + fn a_gain_at_or_under_delta_enters_with_p_one() { + let rule = judge_gains(&[gain("probe", (900, 1000), (950, 1000))]); + assert_eq!(rule.rows[0].p, 1., "the gain is exactly δ"); + assert!(!rule.rows[0].rejected); + assert_eq!(rule.verdict, GainVerdict::Fail); + } + + /// The gain test uses each arm's own counted runs: a perfect candidate of + /// eight has p .050 against a current 5/8, and a perfect candidate of + /// three has .170, so unequal judge exclusions change the p-value, not the + /// family. + #[test] + fn a_gain_test_uses_each_arms_own_counted_runs() { + let rule = judge_gains(&[gain("probe", (5, 8), (8, 8))]); + assert!(close(rule.rows[0].p, 0.05), "{}", rule.rows[0].p); + let rule = judge_gains(&[gain("probe", (5, 8), (3, 3))]); + assert!(close(rule.rows[0].p, 28. / 165.), "{}", rule.rows[0].p); + let rule = judge_gains(&[gain("probe", (5, 8), (0, 0))]); + assert_eq!(rule.rows[0].loss, None); + assert_eq!(rule.verdict, GainVerdict::Inconclusive); + } + + /// Every probe stays in the gain family: the family is the rows the caller + /// fixed before the data, and Holm's ordered thresholds and step-down + /// apply over all three even when a probe cannot reject. + #[test] + fn the_gain_family_keeps_every_probe_through_holm() { + let rule = judge_gains(&[ + gain("a", (3, 56), (14, 56)), + gain("b", (5, 8), (5, 5)), + gain("c", (56, 56), (56, 56)), + ]); + assert_eq!(rule.rows.len(), 3); + assert_eq!(rule.rows[0].threshold, 0.1 / 3.); + assert_eq!(rule.rows[1].threshold, 0.1 / 2.); + assert_eq!(rule.rows[2].threshold, 0.1); + assert!(rule.rows[0].rejected, "p {} under 0.10/3", rule.rows[0].p); + assert!(!rule.rows[1].rejected, "p {} over 0.10/2", rule.rows[1].p); + assert!(!rule.rows[2].rejected, "the step-down already stopped"); + assert_eq!(rule.verdict, GainVerdict::Pass); + } + + /// A gate with no room to gain is inconclusive, not a fail: no probe can + /// show a gain over its current arm, so the round measured none. + #[test] + fn a_gain_family_without_headroom_is_inconclusive() { + let rule = judge_gains(&[gain("ceiling", (56, 56), (56, 56))]); + assert_eq!(rule.rows[0].p, 1.); + assert_eq!(rule.verdict, GainVerdict::Inconclusive); + let rule = judge_gains(&[gain("near-ceiling", (55, 56), (56, 56))]); + assert_eq!(rule.verdict, GainVerdict::Inconclusive); + } } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 562f3496c1..d29c2fc6ba 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -43,6 +43,15 @@ //! 20 judged runs of every scenario, and `inconclusive` otherwise — also when //! a comparison has no counted run in an arm. There is no absolute pass line. //! +//! When the evaluation configures `timeline-tree/branch-description` and its +//! scenario set carries the three opening probes, the report also applies the +//! opening text's gate 2 (Timeline branches §12.4): the three opening probes +//! form one family fixed at `m = 3`, each entering with its own arm's counted +//! runs, a probe whose gain is at most `δ = 0.05` enters with p = 1, and at +//! least one must gain more than δ and reject at Holm-adjusted `α = 0.10`. An +//! arm with no counted run on a probe, or a family where no probe could gain +//! more than δ, makes gate 2 inconclusive. +//! //! A failed run is one that ended on an error or its wall-clock budget, or //! one whose judging did not happen: there was nothing the judge could be //! asked, or a judge call failed — the first call, its retry without a @@ -8786,6 +8795,57 @@ fn comparisons(current: &Metrics, candidate: &Metrics, scenarios: &[Scenario]) - comparisons } +/// The opening text's three probes, fixed before any data (Timeline branches +/// §12.4). Every one stays in gate 2's family whatever its counts. +const OPENING_PROBES: [(&str, &str); 3] = [ + ("long-work-and-a-flaky-test", "line-opened-for-one-job"), + ("refactor-and-a-pasted-report", "line-opened-for-one-job"), + ("switch-then-open-lines", "new-default-opens-a-line"), +]; + +/// The text whose evaluation gate 2 applies to: the branch tool's opening +/// description. +const OPENING_TEXT: &str = "timeline-tree/branch-description"; + +/// Gate 2 over the fixed opening-probe family (Timeline branches §12.4): at +/// least one probe gains more than δ and rejects at Holm-adjusted α, and every +/// probe enters with its own counts whatever they are. +fn opening_gate(current: &Metrics, candidate: &Metrics) -> rule::GainRule { + let counts = |metrics: &Metrics, scenario: &str, probe: &str| { + let counts = metrics.counts(&(scenario.to_owned(), probe.to_owned())); + rule::Counts::new(counts.passed.into(), counts.runs.into()) + }; + let gains = OPENING_PROBES.map(|(scenario, probe)| rule::Gain { + name: format!("{scenario}/{probe}"), + current: counts(current, scenario, probe), + candidate: counts(candidate, scenario, probe), + }); + rule::judge_gains(&gains) +} + +/// Whether the evaluation configured the opening text, in this evaluation or +/// in the saved runs it pooled. +fn evaluates_opening_text(instrument: &Instrument, records: &[RunRecord]) -> bool { + instrument.texts.iter().any(|text| text == OPENING_TEXT) + || records + .iter() + .any(|record| record.texts.iter().any(|text| text.id == OPENING_TEXT)) +} + +/// Whether the scenario set carries all three opening probes, so gate 2 can +/// be judged at all; a set without them is not the opening text's evaluation. +fn has_opening_probes(scenarios: &[Scenario]) -> bool { + OPENING_PROBES.iter().all(|(scenario, probe_id)| { + scenarios.iter().any(|candidate| { + candidate.id == *scenario + && candidate + .probes + .iter() + .any(|probe| probe.id == *probe_id && probe.kind == ProbeKind::MustShow) + }) + }) +} + /// The finished evaluations a report was built from, in the order given: each /// directory with the runs it supplied. Such a report names them, and leaves /// out what no saved run records. @@ -9125,6 +9185,18 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] "candidate", )); text.push('\n'); + if evaluates_opening_text(instrument, records) && has_opening_probes(scenarios) { + let gate = opening_gate(current, candidate); + text.push_str("\n**Gate 2, the opening rate.**\n\n"); + text.push_str(rule::GAIN_HEADER); + for row in &gate.rows { + text += &row.gain_line(); + text.push('\n'); + } + text.push('\n'); + text.push_str(&rule::gain_verdict_line(&gate, "candidate")); + text.push('\n'); + } text } @@ -10849,6 +10921,27 @@ mod tests { ); } + /// Gate 2's fixed probe list is the committed scenarios' own: a rename in a + /// scenario cannot move the family without failing here. + #[test] + fn the_opening_gate_names_the_committed_opening_probes() { + let root = repository().join("xtask").join("scenario-eval"); + let branches = read_scenarios(&root.join("timeline-branches")).unwrap(); + for (scenario, probe_id) in OPENING_PROBES { + let committed = branches + .iter() + .find(|candidate| candidate.id == scenario) + .unwrap_or_else(|| panic!("{scenario} is in the committed set")); + assert!( + committed + .probes + .iter() + .any(|probe| probe.id == probe_id && probe.kind == ProbeKind::MustShow), + "{scenario} pre-registers {probe_id} as a must_show probe" + ); + } + } + /// The opening scenarios pre-register the probe that their runs open one /// line for one job, and the compact scenario asks the user for the parser /// line (Timeline branches §12.3). No model runs, so CI catches a drift in @@ -11952,6 +12045,83 @@ mod tests { ); } + /// Gate 2 applies to the opening text's evaluation and keeps its three + /// probes as one family: a probe at its ceiling enters with p = 1, and one + /// rejecting probe passes the gate (Timeline branches §12.4). + #[test] + fn the_report_judges_gate_2_for_the_opening_text() { + let scenarios: Vec = OPENING_PROBES + .iter() + .map(|(id, probe_id)| Scenario { + id: (*id).into(), + probes: vec![probe(probe_id, ProbeKind::MustShow)], + ..scenario(Vec::new()) + }) + .collect(); + let mut records = Vec::new(); + for scenario in &scenarios { + let probe_id = scenario.probes[0].id.as_str(); + let current_passes = scenario.id != "long-work-and-a-flaky-test"; + for _ in 0..20 { + records.push(record( + "current", + scenario, + &[( + probe_id, + if current_passes { + ProbeVerdict::Present + } else { + ProbeVerdict::Absent + }, + )], + JudgeOutcome::Judged, + )); + records.push(record( + "candidate", + scenario, + &[(probe_id, ProbeVerdict::Present)], + JudgeOutcome::Judged, + )); + } + } + let mut opening = instrument(model()); + opening.texts = vec![OPENING_TEXT.into()]; + let text = report(&opening, &scenarios, &records); + assert!(text.contains("**Gate 2, the opening rate.**"), "{text}"); + assert!( + text.contains( + "| long-work-and-a-flaky-test/line-opened-for-one-job | 0/20 (0.000) | 20/20 (1.000) | 1.000 |" + ), + "{text}" + ); + assert!( + text.contains( + "candidate passes gate 2: long-work-and-a-flaky-test/line-opened-for-one-job gains from 0.000 to 1.000" + ), + "{text}" + ); + assert!( + text.contains( + "| refactor-and-a-pasted-report/line-opened-for-one-job | 20/20 (1.000) | 20/20 (1.000) | 0.000 | 1 |" + ), + "a probe at its ceiling enters with p = 1: {text}" + ); + let text = report(&instrument(model()), &scenarios, &records); + assert!( + !text.contains("Gate 2"), + "other texts do not judge it: {text}" + ); + let text = report( + &opening, + &[scenario(vec![probe("reports", ProbeKind::MustShow)])], + &[], + ); + assert!( + !text.contains("Gate 2"), + "a set without the opening probes cannot judge it: {text}" + ); + } + /// Twenty runs an arm whose every judge call failed are not twenty judged /// runs: the probe rows have nothing to compare, so the verdict is /// inconclusive and never `pass` (model-prompts §8.1). From c19ebcb9916ebfd45c4ddcdd1fc9719767bcec6c Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:24:54 +0800 Subject: [PATCH 10/25] refactor(scenario-eval): keep gate 2 in the design text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The report judged gate 2 whenever the branch tool description was the evaluated text and the scenario set carried the three opening probes. No evaluation configured that text, so nothing but the new tests reached the code, and the verdict line at the top of the report still judged gate 1 alone. The design text in §12.4 stays: the three probes are one family fixed at m = 3, a probe at or under delta enters with p = 1 and keeps its rank, Holm at alpha = 0.10 runs over all three rows, and an arm with no counted run or a family with no headroom is inconclusive. The report prints gate 1 only, as it did before, and the implementation follows in the change that runs the opening text. --- xtask/src/rule.rs | 201 +------------------------------------ xtask/src/scenario_eval.rs | 149 --------------------------- 2 files changed, 1 insertion(+), 349 deletions(-) diff --git a/xtask/src/rule.rs b/xtask/src/rule.rs index 00e721149a..5c002a9e1d 100644 --- a/xtask/src/rule.rs +++ b/xtask/src/rule.rs @@ -8,9 +8,7 @@ //! a family-wise α. The verdict is `fail` when any comparison is a regression, //! `inconclusive` when none is but the floor is unmet or a comparison has no //! counted run to compare, and `pass` otherwise. There is no absolute pass -//! line. A family whose rates should rise is judged by the same test with the -//! arms swapped: a gain at or under δ enters with p = 1, every comparison -//! stays in the family, and at least one gain must reject. +//! line. /// The smallest loss that is tested: a comparison whose loss is at most δ /// enters the family with p = 1 and never rejects. @@ -122,144 +120,11 @@ impl Row { if self.rejected { "yes" } else { "no" }, ) } - /// The row's line in a gain table. A gain family's comparison carries its - /// arms swapped, so its `candidate` cell is the current arm's count and - /// its `loss` is the gain. - pub(crate) fn gain_line(&self) -> String { - let cell = |counts: Counts| match counts.rate() { - Some(rate) => format!("{}/{} ({rate:.3})", counts.outcome, counts.total), - None => "–".to_owned(), - }; - let gain = self - .loss - .map_or_else(|| "–".to_owned(), |gain| format!("{gain:.3}")); - format!( - "| {} | {} | {} | {gain} | {} | {:.4} | {} |", - self.name, - cell(self.candidate), - cell(self.current), - probability(self.p), - self.threshold, - if self.rejected { "yes" } else { "no" }, - ) - } } /// The comparison table's header, one row per comparison. pub(crate) const COMPARISON_HEADER: &str = "| comparison | current | candidate | loss | p | Holm threshold | rejected |\n| --- | --- | --- | --- | --- | --- | --- |\n"; -/// A gain table's header, one row per comparison. -pub(crate) const GAIN_HEADER: &str = "| gate 2 probe | current | candidate | gain | p | Holm threshold | rejected |\n| --- | --- | --- | --- | --- | --- | --- |\n"; - -/// One comparison of a family whose rates should rise, fixed before any data: -/// the report's name for it and both arms' counted pass rates. -#[derive(Clone, Debug)] -pub(crate) struct Gain { - pub name: String, - pub current: Counts, - pub candidate: Counts, -} - -/// A gain family's verdict. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum GainVerdict { - Pass, - Fail, - Inconclusive, -} - -/// One gain family's rows and verdict. -#[derive(Clone, Debug)] -pub(crate) struct GainRule { - pub rows: Vec, - pub verdict: GainVerdict, -} - -/// Judges a family of gains fixed before any data with the same δ and Holm α -/// as a loss family: `pass` when at least one comparison's gain rejects, -/// `fail` when none does, and `inconclusive` when a comparison cannot be made -/// or no comparison had room to gain more than δ. Every comparison stays in -/// the family whatever its counts: one whose gain is at most δ enters with -/// p = 1 and cannot reject, but still takes its rank, so a probe at its -/// ceiling never shrinks the family or loosens another threshold. -pub(crate) fn judge_gains(gains: &[Gain]) -> GainRule { - let mut rows: Vec = gains - .iter() - .map(|gain| { - Row::of(&Comparison { - name: gain.name.clone(), - worse: Worse::Lower, - current: gain.candidate, - candidate: gain.current, - }) - }) - .collect(); - holm(&mut rows); - let incomplete = rows.iter().any(|row| row.loss.is_none()); - let headroom = gains.iter().any(has_headroom); - let verdict = if incomplete || !headroom { - GainVerdict::Inconclusive - } else if rows.iter().any(|row| row.rejected) { - GainVerdict::Pass - } else { - GainVerdict::Fail - }; - GainRule { rows, verdict } -} - -/// Whether a perfect candidate arm could gain more than δ over the probe: -/// `1 − current.outcome/current.total > 1/20`, decided in integers. -fn has_headroom(gain: &Gain) -> bool { - 20 * (gain.current.total - gain.current.outcome) > gain.current.total -} - -/// The gain verdict as a report line: the comparisons that rejected, or why -/// the gate cannot pass. -pub(crate) fn gain_verdict_line(rule: &GainRule, subject: &str) -> String { - match rule.verdict { - GainVerdict::Pass => { - let rejected: Vec = rule - .rows - .iter() - .filter(|row| row.rejected) - .map(|row| { - format!( - "{} gains from {:.3} to {:.3} (gain {}, p {}, Holm threshold {:.4})", - row.name, - row.candidate.rate().unwrap_or(0.), - row.current.rate().unwrap_or(0.), - row.loss - .map_or_else(|| "–".to_owned(), |gain| format!("{gain:.3}")), - probability(row.p), - row.threshold, - ) - }) - .collect(); - format!("{subject} passes gate 2: {}.", rejected.join("; ")) - } - GainVerdict::Fail => format!( - "{subject} fails gate 2: no probe gains more than {DELTA:.2} and rejects at Holm-adjusted {ALPHA:.2}." - ), - GainVerdict::Inconclusive => { - let mut reasons: Vec = rule - .rows - .iter() - .filter(|row| row.loss.is_none()) - .map(|row| format!("{} has no counted run in an arm", row.name)) - .collect(); - if reasons.is_empty() { - reasons.push(format!( - "no probe could gain more than {DELTA:.2} over its current arm" - )); - } - format!( - "{subject} is inconclusive on gate 2: {}.", - reasons.join(", and ") - ) - } - } -} - /// The three-valued verdict (`fail`, `pass` or `inconclusive`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Verdict { @@ -464,14 +329,6 @@ mod tests { fn close(left: f64, right: f64) -> bool { (left - right).abs() < 1e-9 } - /// One gain comparison with both arms' counted passes and runs. - fn gain(name: &str, current: (u64, u64), candidate: (u64, u64)) -> Gain { - Gain { - name: name.into(), - current: Counts::new(current.0, current.1), - candidate: Counts::new(candidate.0, candidate.1), - } - } /// The mid-p values against references computed independently with exact /// rational arithmetic and stated here as the fractions they are: small @@ -653,60 +510,4 @@ mod tests { assert_eq!(rule.rows[0].loss, None); assert_eq!(rule.verdict, Verdict::Inconclusive); } - - /// A gain at or under δ enters the fixed family with p = 1 even where the - /// test alone would reject, and the comparison still takes its rank. - #[test] - fn a_gain_at_or_under_delta_enters_with_p_one() { - let rule = judge_gains(&[gain("probe", (900, 1000), (950, 1000))]); - assert_eq!(rule.rows[0].p, 1., "the gain is exactly δ"); - assert!(!rule.rows[0].rejected); - assert_eq!(rule.verdict, GainVerdict::Fail); - } - - /// The gain test uses each arm's own counted runs: a perfect candidate of - /// eight has p .050 against a current 5/8, and a perfect candidate of - /// three has .170, so unequal judge exclusions change the p-value, not the - /// family. - #[test] - fn a_gain_test_uses_each_arms_own_counted_runs() { - let rule = judge_gains(&[gain("probe", (5, 8), (8, 8))]); - assert!(close(rule.rows[0].p, 0.05), "{}", rule.rows[0].p); - let rule = judge_gains(&[gain("probe", (5, 8), (3, 3))]); - assert!(close(rule.rows[0].p, 28. / 165.), "{}", rule.rows[0].p); - let rule = judge_gains(&[gain("probe", (5, 8), (0, 0))]); - assert_eq!(rule.rows[0].loss, None); - assert_eq!(rule.verdict, GainVerdict::Inconclusive); - } - - /// Every probe stays in the gain family: the family is the rows the caller - /// fixed before the data, and Holm's ordered thresholds and step-down - /// apply over all three even when a probe cannot reject. - #[test] - fn the_gain_family_keeps_every_probe_through_holm() { - let rule = judge_gains(&[ - gain("a", (3, 56), (14, 56)), - gain("b", (5, 8), (5, 5)), - gain("c", (56, 56), (56, 56)), - ]); - assert_eq!(rule.rows.len(), 3); - assert_eq!(rule.rows[0].threshold, 0.1 / 3.); - assert_eq!(rule.rows[1].threshold, 0.1 / 2.); - assert_eq!(rule.rows[2].threshold, 0.1); - assert!(rule.rows[0].rejected, "p {} under 0.10/3", rule.rows[0].p); - assert!(!rule.rows[1].rejected, "p {} over 0.10/2", rule.rows[1].p); - assert!(!rule.rows[2].rejected, "the step-down already stopped"); - assert_eq!(rule.verdict, GainVerdict::Pass); - } - - /// A gate with no room to gain is inconclusive, not a fail: no probe can - /// show a gain over its current arm, so the round measured none. - #[test] - fn a_gain_family_without_headroom_is_inconclusive() { - let rule = judge_gains(&[gain("ceiling", (56, 56), (56, 56))]); - assert_eq!(rule.rows[0].p, 1.); - assert_eq!(rule.verdict, GainVerdict::Inconclusive); - let rule = judge_gains(&[gain("near-ceiling", (55, 56), (56, 56))]); - assert_eq!(rule.verdict, GainVerdict::Inconclusive); - } } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index d29c2fc6ba..b0dde99b9d 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -43,15 +43,6 @@ //! 20 judged runs of every scenario, and `inconclusive` otherwise — also when //! a comparison has no counted run in an arm. There is no absolute pass line. //! -//! When the evaluation configures `timeline-tree/branch-description` and its -//! scenario set carries the three opening probes, the report also applies the -//! opening text's gate 2 (Timeline branches §12.4): the three opening probes -//! form one family fixed at `m = 3`, each entering with its own arm's counted -//! runs, a probe whose gain is at most `δ = 0.05` enters with p = 1, and at -//! least one must gain more than δ and reject at Holm-adjusted `α = 0.10`. An -//! arm with no counted run on a probe, or a family where no probe could gain -//! more than δ, makes gate 2 inconclusive. -//! //! A failed run is one that ended on an error or its wall-clock budget, or //! one whose judging did not happen: there was nothing the judge could be //! asked, or a judge call failed — the first call, its retry without a @@ -8795,57 +8786,6 @@ fn comparisons(current: &Metrics, candidate: &Metrics, scenarios: &[Scenario]) - comparisons } -/// The opening text's three probes, fixed before any data (Timeline branches -/// §12.4). Every one stays in gate 2's family whatever its counts. -const OPENING_PROBES: [(&str, &str); 3] = [ - ("long-work-and-a-flaky-test", "line-opened-for-one-job"), - ("refactor-and-a-pasted-report", "line-opened-for-one-job"), - ("switch-then-open-lines", "new-default-opens-a-line"), -]; - -/// The text whose evaluation gate 2 applies to: the branch tool's opening -/// description. -const OPENING_TEXT: &str = "timeline-tree/branch-description"; - -/// Gate 2 over the fixed opening-probe family (Timeline branches §12.4): at -/// least one probe gains more than δ and rejects at Holm-adjusted α, and every -/// probe enters with its own counts whatever they are. -fn opening_gate(current: &Metrics, candidate: &Metrics) -> rule::GainRule { - let counts = |metrics: &Metrics, scenario: &str, probe: &str| { - let counts = metrics.counts(&(scenario.to_owned(), probe.to_owned())); - rule::Counts::new(counts.passed.into(), counts.runs.into()) - }; - let gains = OPENING_PROBES.map(|(scenario, probe)| rule::Gain { - name: format!("{scenario}/{probe}"), - current: counts(current, scenario, probe), - candidate: counts(candidate, scenario, probe), - }); - rule::judge_gains(&gains) -} - -/// Whether the evaluation configured the opening text, in this evaluation or -/// in the saved runs it pooled. -fn evaluates_opening_text(instrument: &Instrument, records: &[RunRecord]) -> bool { - instrument.texts.iter().any(|text| text == OPENING_TEXT) - || records - .iter() - .any(|record| record.texts.iter().any(|text| text.id == OPENING_TEXT)) -} - -/// Whether the scenario set carries all three opening probes, so gate 2 can -/// be judged at all; a set without them is not the opening text's evaluation. -fn has_opening_probes(scenarios: &[Scenario]) -> bool { - OPENING_PROBES.iter().all(|(scenario, probe_id)| { - scenarios.iter().any(|candidate| { - candidate.id == *scenario - && candidate - .probes - .iter() - .any(|probe| probe.id == *probe_id && probe.kind == ProbeKind::MustShow) - }) - }) -} - /// The finished evaluations a report was built from, in the order given: each /// directory with the runs it supplied. Such a report names them, and leaves /// out what no saved run records. @@ -9185,18 +9125,6 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] "candidate", )); text.push('\n'); - if evaluates_opening_text(instrument, records) && has_opening_probes(scenarios) { - let gate = opening_gate(current, candidate); - text.push_str("\n**Gate 2, the opening rate.**\n\n"); - text.push_str(rule::GAIN_HEADER); - for row in &gate.rows { - text += &row.gain_line(); - text.push('\n'); - } - text.push('\n'); - text.push_str(&rule::gain_verdict_line(&gate, "candidate")); - text.push('\n'); - } text } @@ -12045,83 +11973,6 @@ mod tests { ); } - /// Gate 2 applies to the opening text's evaluation and keeps its three - /// probes as one family: a probe at its ceiling enters with p = 1, and one - /// rejecting probe passes the gate (Timeline branches §12.4). - #[test] - fn the_report_judges_gate_2_for_the_opening_text() { - let scenarios: Vec = OPENING_PROBES - .iter() - .map(|(id, probe_id)| Scenario { - id: (*id).into(), - probes: vec![probe(probe_id, ProbeKind::MustShow)], - ..scenario(Vec::new()) - }) - .collect(); - let mut records = Vec::new(); - for scenario in &scenarios { - let probe_id = scenario.probes[0].id.as_str(); - let current_passes = scenario.id != "long-work-and-a-flaky-test"; - for _ in 0..20 { - records.push(record( - "current", - scenario, - &[( - probe_id, - if current_passes { - ProbeVerdict::Present - } else { - ProbeVerdict::Absent - }, - )], - JudgeOutcome::Judged, - )); - records.push(record( - "candidate", - scenario, - &[(probe_id, ProbeVerdict::Present)], - JudgeOutcome::Judged, - )); - } - } - let mut opening = instrument(model()); - opening.texts = vec![OPENING_TEXT.into()]; - let text = report(&opening, &scenarios, &records); - assert!(text.contains("**Gate 2, the opening rate.**"), "{text}"); - assert!( - text.contains( - "| long-work-and-a-flaky-test/line-opened-for-one-job | 0/20 (0.000) | 20/20 (1.000) | 1.000 |" - ), - "{text}" - ); - assert!( - text.contains( - "candidate passes gate 2: long-work-and-a-flaky-test/line-opened-for-one-job gains from 0.000 to 1.000" - ), - "{text}" - ); - assert!( - text.contains( - "| refactor-and-a-pasted-report/line-opened-for-one-job | 20/20 (1.000) | 20/20 (1.000) | 0.000 | 1 |" - ), - "a probe at its ceiling enters with p = 1: {text}" - ); - let text = report(&instrument(model()), &scenarios, &records); - assert!( - !text.contains("Gate 2"), - "other texts do not judge it: {text}" - ); - let text = report( - &opening, - &[scenario(vec![probe("reports", ProbeKind::MustShow)])], - &[], - ); - assert!( - !text.contains("Gate 2"), - "a set without the opening probes cannot judge it: {text}" - ); - } - /// Twenty runs an arm whose every judge call failed are not twenty judged /// runs: the probe rows have nothing to compare, so the verdict is /// inconclusive and never `pass` (model-prompts §8.1). From 12e36fdfe666c97f9e21b1ae98401e996c52e534 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:25:01 +0800 Subject: [PATCH 11/25] fix(scenario-eval): place a request by the turn it ran in A `step/model-start` without a turn id took the empty string, so every such start fell into one turn: a note check that means to read only the turn that consumed the input fell back to a scan of the branch, and a request a later turn started could stand in for one that never reached the model. A start without a turn id now joins no other start's turn and takes neither exemption: neither the steer that replaced it nor the stop that ended it can be placed without the turn. The test with a replaced request states the turn it ran in, as every recorded export does. A start without one that has no model call is still reported. --- xtask/src/scenario_eval.rs | 87 +++++++++++++++++++++++++++++++------- 1 file changed, 71 insertions(+), 16 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index b0dde99b9d..932cf8e192 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -6110,7 +6110,9 @@ fn switch_note_failure(driven: &Driven, export: &str) -> Option { /// turn-budget stop ended, whose reason `cap_stop` carries: that stop, not the /// note, kept it from the model (issue #2140). Every other request that never /// reached the model is reported, because no request of the line carried the -/// text being evaluated. +/// text being evaluated. A request whose `step/model-start` carries no turn id +/// is exempted by neither: without the turn, neither the steer that replaced +/// it nor the stop that ended it can be placed. fn switch_notes_unseen( export: &str, notes: &[SwitchNote], @@ -6123,9 +6125,10 @@ fn switch_notes_unseen( note: Option, } /// One `step/model-start`: the request it began, and its line and turn. + /// `turn` is `None` when the start carries no turn id. struct Start { branch: String, - turn: String, + turn: Option, sequence: u64, request: String, } @@ -6167,10 +6170,7 @@ fn switch_notes_unseen( (Some("step"), Some("model-start")) => { if let Some(request) = event["data"]["request_id"].as_str() { starts.push(Start { - turn: event["data"]["turn_id"] - .as_str() - .unwrap_or_default() - .to_owned(), + turn: event["data"]["turn_id"].as_str().map(str::to_owned), branch, sequence, request: request.to_owned(), @@ -6228,9 +6228,12 @@ fn switch_notes_unseen( .filter(|start| &start.branch == branch && start.sequence < *at) .filter(|start| { let request = (start.branch.clone(), start.request.clone()); - let turn = (start.branch.clone(), start.turn.clone()); + let turn = start + .turn + .as_ref() + .map(|turn| (start.branch.clone(), turn.clone())); !ended.get(&request).is_some_and(|end| end < at) - && !ended_turns.get(&turn).is_some_and(|end| end < at) + && !turn.is_some_and(|turn| ended_turns.get(&turn).is_some_and(|end| end < at)) }) .max_by_key(|start| start.sequence) { @@ -6266,7 +6269,8 @@ fn switch_notes_unseen( // A steer replaces a request inside the turn that began it, so the // requests that can answer for this note are that turn's own: a later // turn's request carries the note as context and cannot stand in for a - // request that never reached the model. + // request that never reached the model. A start without a turn id + // joins no other start's turn, and the loop below exempts none of them. let turn = first.turn.clone(); requests.retain(|start| start.turn == turn); // A steer can replace the request a line began before it reaches the @@ -6281,11 +6285,13 @@ fn switch_notes_unseen( call = Some(found); break; } - if replaced.contains(&key) { - continue; - } - if cut.contains(&key) { - continue 'notes; + if start.turn.is_some() { + if replaced.contains(&key) { + continue; + } + if cut.contains(&key) { + continue 'notes; + } } break; } @@ -9946,14 +9952,14 @@ mod tests { "data": {"input_id": "f1"}}}), json!({"kind": "event", "branch_id": "2", "event": {"id": "s1", "sequence": 4, "type": "step", "name": "model-start", - "data": {"request_id": "r1"}}}), + "data": {"turn_id": "t1", "request_id": "r1"}}}), json!({"kind": "event", "branch_id": "2", "event": {"id": "o1", "sequence": 5, "type": "step", "name": "model-output-end", "data": {"turn_id": "t1", "request_id": "r1", "status": "cancelled", "reason": "replaced by steer"}}}), json!({"kind": "event", "branch_id": "2", "event": {"id": "s2", "sequence": 6, "type": "step", "name": "model-start", - "data": {"request_id": "r2"}}}), + "data": {"turn_id": "t1", "request_id": "r2"}}}), json!({"kind": "event", "branch_id": "2", "event": {"id": "m2", "sequence": 7, "type": "model", "name": "call", "data": {"request_id": "r2", @@ -10269,6 +10275,55 @@ mod tests { } } + /// A start that carries no turn id is not exempted by the turn-budget stop + /// the way a placed request is: without the turn, nothing says the stop + /// found this request in flight, and grouping every such start under one + /// turn would drop the turn the check reads (Timeline branches §12.4). + #[test] + fn a_start_without_a_turn_id_is_exempted_by_no_stop() { + let note = "\nswitched from line main.\n"; + let event = |sequence: u64, id: &str, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": "2", + "event": {"id": id, "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + }; + let notes = [SwitchNote { + line: "2".into(), + input: "f1".into(), + default: true, + other: "main".into(), + }]; + let export = [ + event( + 1, + "n1", + ["input", "message"], + json!({"blocks": [{"type": "raw", "key": "branch:line", "text": note}]}), + ), + event(2, "f1", ["input", "message"], json!({})), + event(3, "c1", ["input", "consumed"], json!({"input_id": "f1"})), + event( + 4, + "s1", + ["step", "model-start"], + json!({"request_id": "r1"}), + ), + event( + 5, + "i1", + ["stop", "interrupt"], + json!({"reason": "budget: turns", "scope": "turn"}), + ), + ] + .iter() + .map(|record| serde_json::to_string(record).unwrap()) + .collect::>() + .join("\n"); + let unseen = switch_notes_unseen(&export, ¬es, Some("budget: turns")) + .expect("an unplaced request is not exempted by the stop"); + assert!(unseen.contains("never reached the model"), "{unseen}"); + } + /// A turn-budget stop does not hide a request that reached the model /// without the note: the stop explains a request that never reached the /// model, not one that did (Timeline branches §12.4). From 8c7520c0defe430ec3ab82917b240061db21f670 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:25:09 +0800 Subject: [PATCH 12/25] test(scenario-eval): write the cap's interrupt with the scope it has The turn-budget fixtures wrote `stop/interrupt` with scope `branch`, which is the scope a Timeline closes with, not the one `session.stop` writes: the cap stops the turn it found in flight, so its interrupt carries scope `turn`. The check reads the reason and not the scope, so the fixtures passed either way; they now record the event the runtime writes, so a later check that reads the scope sees the real one. --- xtask/src/scenario_eval.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 932cf8e192..c41dce2cd1 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -10060,7 +10060,7 @@ mod tests { "data": {"turn_id": "t1", "request_id": "r1"}}}), json!({"kind": "event", "branch_id": "2", "event": {"id": "i1", "sequence": 5, "type": "stop", "name": "interrupt", - "data": {"reason": "budget: turns", "scope": "branch"}}}), + "data": {"reason": "budget: turns", "scope": "turn"}}}), json!({"kind": "event", "branch_id": "2", "event": {"id": "o1", "sequence": 6, "type": "step", "name": "model-output-end", "data": {"turn_id": "t1", "request_id": "r1", "status": "cancelled", @@ -10127,7 +10127,7 @@ mod tests { 5, "i2", ["stop", "interrupt"], - json!({"reason": "budget: turns", "scope": "branch"}), + json!({"reason": "budget: turns", "scope": "turn"}), ), // Line 3's follow-up ended before the model for another reason, // and the request the cap stopped on that line is a later one. @@ -10176,7 +10176,7 @@ mod tests { 22, "i3", ["stop", "interrupt"], - json!({"reason": "budget: turns", "scope": "branch"}), + json!({"reason": "budget: turns", "scope": "turn"}), ), ] .iter() @@ -10246,7 +10246,7 @@ mod tests { 6, "i1", ["stop", "interrupt"], - json!({"reason": "budget: turns", "scope": "branch"}), + json!({"reason": "budget: turns", "scope": "turn"}), ), ] .iter() From b827fb194f570a91d000950ec5cc6020b2d409c8 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:25:15 +0800 Subject: [PATCH 13/25] test(scenario-eval): settle the compact scenario's lines after the first idle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The identity probe read whether the model opened a line, so a run whose model kept to itself reported the same absent verdict as a run that lost its identity after a compaction. The scenario now opens the line itself: a `calls` step creates it on `parser/` before the message, a 0.1s steer keeps `main` on `cache/`, and a new `afterIdle` step compacts every line that did not compact on its own with `session.context.compact` and then asks each line one request that re-runs its own tests. The probe reads a line's own identity block; `main` no longer has a roster to carry, so the phrase about it and the §12.3 row that named both are gone. A run whose `calls` step fails stopped before its message, so no request of it saw the configured text: it is recorded as `setup_failed`, still a failed run for the gate-1 rate, out of every probe rate, and listed in the report beside the runs that failed later. A compaction that does not complete in the step after the idle fails the run there, so a request is only judged as one after a compaction when a compaction happened. The line the `calls` step opened is known before its `branch/create` notice arrives, so a run that stops early does not go idle with that line still starting. --- docs/design/timeline-branches.md | 2 +- docs/zh/design/timeline-branches.md | 2 +- .../identity-after-compaction/scenario.json | 10 +- xtask/src/scenario_eval.rs | 390 ++++++++++++++++-- 4 files changed, 369 insertions(+), 35 deletions(-) diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index 65380fb9fc..f017fa5e0c 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -533,7 +533,7 @@ The opening and switching roles add eight scenarios: `long-work-and-a-flaky-test | Over-splitting | `timeline-branches/over-splitting` | Lines opened for short or sequential steps | | Never ending | `timeline-branches/never-ending` | A line that is done but does not call `end` | | Sibling relay | `timeline-branches/sibling-relay` | An opener is used to pass messages between lines that should have been one line | -| Identity after compaction | `timeline-branches-compact/identity-after-compaction` | After compaction on `main` and on a line, each still knows which line it is and which lines are its own | +| Identity after compaction | `timeline-branches-compact/identity-after-compaction` | After compaction on `main` and on a line, each still knows which line it is | | Continuing on a line after a switch | `—` | A line that became the default branch calls `end` on itself, hands its work to another line, keeps waking its opener with idle notices, or cannot open a line while the root could | | Opening lines after a switch | `timeline-branches/switch-then-open-lines` | The new default branch does both independent additions itself instead of opening a line for one of them, or the former default branch takes the new work | | The root opens while a line holds the role | `timeline-branches/root-opens-after-switch` | The user asks the root for a line after another line became the default branch: the root must open it, the new line must start from the root's history, and it must report to the root | diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index b23cdfa03f..48f351a066 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -499,7 +499,7 @@ WorkspaceTools 不变。 | 过度拆分 | `timeline-branches/over-splitting` | 为很短或必须按顺序做的步骤开线 | | 不结束 | `timeline-branches/never-ending` | 一条线已经做完,却不调用 `end` | | 兄弟中转 | `timeline-branches/sibling-relay` | 用 `main` 在本该合成一条线的几条线之间传话 | -| 压缩后的身份 | `timeline-branches-compact/identity-after-compaction` | `main` 和某条线各自压缩之后,仍知道自己是哪条线、哪些线是自己的 | +| 压缩后的身份 | `timeline-branches-compact/identity-after-compaction` | `main` 和某条线各自压缩之后,仍知道自己是哪条线 | | 切换后继续在线上工作 | — | 成为默认分支的线对自己调用 `end`、把工作交给另一条线、不断用 idle 通知唤醒开它的线,或者根能开线而这条线不能 | | 切换后开线 | `timeline-branches/switch-then-open-lines` | 新的默认分支自己做掉两处互不相干的新增,而不是为其中一处开一条线;或者原默认分支接过新工作 | | 线持有角色时根开线 | `timeline-branches/root-opens-after-switch` | 另一条线成为默认分支后,用户向根要一条线:根必须开这条线,新线必须从根的历史开始,并向根汇报 | diff --git a/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json b/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json index f3b75d586d..d06f230377 100644 --- a/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json +++ b/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json @@ -1,12 +1,18 @@ { "description": "The same two-subsystem task on a small window, so main and its line compact and must still know which line they are", "message": "Two independent subsystems need building in this project, and each has its own failing test suite:\n\n- parser/ — the integer expression parser specified in parser/expr.py\n- cache/ — the bounded LRU cache with TTL specified in cache/lru.py\n\nThey share no code and do not touch the same files. Make `python3 -m unittest discover -s tests` pass for both, and keep the implementations to their specs.", + "calls": [ + {"method": "session.branch_create", "params": {"parentBranchId": "main", "at": 0, "prompt": "Build the parser/ subsystem specified in parser/expr.py so `python3 -m unittest discover -s tests -p 'test_expr.py' -v` passes, keeping to its spec. Do not touch cache/ or tests/test_lru.py."}} + ], "steers": [ - {"afterSeconds": 0.1, "text": "Open one line for the parser/ subsystem and keep the cache/ work on main. Give the new line the parser/ files and the failing parser tests; both subsystems still have to pass."} + {"afterSeconds": 0.1, "text": "A user line is already building parser/ (parser/expr.py and tests/test_expr.py). Keep main strictly on cache/ (cache/lru.py and tests/test_lru.py): do not open another line and do not edit parser/ files."} ], + "afterIdle": { + "request": "Re-run the tests of the subsystem you are building and report whether they pass." + }, "budget": {"turns": 30, "seconds": 900, "window": 29000}, "probes": [ - {"id": "identity-after-compaction", "kind": "must_show", "text": "after a compaction, main's next request still carries its roster of open lines and a line's next request still carries its own identity block"}, + {"id": "identity-after-compaction", "kind": "must_show", "text": "after a compaction, a line's next request still carries its own identity block"}, {"id": "line-stays-a-line", "kind": "must_not_show", "text": "after a compaction a line acts as if it were main or forgets which line it is"} ] } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index c41dce2cd1..a5c331c738 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -171,7 +171,16 @@ //! after it is created and before the message. The runner resolves the //! Session id into `params.sessionId`; a branch defaults to `main` the //! way the methods treat it. A call that fails fails the run, and the -//! error names the method. +//! error names the method. Such a run stopped at `setup_failed`: it ran +//! before the message, so no request of it saw the configured text. It is +//! a failed run, enters no probe rate, and the report lists it apart from a +//! run that failed later. +//! - `afterIdle` is the step a scenario runs after its first idle: every one +//! of the scenario's lines — `main` and the line a `calls` step opened — +//! with no `completed` compaction of this run is compacted with +//! `session.context.compact`, then each line is asked `request`. A +//! compaction that does not complete fails the run there, so the requests +//! after it are only judged when a compaction happened. //! - `sources` declares the event producers a scenario runs with and the //! Session's subscription to them. One producer row is installed, only //! when `sources` is present, and it declares every source through the @@ -2065,6 +2074,9 @@ struct ScenarioFile { #[serde(default)] moves: Vec, budget: Budget, + /// The step after the run's first idle, when the scenario runs one. + #[serde(default)] + after_idle: Option, probes: Vec, } @@ -2365,6 +2377,18 @@ struct SwitchNotes { expected: Vec, } +/// The step a scenario runs after its first idle: every line that did not +/// compact on its own is compacted by the runner, and each line then answers +/// one request that sees the compacted context (Timeline branches §12.3). The +/// lines are the Session's `main` and the one the `calls` step opened, and +/// what a step does with them is fixed: a line without a completed compaction +/// of this run gets `session.context.compact`, then both lines get `request`. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct AfterIdle { + pub(crate) request: String, +} + /// One source a scenario declares through the `eventHub` service, and /// optionally subscribes its Session's `main` branch to (EventHub design A.1, /// A.3). Without `subscribe` the source starts unsubscribed, for a scenario @@ -2501,6 +2525,9 @@ pub(crate) struct Scenario { #[serde(default)] pub(crate) moves: Vec, pub(crate) budget: Budget, + /// The step after the run's first idle, when the scenario runs one. + #[serde(default)] + pub(crate) after_idle: Option, probes: Vec, } @@ -2722,6 +2749,7 @@ fn into_scenario( steers: raw.steers, switch: raw.switch, moves: raw.moves, + after_idle: raw.after_idle, budget: raw.budget, probes: raw.probes, }) @@ -2740,9 +2768,12 @@ struct RunRecord { /// emitted. texts: Vec, session: Option, - /// `idle`, `turns`, `seconds`, `switch_target_not_reached`, - /// `switch_target_ended`, `switch_target_unknown`, `switch_note_missing`, - /// `switch_incomplete` or `error`. + /// `idle`, `turns`, `seconds`, `setup_failed`, + /// `switch_target_not_reached`, `switch_target_ended`, + /// `switch_target_unknown`, `switch_note_missing`, `switch_incomplete` or + /// `error`. `setup_failed` is the `calls` step before the first submit: no + /// model request of that run saw the configured text (Timeline branches + /// §12.3). stop: &'static str, turns: u32, window: Option, @@ -5597,6 +5628,7 @@ fn child_record( "idle" => "idle", "turns" => "turns", "seconds" => "seconds", + "setup_failed" => "setup_failed", "switch_target_not_reached" => "switch_target_not_reached", "switch_target_ended" => "switch_target_ended", "switch_target_unknown" => "switch_target_unknown", @@ -6543,7 +6575,11 @@ async fn drive( } } Err(error) => { - driven.stop = "error"; + // The calls step runs before the message, so no model request + // of this run has seen the text being evaluated: the failure + // is a setup failure, not the model's answer (Timeline + // branches §12.3). + driven.stop = "setup_failed"; driven.error = Some(format!( "the calls step {} ({}) failed: {error}", index + 1, @@ -6581,7 +6617,20 @@ async fn drive( return driven; } let started = Instant::now(); - let mut branches: BTreeSet = ["main".to_owned()].into(); + // The lines the run knows before its message: `main` and the line the calls + // step opened, whose id is known before its `branch/create` notice arrives + // — waiting on that notice alone would let a run that stops early go idle + // with the line still starting. They are also the lines the step after the + // first idle settles (Timeline branches §12.3). + let after_lines: Vec = std::iter::once("main".to_owned()) + .chain(user_line.clone()) + .collect(); + let mut branches: BTreeSet = after_lines.iter().cloned().collect(); + // The lines whose `context/compaction` this run has seen complete, and the + // step after the first idle, which compacts the rest before it asks each + // line for a request. + let mut compacted: BTreeSet = BTreeSet::new(); + let mut after_idle = scenario.after_idle.clone(); let mut steers: Vec<(Steer, bool)> = scenario .steers .iter() @@ -6782,7 +6831,43 @@ async fn drive( } if !pending && !awaiting && last_event.elapsed() >= QUIET { match idle(client, &session, &branches, &mut calls).await { - Ok(true) => break, + Ok(true) => { + // The lines are idle: a scenario with a step after the + // first idle runs it here, and its requests keep the loop + // going until the second idle. + let Some(after) = after_idle.take() else { + break; + }; + let settled = tokio::time::timeout( + time_left(started, &scenario.budget), + settle_after_idle(client, &session, &after_lines, &after, &compacted), + ) + .await; + match settled { + Ok(Ok(())) => awaiting = true, + Ok(Err(error)) => { + driven.stop = "error"; + driven.error = Some(error); + return driven; + } + Err(_) => { + driven.stop = "seconds"; + driven.timed_out = true; + driven.cleanup_deadline = Some( + tokio::time::Instant::now() + + cleanup_budget( + settings.stall_cleanup, + settings.cleanup_budget_ms, + ), + ); + driven.error = Some(format!( + "the step after the first idle did not answer before the run's {}s budget ran out", + scenario.budget.seconds + )); + return driven; + } + } + } Ok(false) => last_event = Instant::now(), Err(error) => { driven.stop = "error"; @@ -6806,6 +6891,15 @@ async fn drive( { branches.insert(branch.to_owned()); } + // A line that compacted on its own is not compacted + // again after the idle: a second compaction of the same + // tail does not shrink the input (context policy §5). + if event["type"] == "context" + && event["name"] == "compaction" + && event["data"]["status"] == "completed" + { + compacted.insert(branch.clone()); + } if let Some(line) = tool_line(&event) { latest_tool_line = Some(line.to_owned()); } @@ -8238,6 +8332,54 @@ impl IdleCalls { } } +/// The step after the first idle: every line without a completed compaction of +/// this run is compacted, then each line is asked one request (Timeline +/// branches §12.3). A compaction that does not complete ends the run here +/// instead of letting the next request be judged as one after a compaction: +/// the probe reads identity across a compaction, and a run that did not compact +/// measures nothing else. +async fn settle_after_idle( + client: &mut impl SwitchClient, + session: &str, + lines: &[String], + after: &AfterIdle, + compacted: &BTreeSet, +) -> std::result::Result<(), String> { + for line in lines { + if compacted.contains(line) { + continue; + } + let reply = client + .rpc( + "session.context.compact", + json!({"sessionId": session, "branchId": line}), + ) + .await + .map_err(|error| format!("{line}: session.context.compact failed: {error}"))?; + match reply["status"].as_str() { + Some("completed") => {} + Some("skipped") => { + return Err(format!( + "{line}: the compaction after the first idle was skipped: {}", + reply["reason"].as_str().unwrap_or("no reason given") + )); + } + status => { + return Err(format!( + "{line}: the compaction after the first idle answered {}", + status.unwrap_or("no status") + )); + } + } + } + for line in lines { + submit(client, session, &after.request, None, Some(line)) + .await + .map_err(|error| format!("{line}: the request after the idle failed: {error}"))?; + } + Ok(()) +} + /// Whether every known line is idle and no notice arrived while it asked. /// `session.idle` returns when the line is idle; a short deadline keeps a busy /// line from holding the driver, and a call whose deadline passes stays @@ -9123,6 +9265,29 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] ); } } + // A run that failed before its first request is a setup failure, not the + // model's answer: the report names it apart from the run failures beside + // the rates it left, so a probe no run was judged on is not read as a lost + // identity (Timeline branches §12.3). + let failed_runs: Vec<&RunRecord> = records.iter().filter(|record| record.failed).collect(); + if !failed_runs.is_empty() { + text += "\n| arm | scenario | run | failure | error |\n| --- | --- | --- | --- | --- |\n"; + for record in failed_runs { + let failure = if record.stop == "setup_failed" { + "setup" + } else { + "run" + }; + let error = record.error.as_deref().unwrap_or_default(); + text += &format!( + "| {} | {} | {} | {failure} | {} |\n", + record.arm, + record.scenario, + record.run, + error.lines().next().unwrap_or_default(), + ); + } + } text.push('\n'); text.push_str(&rule::verdict_line( &judged, @@ -9229,6 +9394,7 @@ mod tests { steers: Vec::new(), switch: None, moves: Vec::new(), + after_idle: None, budget: Budget { turns: 4, seconds: 60., @@ -10489,6 +10655,41 @@ mod tests { Ok(json!({})) } } + /// Answers the step after the first idle's two calls and records them: its + /// compaction with the status the test set, and each request with an input + /// id. + struct AfterIdleRecorder { + calls: Vec<(String, Value)>, + compaction: &'static str, + } + impl Default for AfterIdleRecorder { + fn default() -> Self { + Self { + calls: Vec::new(), + compaction: "completed", + } + } + } + impl AfterIdleRecorder { + fn methods(&self) -> Vec<&str> { + self.calls + .iter() + .map(|(method, _)| method.as_str()) + .collect() + } + } + impl SwitchClient for AfterIdleRecorder { + async fn rpc(&mut self, method: &str, params: Value) -> dim_client::Result { + self.calls.push((method.to_owned(), params)); + Ok(match method { + "session.context.compact" => json!({ + "status": self.compaction, + "reason": "nothing_to_compact", + }), + _ => json!({"event": {"id": "input"}}), + }) + } + } /// The `branch:line` message a move writes on `line`: the role it gives /// the line and the participant it names (design §12.1). @@ -10904,33 +11105,76 @@ mod tests { ); } - /// Gate 2's fixed probe list is the committed scenarios' own: a rename in a - /// scenario cannot move the family without failing here. - #[test] - fn the_opening_gate_names_the_committed_opening_probes() { - let root = repository().join("xtask").join("scenario-eval"); - let branches = read_scenarios(&root.join("timeline-branches")).unwrap(); - for (scenario, probe_id) in OPENING_PROBES { - let committed = branches - .iter() - .find(|candidate| candidate.id == scenario) - .unwrap_or_else(|| panic!("{scenario} is in the committed set")); - assert!( - committed - .probes - .iter() - .any(|probe| probe.id == probe_id && probe.kind == ProbeKind::MustShow), - "{scenario} pre-registers {probe_id} as a must_show probe" + /// The step after the first idle compacts only the lines that did not + /// compact on their own, then asks every line of the scenario one + /// request (Timeline branches §12.3). + #[tokio::test] + async fn the_step_after_the_idle_compacts_the_rest_and_asks_every_line() { + let mut client = AfterIdleRecorder::default(); + let lines = vec!["main".to_owned(), "line".to_owned()]; + let compacted: BTreeSet = ["main".to_owned()].into(); + let after = AfterIdle { + request: "re-run the tests".into(), + }; + settle_after_idle(&mut client, "session", &lines, &after, &compacted) + .await + .unwrap(); + assert_eq!( + client.methods(), + [ + "session.context.compact", + "session.submit", + "session.submit" + ], + "the line that compacted is not compacted again, and both are asked" + ); + assert_eq!(client.calls[0].1["branchId"], "line"); + assert_eq!(client.calls[1].1["branchId"], "main"); + assert_eq!(client.calls[1].1["text"], "re-run the tests"); + assert_eq!(client.calls[2].1["branchId"], "line"); + } + + /// A compaction that does not complete fails the run there: the requests + /// after it would be judged as ones after a compaction (Timeline branches + /// §12.3). + #[tokio::test] + async fn a_compaction_the_idle_step_could_not_complete_fails_the_run() { + let after = AfterIdle { + request: "re-run the tests".into(), + }; + for (status, reason) in [ + ("skipped", "nothing_to_compact"), + ("failed", "no error given"), + ] { + let mut client = AfterIdleRecorder { + compaction: status, + ..AfterIdleRecorder::default() + }; + let error = settle_after_idle( + &mut client, + "session", + &["main".to_owned()], + &after, + &BTreeSet::new(), + ) + .await + .expect_err("a line that did not compact cannot be judged on it"); + assert!(error.contains(status) || error.contains(reason), "{error}"); + assert_eq!( + client.methods(), + ["session.context.compact"], + "no request follows a compaction that did not complete" ); } } /// The opening scenarios pre-register the probe that their runs open one - /// line for one job, and the compact scenario asks the user for the parser - /// line (Timeline branches §12.3). No model runs, so CI catches a drift in - /// the committed probes or steer before a manual run. + /// line for one job, and the compact scenario opens its parser line before + /// the message, keeps `main` off it, and settles both lines after the + /// first idle (Timeline branches §12.3). No model runs, so CI catches a + /// drift in the committed probes, calls or step before a manual run. #[test] - fn the_opening_scenarios_pre_register_their_probe_and_the_compact_scenario_asks_for_one_line() { + fn the_opening_scenarios_pre_register_their_probe_and_the_compact_scenario_opens_its_line() { let root = repository().join("xtask").join("scenario-eval"); let branches = read_scenarios(&root.join("timeline-branches")).unwrap(); let compact = read_scenarios(&root.join("timeline-branches-compact")).unwrap(); @@ -10949,18 +11193,52 @@ mod tests { ); } let identity = find(&compact, "identity-after-compaction"); + assert_eq!( + identity.calls.len(), + 1, + "identity-after-compaction opens its line before the message" + ); + assert_eq!(identity.calls[0].method, "session.branch_create"); + assert_eq!(identity.calls[0].params["parentBranchId"], "main"); + assert_eq!(identity.calls[0].params["at"], 0); + assert!( + identity.calls[0].params["prompt"] + .as_str() + .is_some_and(|prompt| prompt.contains("parser/")), + "the line is given the parser/ subsystem: {:?}", + identity.calls[0].params["prompt"] + ); assert_eq!( identity.steers.len(), 1, - "identity-after-compaction asks the user for one line" + "identity-after-compaction keeps main off the line's subsystem" ); assert!( identity.steers[0] .text - .contains("Open one line for the parser/"), - "the steer names the parser line: {}", + .contains("Keep main strictly on cache/"), + "the steer keeps main on cache/: {}", identity.steers[0].text ); + let after = identity + .after_idle + .as_ref() + .expect("identity-after-compaction settles both lines after the first idle"); + assert!( + after.request.contains("Re-run the tests") && !after.request.contains("which line"), + "the request re-runs a line's own tests and names no line: {}", + after.request + ); + let probe = identity + .probes + .iter() + .find(|probe| probe.id == "identity-after-compaction") + .expect("the identity probe"); + assert_eq!( + probe.text, + "after a compaction, a line's next request still carries its own identity block", + "the probe reads a line's own identity, not main's roster" + ); } /// The scheduler set parses through the runner's own reader (Scheduler @@ -12072,6 +12350,56 @@ mod tests { ); } + /// A run whose calls step failed never sent the configured text to a model: + /// the report lists it as a setup failure, apart from a run that failed on + /// its own, and neither enters the probe's rate (Timeline branches §12.3). + #[test] + fn the_report_lists_a_setup_failure_apart_from_a_run_failure() { + let scenario = scenario(vec![probe("reports", ProbeKind::MustShow)]); + let mut setup = record( + "candidate", + &scenario, + &[("reports", ProbeVerdict::Unparsed)], + JudgeOutcome::NotAsked, + ); + setup.stop = "setup_failed"; + setup.error = + Some("the calls step 1 (session.branch_create) failed: branch_not_found".into()); + setup.failed = true; + let mut run = record( + "current", + &scenario, + &[("reports", ProbeVerdict::Present)], + JudgeOutcome::Judged, + ); + run.stop = "seconds"; + run.error = Some("the run stopped on its wall clock".into()); + run.failed = true; + let records = [setup, run]; + let text = report( + &instrument(model()), + std::slice::from_ref(&scenario), + &records, + ); + assert!( + text.contains( + "| candidate | case | 0 | setup | the calls step 1 (session.branch_create) failed" + ), + "a setup failure is named as one: {text}" + ); + assert!( + text.contains("| current | case | 0 | run | the run stopped on its wall clock |"), + "a run failure is named as one: {text}" + ); + let metrics = metrics(&scenario, &records); + assert_eq!(metrics.failed, 2, "both are failed runs for gate 1"); + assert_eq!( + metrics.counts(&("case".to_owned(), "reports".to_owned())), + ProbeCounts::default(), + "neither enters the probe's rate" + ); + } + /// The same holds when the judge answered unreadably: twenty unjudged /// runs compare zero probes with zero probes, and the verdict is /// inconclusive (model-prompts §8.1). From 8107ca08e466ab4006afdbf4732b81b84b584991 Mon Sep 17 00:00:00 2001 From: huihui Date: Tue, 24 Nov 2026 23:25:19 +0800 Subject: [PATCH 14/25] test(capabilities): pin a line's identity across a manual compaction The compact scenario now settles its lines with `session.context.compact`, so the identity probe reads a request that follows a manual compaction rather than an automatic one. A flow test compacts a line by hand and checks that the compaction completed, that its baseline carries the line's identity block, and that the request after it carries that block once: the opening input that first carried the identity is behind the cut, so the identity the request shows comes from the compaction's baseline. The compaction model keeps the last turn inside the retention bound at a 29,000-token window, and the line adopts a model, which the manual step reads from the branch rather than from the request. --- .../tests/branch_flow.rs | 177 ++++++++++++++++++ 1 file changed, 177 insertions(+) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 5b9a693a55..f731302681 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -5688,6 +5688,7 @@ async fn a_parent_read_carries_the_effects_its_tool_results_declared() { "branch".into(), "touch".into(), ]), + system_prompt: "You are a test.".into(), ..SessionConfig::default() })) .await @@ -8367,6 +8368,182 @@ async fn a_roster_and_an_identity_replay_separately_after_a_compaction() { soon(agent.close()).await.unwrap(); } +/// [`Compact`] with a 29,000-token window, so a manual step has a cut that +/// keeps the last turn inside the retention bound. +#[derive(Clone, Copy)] +struct Roomy; +impl ResolveContextModel for Roomy { + fn resolve( + &self, + _: Arc, + _: CancellationToken, + ) -> HostFuture<'_, Arc> { + Box::pin(async { Ok(Arc::new(Roomy) as Arc) }) + } +} +impl ContextModel for Roomy { + fn context_window(&self) -> f64 { + 29_000. + } + fn output_tokens(&self) -> f64 { + 64. + } + fn threshold_tokens(&self) -> f64 { + 20_000. + } + fn count_tokens(&self, request: &ModelRequest) -> f64 { + Compact.count_tokens(request) + } +} +impl CompactionStrategy for Roomy { + fn name(&self) -> &str { + Compact.name() + } + fn replacement_size(&self, model: &dyn ContextModel) -> f64 { + Compact.replacement_size(model) + } + fn compact( + &self, + input: CompactionInput, + cancel: CancellationToken, + ) -> HostFuture<'_, StrategyOutcome> { + Compact.compact(input, cancel) + } +} + +/// A manual compaction, the one `session.context.compact` asks the loop for, +/// replays a line's identity the way an automatic one does: the request after +/// it still carries which line it is (Timeline branches §12.3). The identity +/// probe of the compact scenario now reads a manual compaction, so this is the +/// property that probe depends on. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_manual_compaction_replays_a_lines_identity() { + let mut builder = AgentBuilder::new(AgentConfig::default()); + builder + .timeline_store(dim_agent_runtime::TimelineStoreBinding::new(Arc::new( + MemoryTimelineStore::default(), + ))) + .session_value(Arc::new(HistoryRenderer::default())) + .process_value(Arc::new(ModelHost(Arc::new(FlowModel)))) + .session_value(Arc::new(ToolHost(Arc::new(MockTools)))) + .session_value(Arc::new(PrepareContextHost(Arc::new(IdentityContext)))) + .session_value(Arc::new(ContextModelHost(Some(Arc::new(Roomy))))) + .session_value(Arc::new(CompactionStrategyHost(Some(Arc::new(Roomy))))) + .require_feature( + Feature::new("PrepareModelHost").session("PrepareModelHost", |names| { + Ok(Box::new(DefaultPrepareModelPlugin::new(names)?)) + }), + ); + defaults::install(&mut builder); + let agent = MinimalHost::start(&builder).await.unwrap(); + // The Session's own model: a manual compaction at idle has no request to + // adopt one from. + let session = soon(agent.create_session(SessionConfig { + model: ModelSelection { + provider_id: "test".into(), + model_id: "flow".into(), + capability_snapshot: None, + config: None, + metadata: None, + }, + ..SessionConfig::default() + })) + .await + .unwrap(); + let line = open_line(&session, "compact my line").await; + for text in ["x".repeat(1500), "y".repeat(1500)] { + session.submit(text, InputMode::Queue, &line).await.unwrap(); + patient(session.idle(&line)).await.unwrap(); + } + // The manual step reads the configuration the branch adopted; a flow test + // adopts none until it configures one. + session + .configure( + ConfigureUpdate { + model: Some(ModelSelection { + provider_id: "test".into(), + model_id: "flow".into(), + capability_snapshot: None, + config: None, + metadata: None, + }), + ..Default::default() + }, + &line, + ) + .await + .unwrap(); + let command = session + .service::(&line) + .expect("the line's loop") + .compact() + .unwrap(); + // A compaction is not a turn: `session.idle` returns before its step has + // written its result. + patient(async { + loop { + let events = chain_events(&session, &line, ..).await.unwrap(); + if events.iter().any(|event| { + matches!(&event.kind, EventKind::ContextCompaction(data) + if data.command == Some(command)) + }) { + return; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await; + session + .submit("after the compaction".into(), InputMode::Queue, &line) + .await + .unwrap(); + patient(session.idle(&line)).await.unwrap(); + let events = chain_events(&session, &line, ..).await.unwrap(); + let (at, outcome) = events + .iter() + .find_map(|event| match &event.kind { + EventKind::ContextCompaction(data) if data.command == Some(command) => { + Some((event.sequence, &data.outcome)) + } + _ => None, + }) + .expect("the manual compaction wrote its result"); + assert!( + matches!(outcome, ContextCompactionResult::Completed { .. }), + "the manual compaction completed on the line: {outcome:?}" + ); + let message = baseline_message(&events, "branch:line") + .expect("the manual compaction replayed the line's identity"); + let MessageContent::Text(text) = &message.content else { + panic!("the identity is text: {message:?}"); + }; + assert!( + text.starts_with(&format!( + " at) + .find_map(|event| match &event.kind { + EventKind::ModelCall(data) => Some(&data.request), + _ => None, + }) + .expect("the request after the compaction"); + // One identity message and no second copy from the history: the opening + // input that carried it is behind the cut. + let identities = request + .messages + .iter() + .filter(|message| said(message).starts_with(" Date: Wed, 25 Nov 2026 00:50:31 +0800 Subject: [PATCH 15/25] fix(scenario-eval): start the compact scenario's line where the session did A `session.branch_create` call in a scenario could only name a numeric sequence, so the compact scenario cut its line at 0. A line cut before `main`'s `context/configured` carries no configuration of its own, and `session.context.compact` on it fails with "Context is not configured; adopt a model first"; the fixture's smoke runs failed there before any compaction. A call may now write `"at": "session_open"`, and only a `session.branch_create` whose `parentBranchId` is `main` may do so. The runner sends it with the sequence `session.create` returned, so the line starts where the Session did without the scenario naming a number; a Session reply that carries no sequence fails the run in its calls step, before the message. A numeric `at` keeps its meaning, and a call that omits it is sent as written. The fake daemon in the runner's tests still answers `session.create` with no sequence, so the reply's sequence is optional until a `session_open` call needs it. A parser test covers the placeholder's validation, and two driver tests cover the fill and the missing-sequence setup failure. --- .../identity-after-compaction/scenario.json | 2 +- xtask/src/scenario_eval.rs | 197 +++++++++++++++++- 2 files changed, 192 insertions(+), 7 deletions(-) diff --git a/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json b/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json index d06f230377..a4175ee97e 100644 --- a/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json +++ b/xtask/scenario-eval/timeline-branches-compact/identity-after-compaction/scenario.json @@ -2,7 +2,7 @@ "description": "The same two-subsystem task on a small window, so main and its line compact and must still know which line they are", "message": "Two independent subsystems need building in this project, and each has its own failing test suite:\n\n- parser/ — the integer expression parser specified in parser/expr.py\n- cache/ — the bounded LRU cache with TTL specified in cache/lru.py\n\nThey share no code and do not touch the same files. Make `python3 -m unittest discover -s tests` pass for both, and keep the implementations to their specs.", "calls": [ - {"method": "session.branch_create", "params": {"parentBranchId": "main", "at": 0, "prompt": "Build the parser/ subsystem specified in parser/expr.py so `python3 -m unittest discover -s tests -p 'test_expr.py' -v` passes, keeping to its spec. Do not touch cache/ or tests/test_lru.py."}} + {"method": "session.branch_create", "params": {"parentBranchId": "main", "at": "session_open", "prompt": "Build the parser/ subsystem specified in parser/expr.py so `python3 -m unittest discover -s tests -p 'test_expr.py' -v` passes, keeping to its spec. Do not touch cache/ or tests/test_lru.py."}} ], "steers": [ {"afterSeconds": 0.1, "text": "A user line is already building parser/ (parser/expr.py and tests/test_expr.py). Keep main strictly on cache/ (cache/lru.py and tests/test_lru.py): do not open another line and do not edit parser/ files."} diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index a5c331c738..59de8efccb 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -2128,6 +2128,10 @@ pub(crate) enum SwitchRole { /// turn before the line is marked ready. const UNKNOWN_BRANCH_RETRIES: u32 = 3; +/// The `at` a `session.branch_create` call writes to start where the Session +/// did: `drive` replaces it with the sequence `session.create` returned. +const SESSION_OPEN: &str = "session_open"; + /// The tool line a `branch/create` notice opened: the branch tool's line, which /// [`SwitchRole::LatestToolLine`] names. Any other notice answers `None`. fn tool_line(event: &Value) -> Option<&str> { @@ -2456,6 +2460,10 @@ pub(crate) struct EventSpec { #[serde(skip)] pub(crate) declared_mode: InputMode, } +/// One call the runner makes before the message. A `session.branch_create` +/// whose `parentBranchId` is `main` may set `at` to `"session_open"` instead +/// of a sequence: the runner replaces it with the sequence `session.create` +/// returned, so the line starts where the Session did. #[derive(Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct Call { @@ -2637,6 +2645,19 @@ fn into_scenario( if !call.params.is_object() && !call.params.is_null() { return Err(format!("call {}: params must be an object", call.method)); } + if call.params.get("at").and_then(Value::as_str) == Some(SESSION_OPEN) { + if call.method != "session.branch_create" { + return Err(format!( + "call {}: {SESSION_OPEN} is only for session.branch_create", + call.method + )); + } + if call.params.get("parentBranchId").and_then(Value::as_str) != Some("main") { + return Err(format!( + "session.branch_create: {SESSION_OPEN} needs parentBranchId main" + )); + } + } } if raw.sources.is_empty() && !raw.events.is_empty() { return Err("an event needs the source it comes from declared in sources".into()); @@ -6493,8 +6514,11 @@ async fn drive( create["tools"] = json!(tools); } let created = client.rpc("session.create", create).await; - let session = match created { - Ok(reply) => reply["sessionId"].as_str().unwrap_or_default().to_owned(), + let (session, created_sequence) = match created { + Ok(reply) => ( + reply["sessionId"].as_str().unwrap_or_default().to_owned(), + reply["sequence"].as_u64(), + ), Err(error) => { return Driven { session: String::new(), @@ -6568,6 +6592,18 @@ async fn drive( _ => serde_json::Map::new(), }; params.insert("sessionId".to_owned(), json!(session)); + if params.get("at").and_then(Value::as_str) == Some(SESSION_OPEN) { + let Some(sequence) = created_sequence else { + driven.stop = "setup_failed"; + driven.error = Some(format!( + "the calls step {} ({}) starts where the Session did, but session.create returned no sequence", + index + 1, + call.method + )); + return driven; + }; + params.insert("at".to_owned(), json!(sequence)); + } match client.rpc(&call.method, Value::Object(params)).await { Ok(reply) => { if call.method == "session.branch_create" { @@ -9784,6 +9820,52 @@ mod tests { let _ = std::fs::remove_dir_all(directory); } + /// `session_open` is filled from `session.create`, so only a + /// `session.branch_create` on `main` may write it: any other call or + /// parent would name a line the Session never opened. A numeric `at` is + /// still a call's own sequence, whatever its parent. + #[test] + fn the_session_open_placeholder_needs_a_main_branch_create() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-session-open-parse-{}", + std::process::id() + )); + std::fs::create_dir_all(directory.join("workspace")).unwrap(); + let parse = |calls: Value| { + let file: ScenarioFile = serde_json::from_value(json!({ + "message": "first", + "calls": calls, + "budget": {"turns": 3, "seconds": 60, "window": 1000}, + "probes": [{"id": "ran", "kind": "must_show", "text": "it ran"}] + })) + .unwrap(); + into_scenario("case".into(), directory.clone(), file) + }; + let create = |at: Value, parent: &str| { + json!([{"method": "session.branch_create", + "params": {"parentBranchId": parent, "at": at, + "prompt": "the user's line"}}]) + }; + let scenario = parse(create(json!(SESSION_OPEN), "main")).unwrap(); + assert_eq!(scenario.calls[0].params["at"], SESSION_OPEN); + let Err(error) = parse(create(json!(SESSION_OPEN), "3")) else { + panic!("a line cut from another line cannot start where the Session did"); + }; + assert!( + error.contains(SESSION_OPEN) && error.contains("main"), + "{error}" + ); + let Err(error) = parse(json!([{"method": "session.context.usage", + "params": {"at": SESSION_OPEN}}])) + else { + panic!("the placeholder is only a branch_create's at"); + }; + assert!(error.contains("session.branch_create"), "{error}"); + let scenario = parse(create(json!(0), "3")).unwrap(); + assert_eq!(scenario.calls[0].params["at"], 0); + let _ = std::fs::remove_dir_all(directory); + } + /// A second move fires right after the first, and a move that names a /// former-default input sends it to the line it moved away from: the note /// a move writes goes in as `append` input, which never starts a turn, so @@ -11200,7 +11282,7 @@ mod tests { ); assert_eq!(identity.calls[0].method, "session.branch_create"); assert_eq!(identity.calls[0].params["parentBranchId"], "main"); - assert_eq!(identity.calls[0].params["at"], 0); + assert_eq!(identity.calls[0].params["at"], "session_open"); assert!( identity.calls[0].params["prompt"] .as_str() @@ -15655,6 +15737,10 @@ mod tests { /// so the check is deferred, and the deferred read answers /// `session_reloading`: a failure that is not the deferral itself. DeferredUsageFails, + /// The Session is created at its opening sequence, which + /// `session.create` reports, and the submitted turn starts and ends + /// at once: a scenario's `session_open` call has a sequence to use. + OpensAtTheSessionStart, } /// What a scripted peer read: the `requestId` of every decline, in order, @@ -15670,6 +15756,8 @@ mod tests { usages: AtomicUsize, /// The `branchId` of every `session.branch_set_default`, in order. moves: Mutex>, + /// The parameters of every `session.branch_create`, in order. + opens: Mutex>, attached: tokio::sync::Notify, closes: AtomicUsize, } @@ -15800,7 +15888,7 @@ mod tests { // The line is busy until the peer writes the call's result, the // way a running turn is: `session.idle` stays unanswered and the // driver's own deadline reports the line busy. - let mut settled = false; + let mut settled = matches!(script, PeerScript::OpensAtTheSessionStart); // [`PeerScript::HeldIdle`]'s hold: the calls it kept, and the // deadline it answers them at. The deadline stands after the // release, so a later call starts no second hold. @@ -15835,6 +15923,13 @@ mod tests { .to_owned(), ); } + if method == "session.branch_create" { + recorded + .opens + .lock() + .unwrap() + .push(request["params"].clone()); + } if method == "session.attach" { recorded.attached.notify_one(); } @@ -15960,6 +16055,7 @@ mod tests { PeerScript::ChainedToolLineBeforeActivation | PeerScript::ChainedToolLineAfterActivation => None, PeerScript::DeferredUsageFails => None, + PeerScript::OpensAtTheSessionStart => None, }; if let Some((request, sequence)) = closed { if recorded.settled_at.load(Ordering::SeqCst) == 0 { @@ -15996,7 +16092,11 @@ mod tests { "features": ["session.create", "session.history"], "daemonProfile": {"kind": "mock"}, }}), - "session.create" => json!({"result": {"sessionId": "peer"}}), + "session.create" => match &script { + PeerScript::OpensAtTheSessionStart => json!({"result": { + "sessionId": "peer", "sequence": 12}}), + _ => json!({"result": {"sessionId": "peer"}}), + }, "session.context.usage" => { let read = recorded.usages.fetch_add(1, Ordering::SeqCst) + 1; match (matches!(script, PeerScript::DeferredUsageFails), read) { @@ -16111,10 +16211,13 @@ mod tests { PeerScript::HeldIdle | PeerScript::SwitchNeverFires | PeerScript::DeferredUsageFails + | PeerScript::OpensAtTheSessionStart ) { if matches!( script, - PeerScript::SwitchNeverFires | PeerScript::DeferredUsageFails + PeerScript::SwitchNeverFires + | PeerScript::DeferredUsageFails + | PeerScript::OpensAtTheSessionStart ) { write .write_all(¬ice(json!({"type": "turn", "name": "end", @@ -16236,6 +16339,88 @@ mod tests { ); } + /// A `session.branch_create` whose `at` is `session_open` is sent with the + /// sequence `session.create` reported, so the line starts where the + /// Session did without the scenario naming a number. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_session_open_call_starts_the_line_where_the_session_did() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-session-open-drive-{}", + std::process::id() + )); + let (socket, reads) = + scripted_peer(&directory, 8_000, PeerScript::OpensAtTheSessionStart).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.seconds = 10.; + scenario.calls = vec![Call { + method: "session.branch_create".into(), + params: json!({"parentBranchId": "main", "at": SESSION_OPEN, + "prompt": "the line's job"}), + }]; + let driven = drive( + &mut client, + &RunSettings::default(), + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let opened = reads.opens.lock().unwrap().clone(); + let _ = std::fs::remove_dir_all(directory); + assert_eq!(driven.stop, "idle", "{:?}", driven.error); + assert_eq!(opened.len(), 1, "one line is opened before the message"); + assert_eq!( + opened[0]["at"], 12, + "the reply's sequence fills the placeholder: {}", + opened[0] + ); + assert_eq!(opened[0]["parentBranchId"], "main"); + assert_eq!(opened[0]["sessionId"], "peer"); + } + + /// A `session_open` call needs the sequence `session.create` reports: a + /// reply without one fails the run in its calls step, before the message, + /// and the call is never sent. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_session_open_call_without_a_session_sequence_is_a_setup_failure() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-session-open-missing-{}", + std::process::id() + )); + let (socket, reads) = scripted_peer(&directory, 8_000, PeerScript::SwitchNeverFires).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.seconds = 10.; + scenario.calls = vec![Call { + method: "session.branch_create".into(), + params: json!({"parentBranchId": "main", "at": SESSION_OPEN, + "prompt": "the line's job"}), + }]; + let driven = drive( + &mut client, + &RunSettings::default(), + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let opened = reads.opens.lock().unwrap().clone(); + let _ = std::fs::remove_dir_all(directory); + assert_eq!(driven.stop, "setup_failed", "{:?}", driven.error); + assert!(opened.is_empty(), "the call is not sent without a sequence"); + assert!( + driven.error.unwrap_or_default().contains("no sequence"), + "the error names the missing sequence" + ); + } + /// A switch whose target never appears is its own outcome and a failed /// run: the run ends on its turn budget with the switch pending, and the /// runner records `switch_target_not_reached` rather than dropping it From e7e9d98921fdd0d77e3fedc50987a0223e8f9843 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 01:35:03 +0800 Subject: [PATCH 16/25] test(capabilities): keep the parent read test's session as main has it a_parent_read_carries_the_effects_its_tool_results_declared asserts what a branch page carries from its parent's tool results; it needs no system prompt. The line was a stray edit beside the manual-compaction test and is removed, leaving the test as it is on main. --- crates/dim-agent-capabilities/tests/branch_flow.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index f731302681..f0b73734ac 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -5688,7 +5688,6 @@ async fn a_parent_read_carries_the_effects_its_tool_results_declared() { "branch".into(), "touch".into(), ]), - system_prompt: "You are a test.".into(), ..SessionConfig::default() })) .await From 0390f0d53e515398e81de861c43872f447d02cf7 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 01:35:06 +0800 Subject: [PATCH 17/25] fix(scenario-eval): read a saved setup failure back by its stop `--rejudge` and `--pool` read a runner-written `runs.jsonl` through `stop_name`, which did not know the `setup_failed` stop the runner writes when a calls step fails, so the whole read was refused with "the saved run has an unknown stop setup_failed". The stop maps to itself, and a test writes such a record and reads it back through the pool's reader. --- xtask/src/scenario_eval.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 59de8efccb..2b45c00f82 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -1440,6 +1440,7 @@ fn stop_name(stop: &str) -> Result<&'static str> { "idle" => Ok("idle"), "turns" => Ok("turns"), "seconds" => Ok("seconds"), + "setup_failed" => Ok("setup_failed"), "switch_target_not_reached" => Ok("switch_target_not_reached"), "switch_target_ended" => Ok("switch_target_ended"), "switch_target_unknown" => Ok("switch_target_unknown"), @@ -13776,6 +13777,41 @@ mod tests { ); } + /// A run that the runner itself recorded with the `setup_failed` stop is + /// read back by the read a pool or a re-judge takes: `stop_name` keeps the + /// stop, so a read that meets a calls-step failure reports the run again + /// instead of refusing the whole set. + #[test] + fn a_saved_setup_failure_reads_back_by_its_own_stop() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-setup-failed-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&directory); + std::fs::create_dir_all(&directory).unwrap(); + let saved = json!({ + "arm": "current", "scenario": "identity-after-compaction", "run": 0, + "session": null, "stop": "setup_failed", "turns": 0, "window": null, + "durationMs": 1.0, "failed": true, "judgeOutcome": "not_asked", + "error": "the calls step 1 (session.branch_create) failed", + "judgeError": null, "judgeReasks": 0, "probes": [] + }); + std::fs::write(directory.join("runs.jsonl"), format!("{saved}\n")).unwrap(); + let scenarios = read_scenarios( + &repository() + .join("xtask") + .join("scenario-eval") + .join("timeline-branches-compact"), + ) + .unwrap(); + let records = read_pooled_runs(&directory, &scenarios) + .expect("a saved setup failure is one of the stops the runner writes"); + assert_eq!(records.len(), 1); + assert_eq!(records[0].stop, "setup_failed"); + assert!(records[0].failed); + let _ = std::fs::remove_dir_all(&directory); + } + /// A pool reports several finished evaluations under one rule: both /// sources' runs are added, their probes counted together, and no source /// is written to. From 0d115c2de7f2f27ae3ce49014f006da3e27d5aa0 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 02:53:57 +0800 Subject: [PATCH 18/25] fix(scenario-eval): score a probe only after its fixture request ran A run the harness stopped before the request a probe reads existed is an incomplete fixture, not a loss of identity. The runner records the scenario's message and every request the step after the first idle submits, with the input id the Session answered, and the export must show each input consumed and followed by a model call on its line. A run the turn budget stopped before that step, or between a submission and the request on its line, carries `incomplete`: it is not failed, is not judged, enters no probe rate, does not count toward the floor, and the report lists it apart from failed and unjudged runs. A run that fails at the compaction or the review request still fails. The same rule covers a switch follow-up whose request the turn cap stopped: the note check reports that shape as the cap's, not as a missing note, and the run is incomplete instead of scored. A request that never reached the model for another reason still fails as `switch_note_missing`. Tests: `a_run_that_reaches_the_turn_budget_before_the_after_idle_step_is_incomplete` fails on the previous revision with the run judged and the probe counted; `a_turn_budget_after_the_after_idle_submit_leaves_the_request_unobserved`, `a_fixture_its_budget_stopped_before_its_requests_is_incomplete`, `a_turn_budget_stop_makes_a_note_its_stop_ended_incomplete` and `a_cap_cut_switch_follow_up_makes_the_run_incomplete` cover the two shapes and the switch follow-up. --- docs/design/model-prompts.md | 2 +- docs/zh/design/model-prompts.md | 2 +- xtask/src/scenario_eval.rs | 692 +++++++++++++++++++++++++++++--- 3 files changed, 628 insertions(+), 68 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index ae7602d5c7..8294ee1ab8 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -163,7 +163,7 @@ A probe's rate counts judged, non-failed runs only, and failed runs are compared The last row is the rule's limit at the floor: catching that loss 80% of the time needs about 44–51 runs per scenario per arm. The report therefore prints both arms' counts, both rates, the loss, the p-value and the Holm threshold for every comparison, so a reader sees a loss the rule did not flag as well as one it did. The measured table resamples whole runs, which keeps each run's probes together. The pooled rows do not: they count each probe of each run as an observation, and the probes of one run share a transcript, so those p-values are optimistic. That errs toward rejecting, which means failing a candidate, and the per-probe rows compare one probe over whole runs. -**Failed and unjudged runs.** A failed run is one that ended on an error or its wall-clock budget, or one whose judging did not happen: there was nothing the judge could be asked, or a judge call failed — a window overflow, a transport or an HTTP error, or a reply cut off at its output cap. An unjudged run is one the judge answered but gave no usable verdicts for after two re-asks, or one whose view does not fit the judge's budget, which is never asked: it enters none of its arm's probe rates, and the report counts it and lists it with its reason; the unjudged-run rate compares it. A failed run is out of the probe rates too, and is compared once, as the failed-run rate. A re-asked verdict comes from a longer conversation with the same judge at the same settings, and both arms are re-asked by the same rule. A run is judged through a view of its export: each request is given against the previous request of its line — the messages added since that request, or the whole message list after a history change — and every other field of the request appears in full only when it changed, or as an unchanged marker when it did not, so nothing is dropped. A request's consecutive `step/thinking` deltas are one line carrying their text in order, because a delta line is mostly an event id and field names and the judge reads the run as a whole. The judge reads the view in one call. A view that does not fit the judge's declared window — the window less the reply's `maxTokens` — is not split into parts: a probe that counts, orders or holds over a whole run cannot be answered from one part, so the run is unjudged before any call, and the report gives the estimate and the budget. The estimate is the runner's own and is taken before any call, so a predicted overflow is never asked. A call the provider refuses for a window overflow therefore means the declared window or the estimate was wrong, and it stays a failed run: a refusal is how a run outgrowing its model's real window shows up, and failed runs are compared between the arms. The scenario judge is asked for `present` or `absent`; the verdict parser the scenario and summary evaluations share also accepts `contradicted`, which a `must_not_show` probe treats as not shown. An evaluation whose judge declares no window fails before its first call. +**Failed and unjudged runs.** A failed run is one that ended on an error or its wall-clock budget, or one whose judging did not happen: there was nothing the judge could be asked, or a judge call failed — a window overflow, a transport or an HTTP error, or a reply cut off at its output cap. An unjudged run is one the judge answered but gave no usable verdicts for after two re-asks, or one whose view does not fit the judge's budget, which is never asked: it enters none of its arm's probe rates, and the report counts it and lists it with its reason; the unjudged-run rate compares it. A failed run is out of the probe rates too, and is compared once, as the failed-run rate. An incomplete run is one the harness stopped before a request its probes read existed — the step after the first idle never ran, or an input the runner submitted never reached the model. It is neither a failed nor a judged run: it enters none of its arm's probe rates, does not count toward the floor, and the report lists it with its reason apart from the failed and unjudged runs, so a probe no request could answer is not read as the candidate's loss. A re-asked verdict comes from a longer conversation with the same judge at the same settings, and both arms are re-asked by the same rule. A run is judged through a view of its export: each request is given against the previous request of its line — the messages added since that request, or the whole message list after a history change — and every other field of the request appears in full only when it changed, or as an unchanged marker when it did not, so nothing is dropped. A request's consecutive `step/thinking` deltas are one line carrying their text in order, because a delta line is mostly an event id and field names and the judge reads the run as a whole. The judge reads the view in one call. A view that does not fit the judge's declared window — the window less the reply's `maxTokens` — is not split into parts: a probe that counts, orders or holds over a whole run cannot be answered from one part, so the run is unjudged before any call, and the report gives the estimate and the budget. The estimate is the runner's own and is taken before any call, so a predicted overflow is never asked. A call the provider refuses for a window overflow therefore means the declared window or the estimate was wrong, and it stays a failed run: a refusal is how a run outgrowing its model's real window shows up, and failed runs are compared between the arms. The scenario judge is asked for `present` or `absent`; the verdict parser the scenario and summary evaluations share also accepts `contradicted`, which a `must_not_show` probe treats as not shown. An evaluation whose judge declares no window fails before its first call. **The candidate runs through the shipped assembly.** It is put in place at its author's factory configuration, as the summary strategy's optional system prompt member specified in [ContextCompaction §13.4](plugins/ContextCompaction.md#134-evaluation) allows a candidate prompt to replace the fixed one — the product profile never sets it — and never by patching strings in an evaluation-only path, so both arms run the shipped request building, chunking and failure handling. diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index 0ff0ee3352..efdcbc1469 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -163,7 +163,7 @@ 最后一行就是规则在下限处的极限:要以 80% 的概率发现它,每场景每臂需要约 44–51 次运行。因此报告为每个比较项打印两臂的计数、两个比率、落败、p 值与 Holm 阈值,读者既能看见规则标出的落败,也能看见它没有标出的落败。实测表按整次运行重采样,每次运行的探针因此保持在一起。汇总行不是:它把每次运行的每个探针算作一个观测,而同一次运行的探针共享一份对话记录,所以这些 p 值偏乐观。偏乐观的方向是多判回退,也就是多判候选失败;逐探针的行则是同一个探针跨整次运行比较。 -**失败运行与未判运行。** 失败运行是结束于错误或墙钟预算的那次运行,或者判分没有发生的那次:没有能交给判分模型的东西,或者判分调用失败——窗口溢出、传输错误或 HTTP 错误,或回复在输出上限处被截断。未判运行是判分模型回答了、但两次重问后仍给不出可用结论的那次运行,或者视图放不进判分模型预算、因此从未被询问的那次运行:它不计入所在臂的任何探针比率,报告会统计、连同原因一起列出它;未判运行率比较它。失败运行同样不在探针比率里,只比较一次,即失败运行率。重问得到的结论来自同一个判分模型、同样设置下更长的一段对话,两臂按同一规则重问。一次运行的判分读的是它导出的一幅视图:每条请求对照同一行上前一次请求给出——自那次请求以来新增的消息,历史变化后则是整份消息列表——请求的其余字段只在变化时完整给出,未变化时读作未变化标记,因此不丢弃任何东西。同一请求连续的 `step/thinking` 增量渲染成一行,按顺序带上它们的文本:一行增量大部分是事件 id 和字段名,而判分模型读的是整次运行。判分模型一次调用读完这幅视图。视图放不进判分模型声明的窗口(扣除回复的 `maxTokens`)时不分部分判分:统计、排序或贯穿整次运行的探针无法从单独一部分回答,因此该运行在做出任何调用之前就是未判运行,报告给出估算与预算。估算由 runner 自己在调用前给出,因此预测的溢出从不被询问。因窗口溢出被提供方拒绝的调用则说明声明的窗口或估算有误,它仍是失败运行:拒绝是运行超出模型真实窗口的显现方式,而失败运行数在两臂之间比较。场景判分模型被要求回答 `present` 或 `absent`;场景评估与摘要评估共用的判定解析器也接受 `contradicted`,`must_not_show` 探针把它视为没有出现。判分模型没有声明窗口的评估在第一次调用之前就失败。 +**失败运行与未判运行。** 失败运行是结束于错误或墙钟预算的那次运行,或者判分没有发生的那次:没有能交给判分模型的东西,或者判分调用失败——窗口溢出、传输错误或 HTTP 错误,或回复在输出上限处被截断。未判运行是判分模型回答了、但两次重问后仍给不出可用结论的那次运行,或者视图放不进判分模型预算、因此从未被询问的那次运行:它不计入所在臂的任何探针比率,报告会统计、连同原因一起列出它;未判运行率比较它。失败运行同样不在探针比率里,只比较一次,即失败运行率。不完整运行是 harness 在探针要读的请求出现之前就停下的那次运行——第一次 idle 之后的步骤没有跑,或 runner 提交的某个输入没有到达模型。它既不是失败运行也不是已判运行:不进所在臂的任何探针比率,不计入下限,报告会连同原因和失败、未判运行分开列出,因此没有任何请求可回答的探针不会被读成候选文本的损失。重问得到的结论来自同一个判分模型、同样设置下更长的一段对话,两臂按同一规则重问。一次运行的判分读的是它导出的一幅视图:每条请求对照同一行上前一次请求给出——自那次请求以来新增的消息,历史变化后则是整份消息列表——请求的其余字段只在变化时完整给出,未变化时读作未变化标记,因此不丢弃任何东西。同一请求连续的 `step/thinking` 增量渲染成一行,按顺序带上它们的文本:一行增量大部分是事件 id 和字段名,而判分模型读的是整次运行。判分模型一次调用读完这幅视图。视图放不进判分模型声明的窗口(扣除回复的 `maxTokens`)时不分部分判分:统计、排序或贯穿整次运行的探针无法从单独一部分回答,因此该运行在做出任何调用之前就是未判运行,报告给出估算与预算。估算由 runner 自己在调用前给出,因此预测的溢出从不被询问。因窗口溢出被提供方拒绝的调用则说明声明的窗口或估算有误,它仍是失败运行:拒绝是运行超出模型真实窗口的显现方式,而失败运行数在两臂之间比较。场景判分模型被要求回答 `present` 或 `absent`;场景评估与摘要评估共用的判定解析器也接受 `contradicted`,`must_not_show` 探针把它视为没有出现。判分模型没有声明窗口的评估在第一次调用之前就失败。 **候选走 shipped 装配。** 它放在作者的工厂配置里,就像摘要策略可选的 system prompt 成员([ContextCompaction §13.4](plugins/ContextCompaction.md#134-评估))让候选提示词替换固定那份——产品配置从不设置它——绝不在评估专用路径里改字符串;两臂因此跑的都是 shipped 的请求构建、分块与失败处理。 diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 2b45c00f82..7a65454f27 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -180,7 +180,10 @@ //! with no `completed` compaction of this run is compacted with //! `session.context.compact`, then each line is asked `request`. A //! compaction that does not complete fails the run there, so the requests -//! after it are only judged when a compaction happened. +//! after it are only judged when a compaction happened. A run its own budget +//! stops before that step, or before a submitted request ran on its line, is +//! an incomplete fixture: it is neither failed nor judged and enters no +//! probe rate. //! - `sources` declares the event producers a scenario runs with and the //! Session's subscription to them. One producer row is installed, only //! when `sources` is present, and it declares every source through the @@ -1185,6 +1188,7 @@ fn pooled_record(source: &Path, run: SavedRun, scenarios: &[Scenario]) -> Result window: run.window, duration_ms: run.duration_ms, failed: run.failed, + incomplete: run.incomplete, judge_outcome: run.judge_outcome, error: run.error, judge_error: run.judge_error, @@ -1260,7 +1264,9 @@ async fn rejudge_one( limits: JudgeWindow, cancel: &CancellationToken, ) -> Result { - let judging = if saved.judge_outcome == JudgeOutcome::NotAsked { + let judging = if saved.incomplete.is_some() { + Judging::unobserved(scenario) + } else if saved.judge_outcome == JudgeOutcome::NotAsked { Judging::not_asked(scenario, saved.judge_error.clone()) } else { let path = source @@ -1284,6 +1290,7 @@ async fn rejudge_one( window: saved.window, duration_ms: saved.duration_ms, failed: failed(stop, saved.error.as_deref(), judging.outcome), + incomplete: saved.incomplete.clone(), judge_outcome: judging.outcome, error: saved.error.clone(), judge_error: judging.error, @@ -1318,6 +1325,10 @@ struct SavedRun { duration_ms: f64, #[serde(default)] failed: bool, + /// Why the harness never produced a request the scenario's probe reads; + /// `None` in a record written before the runner wrote it. + #[serde(default)] + incomplete: Option, judge_outcome: JudgeOutcome, #[serde(default)] error: Option, @@ -2394,6 +2405,24 @@ pub(crate) struct AfterIdle { pub(crate) request: String, } +/// One input the runner submitted on the fixture's behalf. A run that its own +/// budget stopped before a request ran after the input was consumed did not +/// run the fixture its probe reads: it is incomplete, not scored +/// (model-prompts §8.1). +struct FixtureInput { + /// What the input is, named in the report when it was not observed. + what: &'static str, + /// The line the input was submitted to. + line: String, + /// The input id the Session answered; `None` when its reply named none. + input: Option, +} + +/// The scenario's own message. +const MESSAGE_INPUT: &str = "the message"; +/// One of the requests the step after the first idle submitted. +const AFTER_IDLE_INPUT: &str = "the request after the idle"; + /// One source a scenario declares through the `eventHub` service, and /// optionally subscribes its Session's `main` branch to (EventHub design A.1, /// A.3). Without `subscribe` the source starts unsubscribed, for a scenario @@ -2803,6 +2832,10 @@ struct RunRecord { /// Whether the run is a failed run, set once when the record is built /// (model-prompts §8.1). failed: bool, + /// Why the harness never produced a request the scenario's probe reads, + /// when it did not: the run is neither failed nor judged, enters no probe + /// rate, and does not count toward the floor. + incomplete: Option, /// How the run's judging ended (model-prompts §8.1). judge_outcome: JudgeOutcome, error: Option, @@ -2846,10 +2879,11 @@ impl RunRecord { ) } /// Whether the run is judged (model-prompts §8.1): it failed neither on - /// its own nor on its judging, and the judge answered every call with - /// usable verdicts. Only such a run counts toward the floor. + /// its own nor on its judging, the fixture was observed, and the judge + /// answered every call with usable verdicts. Only such a run counts + /// toward the floor. fn judged(&self) -> bool { - !self.failed && self.judge_outcome == JudgeOutcome::Judged + !self.failed && self.incomplete.is_none() && self.judge_outcome == JudgeOutcome::Judged } } @@ -2919,6 +2953,10 @@ enum JudgeOutcome { /// The judge was never asked: the view of the run's export does not fit /// the judge's budget. The run is unjudged. Unfit, + /// The judge was never asked: the harness stopped the run before a request + /// its probes read existed, so the run is an incomplete fixture, not a + /// scored one. + Unobserved, /// The judge answered every call and gave no usable verdicts after the /// re-asks. Unreadable, @@ -3127,6 +3165,10 @@ struct ChildOutcome { decline_retries: u32, switch_retries: u32, error: Option, + /// Why the harness never produced a request the scenario's probe reads; + /// `None` when the fixture was observed. + #[serde(default)] + incomplete: Option, judge_outcome: JudgeOutcome, judge_error: Option, judge_reasks: u32, @@ -3163,6 +3205,7 @@ fn harness_outcome(error: String, preflight: Vec) -> ChildOutcom decline_retries: 0, switch_retries: 0, error: None, + incomplete: None, judge_outcome: JudgeOutcome::NotAsked, judge_error: None, judge_reasks: 0, @@ -3708,6 +3751,7 @@ async fn child_drive( decline_retries: driven.decline_retries, switch_retries: driven.switch_retries, error: driven.error, + incomplete: driven.incomplete, judge_outcome: judging.outcome, judge_error: judging.error, judge_reasks: judging.reasks, @@ -5311,6 +5355,7 @@ fn supervisor_outcome( decline_retries: 0, switch_retries: 0, error: Some(error), + incomplete: None, judge_outcome: JudgeOutcome::NotAsked, judge_error: Some(judge_error), judge_reasks: 0, @@ -5673,6 +5718,7 @@ fn child_record( window: outcome.window, duration_ms: outcome.duration_ms, failed: failed(stop, error.as_deref(), outcome.judge_outcome), + incomplete: outcome.incomplete.clone(), judge_outcome: outcome.judge_outcome, error, @@ -5750,6 +5796,8 @@ impl Finished { decline_retries: 0, switch_retries: 0, switch_notes: SwitchNotes::default(), + inputs: Vec::new(), + incomplete: None, error: Some(error), }, export: None, @@ -5802,6 +5850,20 @@ impl Judging { temperature_dropped: false, } } + /// A run the harness stopped before a request its probes read existed: + /// the judge is not asked, and every probe stays unparsed. The run is + /// incomplete, not failed; its reason travels on the record + /// (model-prompts §8.1). + fn unobserved(scenario: &Scenario) -> Self { + Self { + outcome: JudgeOutcome::Unobserved, + probes: unparsed(scenario), + error: None, + reasks: 0, + calls: Vec::new(), + temperature_dropped: false, + } + } } #[expect( @@ -5980,14 +6042,29 @@ async fn drive_once( // whose request consumed the input without it is failed before the judge, // so the policy comparison cannot score an answer that did not see the // text being evaluated (Timeline branches §12.4). - if let Some(error) = switch_note_failure(&driven, &export) { + let notes = switch_note_check(&driven, &export); + if let NotesCheck::Unseen(error) = ¬es { driven.stop = "switch_note_missing"; driven.error = Some(error.clone()); return Ok(Finished { driven, export: Some(export), view: None, - judging: Judging::not_asked(scenario, Some(error)), + judging: Judging::not_asked(scenario, Some(error.clone())), + }); + } + // A run the harness stopped before the requests its probes read existed is + // incomplete, not scored: the probe's absence has no candidate behavior to + // read. A run that already failed keeps its failure (model-prompts §8.1). + if driven.error.is_none() + && let Some(reason) = incomplete_reason(&driven, scenario, &export, ¬es) + { + driven.incomplete = Some(reason); + return Ok(Finished { + driven, + export: Some(export), + view: None, + judging: Judging::unobserved(scenario), }); } let (Some(host), Some(resolver)) = ( @@ -6144,34 +6221,48 @@ fn budget_stop_reason(stop: &str) -> String { format!("budget: {stop}") } -/// The run's first missing switch note, or `None` when the run is not scored -/// on its notes: a run that already failed is not (Timeline branches §12.4). -fn switch_note_failure(driven: &Driven, export: &str) -> Option { +/// How a run's counted switch follow-ups ended (Timeline branches §12.4): +/// every one was carried by a request that reached the model, one was stopped +/// by the run's own turn cap before its model call, or one never reached the +/// model for another reason. +#[derive(Debug)] +enum NotesCheck { + Observed, + /// The run's turn cap stopped the note's request before its model call: + /// the note was not at fault, and the probe has no request to read. + CapCut { + line: String, + }, + /// The request never reached the model for another reason. + Unseen(String), +} + +/// The run's switch notes as the export shows them (Timeline branches §12.4). +/// A run that already failed is not checked. +fn switch_note_check(driven: &Driven, export: &str) -> NotesCheck { if driven.error.is_some() { - return None; + return NotesCheck::Observed; } let cap_stop = (driven.stop == "turns").then(|| budget_stop_reason(driven.stop)); switch_notes_unseen(export, &driven.switch_notes.expected, cap_stop.as_deref()) } -/// Why a scored switch follow-up did not see its note, or `None` when every -/// consumed follow-up's note reached the model: the first request the line -/// began after it consumed the input whose model call exists, and the note's -/// exact text (Timeline branches §12.4). An input no request consumed is not -/// checked: no answer of that line is scored. A request a steer replaced +/// Why a scored switch follow-up did not see its note, or [`NotesCheck::Observed`] +/// when every consumed follow-up's note reached the model: the first request +/// the line began after it consumed the input whose model call exists, and the +/// note's exact text (Timeline branches §12.4). An input no request consumed is +/// not checked: no answer of that line is scored. A request a steer replaced /// before its model call is not checked either: the note travels in the -/// request that replaces it in the same turn. Nor is a request the run's own -/// turn-budget stop ended, whose reason `cap_stop` carries: that stop, not the -/// note, kept it from the model (issue #2140). Every other request that never -/// reached the model is reported, because no request of the line carried the -/// text being evaluated. A request whose `step/model-start` carries no turn id -/// is exempted by neither: without the turn, neither the steer that replaced -/// it nor the stop that ended it can be placed. -fn switch_notes_unseen( - export: &str, - notes: &[SwitchNote], - cap_stop: Option<&str>, -) -> Option { +/// request that replaces it in the same turn. A request the run's own +/// turn-budget stop ended, whose reason `cap_stop` carries, is +/// [`NotesCheck::CapCut`]: that stop, not the note, kept it from the model +/// (issue #2140), and the run is incomplete rather than scored. Every other +/// request that never reached the model is [`NotesCheck::Unseen`], because no +/// request of the line carried the text being evaluated. A request whose +/// `step/model-start` carries no turn id is exempted by neither: without the +/// turn, neither the steer that replaced it nor the stop that ended it can be +/// placed. +fn switch_notes_unseen(export: &str, notes: &[SwitchNote], cap_stop: Option<&str>) -> NotesCheck { /// One `input/message` of the export, the line it is on, and the note it /// carries when it is one. struct Message { @@ -6294,9 +6385,10 @@ fn switch_notes_unseen( cut.insert((in_flight.branch.clone(), in_flight.request.clone())); } } - 'notes: for note in notes { + let mut cap_cut: Option = None; + for note in notes { let Some(message) = messages.get(¬e.input) else { - return Some(format!( + return NotesCheck::Unseen(format!( "the switch input {} on line {} is not in the export", note.input, note.line )); @@ -6315,7 +6407,7 @@ fn switch_notes_unseen( .collect(); requests.sort_by_key(|start| start.sequence); let Some(first) = requests.first() else { - return Some(format!( + return NotesCheck::Unseen(format!( "line {} consumed the switch input {} but started no request after it", note.line, note.input )); @@ -6333,6 +6425,7 @@ fn switch_notes_unseen( // run's turn budget stopped: the cap ended it, not the note. Any other // request without a model call ended before the note reached the model. let mut call = None; + let mut note_cap_cut = None; for start in &requests { let key = (start.branch.clone(), start.request.clone()); if let Some(found) = calls.get(&key) { @@ -6344,13 +6437,18 @@ fn switch_notes_unseen( continue; } if cut.contains(&key) { - continue 'notes; + note_cap_cut = Some(start.branch.clone()); + continue; } } break; } let Some(call) = call else { - return Some(format!( + if let Some(line) = note_cap_cut { + cap_cut.get_or_insert(line); + continue; + } + return NotesCheck::Unseen(format!( "line {} consumed the switch input {} but its request never reached the model", note.line, note.input )); @@ -6367,13 +6465,16 @@ fn switch_notes_unseen( .iter() .any(|text| request_carries(&call["messages"], text)) { - return Some(format!( + return NotesCheck::Unseen(format!( "the request that consumed the switch input on line {} does not carry the note it must answer under", note.line )); } } - None + match cap_cut { + Some(line) => NotesCheck::CapCut { line }, + None => NotesCheck::Observed, + } } /// Whether any string in `value` carries `needle`: a request is JSON, so a @@ -6387,6 +6488,94 @@ fn request_carries(value: &Value, needle: &str) -> bool { } } +/// Why the run's fixture was never observed, when it was not: its own message +/// and every request after the first idle must be consumed and followed by a +/// model request on their line, and a scenario with that step must have run +/// it. A run its own budget stopped before such a request is incomplete, not a +/// losing candidate: the probe has no request to read (model-prompts §8.1). +fn fixture_incomplete(driven: &Driven, scenario: &Scenario, export: &str) -> Option { + if scenario.after_idle.is_some() + && !driven + .inputs + .iter() + .any(|input| input.what == AFTER_IDLE_INPUT) + { + return Some(format!( + "the run stopped on {} before the step after the first idle", + driven.stop + )); + } + let mut consumed: Vec<(String, u64, String)> = Vec::new(); + let mut calls: Vec<(String, u64)> = Vec::new(); + for line in export.lines() { + let Ok(record) = serde_json::from_str::(line) else { + continue; + }; + if record["kind"] != "event" { + continue; + } + let event = &record["event"]; + let branch = record["branch_id"].as_str().unwrap_or_default().to_owned(); + let sequence = event["sequence"].as_u64().unwrap_or_default(); + match (event["type"].as_str(), event["name"].as_str()) { + (Some("input"), Some("consumed")) => { + if let Some(input) = event["data"]["input_id"].as_str() { + consumed.push((branch, sequence, input.to_owned())); + } + } + (Some("model"), Some("call")) => calls.push((branch, sequence)), + _ => {} + } + } + for input in &driven.inputs { + let Some(id) = input.input.as_deref() else { + return Some(format!( + "line {}: the Session named no input for {}, so the run cannot show it reached the model", + input.line, input.what + )); + }; + let Some(consumed_at) = consumed + .iter() + .filter(|(branch, _, seen)| branch == &input.line && seen == id) + .map(|(_, sequence, _)| *sequence) + .min() + else { + return Some(format!( + "line {}: {} was never consumed before the run stopped on {}", + input.line, input.what, driven.stop + )); + }; + if !calls + .iter() + .any(|(branch, sequence)| branch == &input.line && *sequence > consumed_at) + { + return Some(format!( + "line {}: no request ran after {} before the run stopped on {}", + input.line, input.what, driven.stop + )); + } + } + None +} + +/// Why the run its own budget stopped is an incomplete fixture, when it is: a +/// request its probes read never ran, or the turn cap stopped the one switch +/// follow-up request whose note was checked. A run that already failed keeps +/// its failure and is not incomplete (model-prompts §8.1). +fn incomplete_reason( + driven: &Driven, + scenario: &Scenario, + export: &str, + notes: &NotesCheck, +) -> Option { + fixture_incomplete(driven, scenario, export).or_else(|| match notes { + NotesCheck::CapCut { line } => Some(format!( + "line {line}: the switch follow-up's request was stopped by the run's turn budget before it reached the model" + )), + NotesCheck::Observed | NotesCheck::Unseen(_) => None, + }) +} + pub(crate) async fn selection( server: &RunningServer, target: &ModelId, @@ -6462,6 +6651,13 @@ struct Driven { /// The switch follow-ups the run sent and the notes each line's request /// must carry; the run is not judged when one is missing. switch_notes: SwitchNotes, + /// The inputs the runner submitted on the fixture's behalf: the scenario's + /// message and the requests after the first idle. + inputs: Vec, + /// Why the fixture's observation never happened, when it did not: the run + /// is neither failed nor judged, enters no probe rate, and the report + /// lists it apart from both. + incomplete: Option, error: Option, } @@ -6502,6 +6698,8 @@ async fn drive( decline_retries: 0, switch_retries: 0, switch_notes: SwitchNotes::default(), + inputs: Vec::new(), + incomplete: None, error: Some(error), }; } @@ -6531,6 +6729,8 @@ async fn drive( decline_retries: 0, switch_retries: 0, switch_notes: SwitchNotes::default(), + inputs: Vec::new(), + incomplete: None, error: Some(format!("session.create failed: {error}")), }; } @@ -6545,6 +6745,8 @@ async fn drive( decline_retries: 0, switch_retries: 0, switch_notes: SwitchNotes::default(), + inputs: Vec::new(), + incomplete: None, error: None, }; if let Err(error) = client @@ -6648,11 +6850,19 @@ async fn drive( return driven; } } - if let Err(error) = submit(client, &session, &scenario.message, None, None).await { - driven.stop = "error"; - driven.error = Some(error); - return driven; - } + let message = match submit(client, &session, &scenario.message, None, None).await { + Ok(input) => input, + Err(error) => { + driven.stop = "error"; + driven.error = Some(error); + return driven; + } + }; + driven.inputs.push(FixtureInput { + what: MESSAGE_INPUT, + line: "main".to_owned(), + input: message, + }); let started = Instant::now(); // The lines the run knows before its message: `main` and the line the calls // step opened, whose id is known before its `branch/create` notice arrives @@ -6881,7 +7091,16 @@ async fn drive( ) .await; match settled { - Ok(Ok(())) => awaiting = true, + Ok(Ok(submitted)) => { + for (line, input) in submitted { + driven.inputs.push(FixtureInput { + what: AFTER_IDLE_INPUT, + line, + input, + }); + } + awaiting = true; + } Ok(Err(error)) => { driven.stop = "error"; driven.error = Some(error); @@ -8374,14 +8593,15 @@ impl IdleCalls { /// branches §12.3). A compaction that does not complete ends the run here /// instead of letting the next request be judged as one after a compaction: /// the probe reads identity across a compaction, and a run that did not compact -/// measures nothing else. +/// measures nothing else. Answers each line's input, in the order sent, so the +/// caller can tell whether a request followed it. async fn settle_after_idle( client: &mut impl SwitchClient, session: &str, lines: &[String], after: &AfterIdle, compacted: &BTreeSet, -) -> std::result::Result<(), String> { +) -> std::result::Result)>, String> { for line in lines { if compacted.contains(line) { continue; @@ -8409,12 +8629,14 @@ async fn settle_after_idle( } } } + let mut submitted = Vec::with_capacity(lines.len()); for line in lines { - submit(client, session, &after.request, None, Some(line)) + let input = submit(client, session, &after.request, None, Some(line)) .await .map_err(|error| format!("{line}: the request after the idle failed: {error}"))?; + submitted.push((line.clone(), input)); } - Ok(()) + Ok(submitted) } /// Whether every known line is idle and no notice arrived while it asked. @@ -8857,6 +9079,9 @@ struct Metrics { impl Metrics { fn add(&mut self, scenario: &Scenario, record: &RunRecord) { self.runs += 1; + if record.incomplete.is_some() { + return; + } if record.unjudged() { self.unjudged += 1; return; @@ -9075,7 +9300,7 @@ impl Instrument { self.judge_window = self.judge_window.take().or(measured.judge_window); let asked = !matches!( record.judge_outcome, - JudgeOutcome::NotAsked | JudgeOutcome::Unfit + JudgeOutcome::NotAsked | JudgeOutcome::Unfit | JudgeOutcome::Unobserved ); match record.temperature_dropped { Some(dropped) => self.judge_temperature_dropped += usize::from(dropped), @@ -9325,6 +9550,27 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] ); } } + // A run the harness stopped before a request its probes read existed is an + // incomplete fixture, not the model's answer: the report names it apart + // from the failed runs and the rates it left, so a probe no run was judged + // on is not read as a lost identity (model-prompts §8.1). + let incomplete_runs: Vec<&RunRecord> = records + .iter() + .filter(|record| record.incomplete.is_some()) + .collect(); + if !incomplete_runs.is_empty() { + text += "\n| arm | scenario | run | incomplete |\n| --- | --- | --- | --- |\n"; + for record in incomplete_runs { + let reason = record.incomplete.as_deref().unwrap_or_default(); + text += &format!( + "| {} | {} | {} | {} |\n", + record.arm, + record.scenario, + record.run, + reason.lines().next().unwrap_or_default(), + ); + } + } text.push('\n'); text.push_str(&rule::verdict_line( &judged, @@ -9457,6 +9703,7 @@ mod tests { window: None, duration_ms: 0., failed: failed("idle", None, judge_outcome), + incomplete: None, judge_outcome, error: None, judge_error: None, @@ -9482,6 +9729,13 @@ mod tests { .collect(), } } + /// The error a `NotesCheck` reported, when it found an unseen request. + fn unseen_note(check: NotesCheck) -> Option { + match check { + NotesCheck::Unseen(error) => Some(error), + NotesCheck::Observed | NotesCheck::CapCut { .. } => None, + } + } fn metrics(scenario: &Scenario, records: &[RunRecord]) -> Metrics { let mut metrics = Metrics::default(); for record in records { @@ -10172,11 +10426,18 @@ mod tests { other: "main".into(), }]; assert!( - switch_notes_unseen(&export(note), ¬es, None).is_none(), + matches!( + switch_notes_unseen(&export(note), ¬es, None), + NotesCheck::Observed + ), "the request carries the note" ); - let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, None) - .expect("the request without the note is unseen"); + let unseen = unseen_note(switch_notes_unseen( + &export("the follow-up was answered"), + ¬es, + None, + )) + .expect("the request without the note is unseen"); assert!(unseen.contains("line 2"), "{unseen}"); } @@ -10226,11 +10487,18 @@ mod tests { other: "main".into(), }]; assert!( - switch_notes_unseen(&export(note), ¬es, None).is_none(), + matches!( + switch_notes_unseen(&export(note), ¬es, None), + NotesCheck::Observed + ), "the replacement request carries the note" ); - let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, None) - .expect("the request without the note is still unseen"); + let unseen = unseen_note(switch_notes_unseen( + &export("the follow-up was answered"), + ¬es, + None, + )) + .expect("the request without the note is still unseen"); assert!(unseen.contains("does not carry the note"), "{unseen}"); } @@ -10279,19 +10547,20 @@ mod tests { default: true, other: "main".into(), }]; - let unseen = switch_notes_unseen(&export(true), ¬es, None) + let unseen = unseen_note(switch_notes_unseen(&export(true), ¬es, None)) .expect("the closed request never reached the model"); assert!(unseen.contains("never reached the model"), "{unseen}"); - let unseen = switch_notes_unseen(&export(false), ¬es, None) + let unseen = unseen_note(switch_notes_unseen(&export(false), ¬es, None)) .expect("no request started after the consumption"); assert!(unseen.contains("started no request after it"), "{unseen}"); } /// A run that stopped on its turn budget ended the request before its - /// model call, so the note the missing call would have answered is not - /// reported; the same export with any other stop is (issue #2140). + /// model call: the note is not a missing note, but the run has no request + /// for its probe to read, so it is an incomplete fixture. The same export + /// with any other stop is a missing note (issue #2140). #[test] - fn a_turn_budget_stop_does_not_report_a_note_its_stop_ended() { + fn a_turn_budget_stop_makes_a_note_its_stop_ended_incomplete() { let note = "\nswitched from line main.\n"; let export = [ json!({"kind": "event", "branch_id": "2", @@ -10326,10 +10595,13 @@ mod tests { other: "main".into(), }]; assert!( - switch_notes_unseen(&export, ¬es, Some("budget: turns")).is_none(), + matches!( + switch_notes_unseen(&export, ¬es, Some("budget: turns")), + NotesCheck::CapCut { ref line } if line == "2" + ), "the run's turn budget ended the request before its model call" ); - let unseen = switch_notes_unseen(&export, ¬es, None) + let unseen = unseen_note(switch_notes_unseen(&export, ¬es, None)) .expect("any other stop still reports the note"); assert!(unseen.contains("never reached the model"), "{unseen}"); } @@ -10446,7 +10718,7 @@ mod tests { other: "main".into(), }, ]; - let unseen = switch_notes_unseen(&export, ¬es, Some("budget: turns")); + let unseen = unseen_note(switch_notes_unseen(&export, ¬es, Some("budget: turns"))); assert!( unseen.as_deref().is_some_and( |error| error.contains("line 3") && error.contains("never reached the model") @@ -10518,8 +10790,12 @@ mod tests { json!({"turn_id": "t1", "status": "completed", "reason": "end_turn"}), ), ] { - let unseen = switch_notes_unseen(&export(end), ¬es, Some("budget: turns")) - .expect("a request that ended before the stop still needs its note"); + let unseen = unseen_note(switch_notes_unseen( + &export(end), + ¬es, + Some("budget: turns"), + )) + .expect("a request that ended before the stop still needs its note"); assert!(unseen.contains("never reached the model"), "{unseen}"); } } @@ -10568,7 +10844,7 @@ mod tests { .map(|record| serde_json::to_string(record).unwrap()) .collect::>() .join("\n"); - let unseen = switch_notes_unseen(&export, ¬es, Some("budget: turns")) + let unseen = unseen_note(switch_notes_unseen(&export, ¬es, Some("budget: turns"))) .expect("an unplaced request is not exempted by the stop"); assert!(unseen.contains("never reached the model"), "{unseen}"); } @@ -10619,12 +10895,149 @@ mod tests { other: "main".into(), }], }, + inputs: Vec::new(), + incomplete: None, error: None, }; - let unseen = switch_note_failure(&driven, &export).expect("the note is missing"); + let unseen = unseen_note(switch_note_check(&driven, &export)).expect("the note is missing"); assert!(unseen.contains("does not carry the note"), "{unseen}"); } + /// The fixture's own inputs must be consumed and followed by a request on + /// their line. A run its own budget stopped before the step after the first + /// idle, or before the follow-up request, leaves the probe with nothing to + /// read: it is an incomplete fixture, not a losing candidate + /// (model-prompts §8.1). + #[test] + fn a_fixture_its_budget_stopped_before_its_requests_is_incomplete() { + let event = |branch: &str, sequence: u64, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": branch, + "event": {"id": format!("e{sequence}"), "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + .to_string() + }; + let mut scenario = scenario(vec![probe("identity", ProbeKind::MustShow)]); + scenario.after_idle = Some(AfterIdle { + request: "Re-run the tests.".into(), + }); + let mut driven = Driven { + session: "s".into(), + stop: "turns", + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes::default(), + inputs: vec![FixtureInput { + what: MESSAGE_INPUT, + line: "main".into(), + input: Some("m1".into()), + }], + incomplete: None, + error: None, + }; + let export = [ + event( + "main", + 1, + ["input", "message"], + json!({"user": {"content": "message"}}), + ), + event("main", 2, ["input", "consumed"], json!({"input_id": "m1"})), + event("main", 3, ["model", "call"], json!({"request": {}})), + ] + .join("\n"); + let reason = fixture_incomplete(&driven, &scenario, &export).unwrap(); + assert!( + reason.contains("before the step after the first idle"), + "{reason}" + ); + + driven.inputs.push(FixtureInput { + what: AFTER_IDLE_INPUT, + line: "main".into(), + input: Some("f1".into()), + }); + let consumed = [ + event( + "main", + 4, + ["input", "message"], + json!({"user": {"content": "Re-run the tests."}}), + ), + event("main", 5, ["input", "consumed"], json!({"input_id": "f1"})), + ] + .join("\n"); + let reason = + fixture_incomplete(&driven, &scenario, &format!("{export}\n{consumed}")).unwrap(); + assert!(reason.contains("no request ran after"), "{reason}"); + + let after = [ + consumed.clone(), + event("main", 6, ["model", "call"], json!({"request": {}})), + ] + .join("\n"); + assert_eq!( + fixture_incomplete(&driven, &scenario, &format!("{export}\n{after}")), + None, + "the request after the follow-up makes the fixture complete" + ); + } + + /// A switch follow-up request the run's turn cap stopped has no request + /// for its probe to read: the note check reports the cap, and the run is + /// incomplete rather than scored (model-prompts §8.1). + #[test] + fn a_cap_cut_switch_follow_up_makes_the_run_incomplete() { + let event = |sequence: u64, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": "main", + "event": {"id": format!("e{sequence}"), "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + .to_string() + }; + let export = [ + event( + 1, + ["input", "message"], + json!({"user": {"content": "message"}}), + ), + event(2, ["input", "consumed"], json!({"input_id": "m1"})), + event(3, ["model", "call"], json!({"request": {}})), + ] + .join("\n"); + let driven = Driven { + session: "s".into(), + stop: "turns", + timed_out: false, + cleanup_deadline: None, + turns: 4, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes::default(), + inputs: vec![FixtureInput { + what: MESSAGE_INPUT, + line: "main".into(), + input: Some("m1".into()), + }], + incomplete: None, + error: None, + }; + let reason = incomplete_reason( + &driven, + &scenario(Vec::new()), + &export, + &NotesCheck::CapCut { line: "2".into() }, + ) + .unwrap(); + assert!( + reason.contains("line 2") && reason.contains("turn budget"), + "{reason}" + ); + } + /// A switch that has started its target stays with it: a tool line opened /// afterwards has its own purpose, so the retry of a move promotes the /// line that started rather than the newer line (model-prompts §9.8). @@ -11199,9 +11612,17 @@ mod tests { let after = AfterIdle { request: "re-run the tests".into(), }; - settle_after_idle(&mut client, "session", &lines, &after, &compacted) + let submitted = settle_after_idle(&mut client, "session", &lines, &after, &compacted) .await .unwrap(); + assert_eq!( + submitted, + [ + ("main".to_owned(), Some("input".to_owned())), + ("line".to_owned(), Some("input".to_owned())) + ], + "every line's request is returned with the input the Session named" + ); assert_eq!( client.methods(), [ @@ -12749,6 +13170,8 @@ mod tests { decline_retries: 0, switch_retries: 0, switch_notes: SwitchNotes::default(), + inputs: Vec::new(), + incomplete: None, error: None, } } @@ -15260,6 +15683,57 @@ mod tests { } } + /// A run that reaches its turn budget before the step after the first idle + /// never compacts and never asks the follow-up request: the identity probe + /// has no request to read, so the run is incomplete, is not judged, and + /// stays out of the probe's denominator and the floor (model-prompts + /// §8.1). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_run_that_reaches_the_turn_budget_before_the_after_idle_step_is_incomplete() { + let fixture = Fixture::start( + "incomplete-turn-cap", + |text| judged(text).or_else(|| Some(content("done"))), + json!({ + "message": "Say hello.", + "budget": {"turns": 1, "seconds": 60, "window": 24000}, + "afterIdle": {"request": "Re-run the tests."}, + "probes": [{"id": "ran", "kind": "must_show", "text": "the run has a transcript"}] + }), + &[], + ) + .await; + let options = fixture.options(fixture.directory.join("out")); + let report = fixture.evaluate(&options).await.unwrap(); + let records = fixture.records(&options.out); + assert_eq!(records.len(), 2, "one run per arm"); + for record in &records { + assert_eq!(record["stop"], "turns", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "unobserved", "{record}"); + let incomplete = record["incomplete"].as_str().unwrap_or_default(); + assert!( + incomplete.contains("before the step after the first idle"), + "{record}" + ); + } + assert!( + fixture.judge().is_empty(), + "an incomplete fixture is not sent to the judge" + ); + assert!( + report.contains("| arm | scenario | run | incomplete |"), + "the report lists the incomplete fixture apart: {report}" + ); + assert!( + report.contains("| case/ran (must_show) | – | – |"), + "the probe counts no run in either arm: {report}" + ); + assert!( + report.contains("| failed runs | 0/1 (0.000) | 0/1 (0.000) |"), + "an incomplete run is not a failed run: {report}" + ); + } + /// Asserts that a run's `judge-view.jsonl` is its export line for line, /// with every request rebuilt from the view alone into the one the export /// carried, and answers the view's rendered requests in order. @@ -15777,6 +16251,11 @@ mod tests { /// `session.create` reports, and the submitted turn starts and ends /// at once: a scenario's `session_open` call has a sequence to use. OpensAtTheSessionStart, + /// The submitted turn starts and ends once; the step after the first + /// idle submits its request, and the peer writes the second turn's end + /// before that request can start, so the run reaches its turn budget + /// between the submission and the model call. + AfterIdleSubmitAtTheCap, } /// What a scripted peer read: the `requestId` of every decline, in order, @@ -15924,7 +16403,10 @@ mod tests { // The line is busy until the peer writes the call's result, the // way a running turn is: `session.idle` stays unanswered and the // driver's own deadline reports the line busy. - let mut settled = matches!(script, PeerScript::OpensAtTheSessionStart); + let mut settled = matches!( + script, + PeerScript::OpensAtTheSessionStart | PeerScript::AfterIdleSubmitAtTheCap + ); // [`PeerScript::HeldIdle`]'s hold: the calls it kept, and the // deadline it answers them at. The deadline stands after the // release, so a later call starts no second hold. @@ -16092,6 +16574,7 @@ mod tests { | PeerScript::ChainedToolLineAfterActivation => None, PeerScript::DeferredUsageFails => None, PeerScript::OpensAtTheSessionStart => None, + PeerScript::AfterIdleSubmitAtTheCap => None, }; if let Some((request, sequence)) = closed { if recorded.settled_at.load(Ordering::SeqCst) == 0 { @@ -16146,6 +16629,7 @@ mod tests { } } "session.idle" => json!({"result": {"sequence": PEER_SEQUENCE}}), + "session.context.compact" => json!({"result": {"status": "completed"}}), "session.branch_set_default" if matches!(script, PeerScript::SwitchMoveRetries) => { @@ -16203,6 +16687,24 @@ mod tests { .unwrap(); } if method == "session.submit" { + if matches!(script, PeerScript::AfterIdleSubmitAtTheCap) { + // The first turn runs and ends; the step after the idle + // submits its request, and the peer ends the second + // turn before that request can start. + let events = if submits == 1 { + vec![("start", 1), ("end", 2)] + } else { + vec![("end", 3)] + }; + for (name, sequence) in events { + write + .write_all(¬ice(json!({"type": "turn", "name": name, + "sequence": sequence, "data": {}}))) + .await + .unwrap(); + } + continue; + } write .write_all(¬ice( json!({"type": "turn", "name": "start", "sequence": 1, "data": {}}), @@ -16618,6 +17120,64 @@ mod tests { ); } + /// A run that reaches its turn budget after the step after the first idle + /// submitted a request, but before that request reached the model, has no + /// request for the identity probe to read: the runner keeps the + /// submission, and the export decides that it was never observed + /// (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_turn_budget_after_the_after_idle_submit_leaves_the_request_unobserved() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-after-idle-cap-{}", + std::process::id() + )); + let (socket, _) = + scripted_peer(&directory, 8_000, PeerScript::AfterIdleSubmitAtTheCap).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.turns = 2; + scenario.budget.seconds = 10.; + scenario.budget.window = 8_000; + scenario.after_idle = Some(AfterIdle { + request: "Re-run the tests.".into(), + }); + let driven = drive( + &mut client, + &RunSettings::default(), + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let _ = std::fs::remove_dir_all(directory); + assert_eq!(driven.stop, "turns", "{:?}", driven.error); + assert_eq!(driven.turns, 2, "the run stopped on its turn budget"); + let after: Vec<&FixtureInput> = driven + .inputs + .iter() + .filter(|input| input.what == AFTER_IDLE_INPUT) + .collect(); + assert_eq!( + after.len(), + 1, + "the step after the idle submitted its request" + ); + assert_eq!(after[0].line, "main"); + assert_eq!(after[0].input.as_deref(), Some("input-2")); + assert_eq!( + driven.inputs.len(), + 2, + "the message and the request after the idle are the fixture's inputs" + ); + assert!( + driven.incomplete.is_none(), + "the runner has no export yet: the export decides the observation" + ); + } + /// A chained move to the latest tool line uses the line the run has seen /// opened, even when it opened while the move before it waited: a line /// that exists when the move is activated is the one its role names, so From e364b213eee91327f192cc27acca5a8a5cd14118 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 04:05:57 +0800 Subject: [PATCH 19/25] fix(scenario-eval): keep an incomplete fixture to the turn cap A run that stopped on its wall clock is a failed run: the harness did not stop it before a request its probes read existed, its own budget did. The incomplete class covers only the harness's turn cap: before the step after the first idle, before a submitted input's request, or before the request a switch follow-up needed. A run that ended idle is scored as it was before the class existed: the stop is the product's state, not the harness's budget, so an input the run left unrun is the candidate's outcome, not a fixture set aside. The failed count, the failed-run rate and the report's classes are what they were before the class existed, and no record carries a failure and an incomplete reason at once. Section 8.1 says the same in both languages. Tests: a_run_that_stopped_on_its_wall_clock_is_failed_not_incomplete and an_idle_run_is_scored_rather_than_incomplete fail on the previous revision, where the run is recorded as an incomplete fixture. --- docs/design/model-prompts.md | 2 +- docs/zh/design/model-prompts.md | 2 +- xtask/src/scenario_eval.rs | 159 ++++++++++++++++++++++++++++++-- 3 files changed, 153 insertions(+), 10 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index 8294ee1ab8..d19ee951a9 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -163,7 +163,7 @@ A probe's rate counts judged, non-failed runs only, and failed runs are compared The last row is the rule's limit at the floor: catching that loss 80% of the time needs about 44–51 runs per scenario per arm. The report therefore prints both arms' counts, both rates, the loss, the p-value and the Holm threshold for every comparison, so a reader sees a loss the rule did not flag as well as one it did. The measured table resamples whole runs, which keeps each run's probes together. The pooled rows do not: they count each probe of each run as an observation, and the probes of one run share a transcript, so those p-values are optimistic. That errs toward rejecting, which means failing a candidate, and the per-probe rows compare one probe over whole runs. -**Failed and unjudged runs.** A failed run is one that ended on an error or its wall-clock budget, or one whose judging did not happen: there was nothing the judge could be asked, or a judge call failed — a window overflow, a transport or an HTTP error, or a reply cut off at its output cap. An unjudged run is one the judge answered but gave no usable verdicts for after two re-asks, or one whose view does not fit the judge's budget, which is never asked: it enters none of its arm's probe rates, and the report counts it and lists it with its reason; the unjudged-run rate compares it. A failed run is out of the probe rates too, and is compared once, as the failed-run rate. An incomplete run is one the harness stopped before a request its probes read existed — the step after the first idle never ran, or an input the runner submitted never reached the model. It is neither a failed nor a judged run: it enters none of its arm's probe rates, does not count toward the floor, and the report lists it with its reason apart from the failed and unjudged runs, so a probe no request could answer is not read as the candidate's loss. A re-asked verdict comes from a longer conversation with the same judge at the same settings, and both arms are re-asked by the same rule. A run is judged through a view of its export: each request is given against the previous request of its line — the messages added since that request, or the whole message list after a history change — and every other field of the request appears in full only when it changed, or as an unchanged marker when it did not, so nothing is dropped. A request's consecutive `step/thinking` deltas are one line carrying their text in order, because a delta line is mostly an event id and field names and the judge reads the run as a whole. The judge reads the view in one call. A view that does not fit the judge's declared window — the window less the reply's `maxTokens` — is not split into parts: a probe that counts, orders or holds over a whole run cannot be answered from one part, so the run is unjudged before any call, and the report gives the estimate and the budget. The estimate is the runner's own and is taken before any call, so a predicted overflow is never asked. A call the provider refuses for a window overflow therefore means the declared window or the estimate was wrong, and it stays a failed run: a refusal is how a run outgrowing its model's real window shows up, and failed runs are compared between the arms. The scenario judge is asked for `present` or `absent`; the verdict parser the scenario and summary evaluations share also accepts `contradicted`, which a `must_not_show` probe treats as not shown. An evaluation whose judge declares no window fails before its first call. +**Failed and unjudged runs.** A failed run is one that ended on an error or its wall-clock budget, or one whose judging did not happen: there was nothing the judge could be asked, or a judge call failed — a window overflow, a transport or an HTTP error, or a reply cut off at its output cap. An unjudged run is one the judge answered but gave no usable verdicts for after two re-asks, or one whose view does not fit the judge's budget, which is never asked: it enters none of its arm's probe rates, and the report counts it and lists it with its reason; the unjudged-run rate compares it. A failed run is out of the probe rates too, and is compared once, as the failed-run rate. An incomplete run is one the harness's turn cap stopped before a request its probes read existed: the step after the first idle never ran, an input the runner submitted never reached the model, or the request a switch follow-up needed was stopped by the cap. A run its wall clock stopped is a failed run, not an incomplete one, and a run that ended idle is scored for the requests its export holds. It is neither a failed nor a judged run: it enters none of its arm's probe rates, does not count toward the floor, and the report lists it with its reason apart from the failed and unjudged runs, so a probe no request could answer is not read as the candidate's loss. A re-asked verdict comes from a longer conversation with the same judge at the same settings, and both arms are re-asked by the same rule. A run is judged through a view of its export: each request is given against the previous request of its line — the messages added since that request, or the whole message list after a history change — and every other field of the request appears in full only when it changed, or as an unchanged marker when it did not, so nothing is dropped. A request's consecutive `step/thinking` deltas are one line carrying their text in order, because a delta line is mostly an event id and field names and the judge reads the run as a whole. The judge reads the view in one call. A view that does not fit the judge's declared window — the window less the reply's `maxTokens` — is not split into parts: a probe that counts, orders or holds over a whole run cannot be answered from one part, so the run is unjudged before any call, and the report gives the estimate and the budget. The estimate is the runner's own and is taken before any call, so a predicted overflow is never asked. A call the provider refuses for a window overflow therefore means the declared window or the estimate was wrong, and it stays a failed run: a refusal is how a run outgrowing its model's real window shows up, and failed runs are compared between the arms. The scenario judge is asked for `present` or `absent`; the verdict parser the scenario and summary evaluations share also accepts `contradicted`, which a `must_not_show` probe treats as not shown. An evaluation whose judge declares no window fails before its first call. **The candidate runs through the shipped assembly.** It is put in place at its author's factory configuration, as the summary strategy's optional system prompt member specified in [ContextCompaction §13.4](plugins/ContextCompaction.md#134-evaluation) allows a candidate prompt to replace the fixed one — the product profile never sets it — and never by patching strings in an evaluation-only path, so both arms run the shipped request building, chunking and failure handling. diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index efdcbc1469..35b16a9ac4 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -163,7 +163,7 @@ 最后一行就是规则在下限处的极限:要以 80% 的概率发现它,每场景每臂需要约 44–51 次运行。因此报告为每个比较项打印两臂的计数、两个比率、落败、p 值与 Holm 阈值,读者既能看见规则标出的落败,也能看见它没有标出的落败。实测表按整次运行重采样,每次运行的探针因此保持在一起。汇总行不是:它把每次运行的每个探针算作一个观测,而同一次运行的探针共享一份对话记录,所以这些 p 值偏乐观。偏乐观的方向是多判回退,也就是多判候选失败;逐探针的行则是同一个探针跨整次运行比较。 -**失败运行与未判运行。** 失败运行是结束于错误或墙钟预算的那次运行,或者判分没有发生的那次:没有能交给判分模型的东西,或者判分调用失败——窗口溢出、传输错误或 HTTP 错误,或回复在输出上限处被截断。未判运行是判分模型回答了、但两次重问后仍给不出可用结论的那次运行,或者视图放不进判分模型预算、因此从未被询问的那次运行:它不计入所在臂的任何探针比率,报告会统计、连同原因一起列出它;未判运行率比较它。失败运行同样不在探针比率里,只比较一次,即失败运行率。不完整运行是 harness 在探针要读的请求出现之前就停下的那次运行——第一次 idle 之后的步骤没有跑,或 runner 提交的某个输入没有到达模型。它既不是失败运行也不是已判运行:不进所在臂的任何探针比率,不计入下限,报告会连同原因和失败、未判运行分开列出,因此没有任何请求可回答的探针不会被读成候选文本的损失。重问得到的结论来自同一个判分模型、同样设置下更长的一段对话,两臂按同一规则重问。一次运行的判分读的是它导出的一幅视图:每条请求对照同一行上前一次请求给出——自那次请求以来新增的消息,历史变化后则是整份消息列表——请求的其余字段只在变化时完整给出,未变化时读作未变化标记,因此不丢弃任何东西。同一请求连续的 `step/thinking` 增量渲染成一行,按顺序带上它们的文本:一行增量大部分是事件 id 和字段名,而判分模型读的是整次运行。判分模型一次调用读完这幅视图。视图放不进判分模型声明的窗口(扣除回复的 `maxTokens`)时不分部分判分:统计、排序或贯穿整次运行的探针无法从单独一部分回答,因此该运行在做出任何调用之前就是未判运行,报告给出估算与预算。估算由 runner 自己在调用前给出,因此预测的溢出从不被询问。因窗口溢出被提供方拒绝的调用则说明声明的窗口或估算有误,它仍是失败运行:拒绝是运行超出模型真实窗口的显现方式,而失败运行数在两臂之间比较。场景判分模型被要求回答 `present` 或 `absent`;场景评估与摘要评估共用的判定解析器也接受 `contradicted`,`must_not_show` 探针把它视为没有出现。判分模型没有声明窗口的评估在第一次调用之前就失败。 +**失败运行与未判运行。** 失败运行是结束于错误或墙钟预算的那次运行,或者判分没有发生的那次:没有能交给判分模型的东西,或者判分调用失败——窗口溢出、传输错误或 HTTP 错误,或回复在输出上限处被截断。未判运行是判分模型回答了、但两次重问后仍给不出可用结论的那次运行,或者视图放不进判分模型预算、因此从未被询问的那次运行:它不计入所在臂的任何探针比率,报告会统计、连同原因一起列出它;未判运行率比较它。失败运行同样不在探针比率里,只比较一次,即失败运行率。不完整运行是 harness 的轮数上限在探针要读的请求出现之前就停下的那次运行:第一次 idle 之后的步骤没有跑、runner 提交的输入没有到达模型,或者 switch 动作的跟进请求被上限停掉;墙钟到点的运行是失败运行,不是不完整运行,idle 结束的运行按它导出里实际有的请求计分。它既不是失败运行也不是已判运行:不进所在臂的任何探针比率,不计入下限,报告会连同原因和失败、未判运行分开列出,因此没有任何请求可回答的探针不会被读成候选文本的损失。重问得到的结论来自同一个判分模型、同样设置下更长的一段对话,两臂按同一规则重问。一次运行的判分读的是它导出的一幅视图:每条请求对照同一行上前一次请求给出——自那次请求以来新增的消息,历史变化后则是整份消息列表——请求的其余字段只在变化时完整给出,未变化时读作未变化标记,因此不丢弃任何东西。同一请求连续的 `step/thinking` 增量渲染成一行,按顺序带上它们的文本:一行增量大部分是事件 id 和字段名,而判分模型读的是整次运行。判分模型一次调用读完这幅视图。视图放不进判分模型声明的窗口(扣除回复的 `maxTokens`)时不分部分判分:统计、排序或贯穿整次运行的探针无法从单独一部分回答,因此该运行在做出任何调用之前就是未判运行,报告给出估算与预算。估算由 runner 自己在调用前给出,因此预测的溢出从不被询问。因窗口溢出被提供方拒绝的调用则说明声明的窗口或估算有误,它仍是失败运行:拒绝是运行超出模型真实窗口的显现方式,而失败运行数在两臂之间比较。场景判分模型被要求回答 `present` 或 `absent`;场景评估与摘要评估共用的判定解析器也接受 `contradicted`,`must_not_show` 探针把它视为没有出现。判分模型没有声明窗口的评估在第一次调用之前就失败。 **候选走 shipped 装配。** 它放在作者的工厂配置里,就像摘要策略可选的 system prompt 成员([ContextCompaction §13.4](plugins/ContextCompaction.md#134-评估))让候选提示词替换固定那份——产品配置从不设置它——绝不在评估专用路径里改字符串;两臂因此跑的都是 shipped 的请求构建、分块与失败处理。 diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 7a65454f27..da48f11437 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -180,10 +180,11 @@ //! with no `completed` compaction of this run is compacted with //! `session.context.compact`, then each line is asked `request`. A //! compaction that does not complete fails the run there, so the requests -//! after it are only judged when a compaction happened. A run its own budget -//! stops before that step, or before a submitted request ran on its line, is -//! an incomplete fixture: it is neither failed nor judged and enters no -//! probe rate. +//! after it are only judged when a compaction happened. A run the turn cap +//! stops before that step, or before a submitted request ran on its line, +//! is an incomplete fixture: it is neither failed nor judged and enters no +//! probe rate. A run its wall clock stops is failed, and a run that ends +//! idle is scored for what its export holds. //! - `sources` declares the event producers a scenario runs with and the //! Session's subscription to them. One producer row is installed, only //! when `sources` is present, and it declares every source through the @@ -6558,16 +6559,21 @@ fn fixture_incomplete(driven: &Driven, scenario: &Scenario, export: &str) -> Opt None } -/// Why the run its own budget stopped is an incomplete fixture, when it is: a -/// request its probes read never ran, or the turn cap stopped the one switch -/// follow-up request whose note was checked. A run that already failed keeps -/// its failure and is not incomplete (model-prompts §8.1). +/// Why the run is an incomplete fixture, when it is: the harness's turn cap +/// stopped it before a request its probes read existed — before the step after +/// the first idle, before a submitted input's request, or before the request a +/// switch follow-up needed. Any other stop keeps its own scoring: a run its +/// wall clock or an error ended is failed, and a run that ended idle is scored +/// for what its export holds (model-prompts §8.1). fn incomplete_reason( driven: &Driven, scenario: &Scenario, export: &str, notes: &NotesCheck, ) -> Option { + if driven.stop != "turns" { + return None; + } fixture_incomplete(driven, scenario, export).or_else(|| match notes { NotesCheck::CapCut { line } => Some(format!( "line {line}: the switch follow-up's request was stopped by the run's turn budget before it reached the model" @@ -10986,6 +10992,49 @@ mod tests { ); } + /// A run that stopped on its wall clock is a failed run, not an incomplete + /// fixture: the harness did not stop it before a request its probes read + /// existed, the run's own budget did, and a probe that saw no request is + /// the candidate's outcome (model-prompts §8.1). + #[test] + fn a_run_that_stopped_on_its_wall_clock_is_failed_not_incomplete() { + let mut scenario = scenario(vec![probe("identity", ProbeKind::MustShow)]); + scenario.after_idle = Some(AfterIdle { + request: "Re-run the tests.".into(), + }); + let driven = Driven { + session: "s".into(), + stop: "seconds", + timed_out: true, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes::default(), + inputs: vec![FixtureInput { + what: MESSAGE_INPUT, + line: "main".into(), + input: Some("m1".into()), + }], + incomplete: None, + error: None, + }; + let export = json!({"kind": "event", "branch_id": "main", + "event": {"id": "e1", "sequence": 1, "type": "input", + "name": "message", "data": {}}}) + .to_string(); + assert_eq!( + incomplete_reason(&driven, &scenario, &export, &NotesCheck::Observed), + None, + "the wall clock ended the run, not the step after the first idle" + ); + assert!( + failed(driven.stop, driven.error.as_deref(), JudgeOutcome::Judged), + "a run that stopped on its wall clock is a failed run" + ); + } + /// A switch follow-up request the run's turn cap stopped has no request /// for its probe to read: the note check reports the cap, and the run is /// incomplete rather than scored (model-prompts §8.1). @@ -11038,6 +11087,100 @@ mod tests { ); } + /// A run that ended idle is scored as it was before the incomplete class + /// existed: the stop is the product's state, not the harness's turn cap, + /// so an input it left unrun is the candidate's outcome, not a fixture + /// the report sets aside (model-prompts §8.1). + #[test] + fn an_idle_run_is_scored_rather_than_incomplete() { + let event = |sequence: u64, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": "main", + "event": {"id": format!("e{sequence}"), "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + .to_string() + }; + let message = || FixtureInput { + what: MESSAGE_INPUT, + line: "main".into(), + input: Some("m1".into()), + }; + let driven = |stop: &'static str| Driven { + session: "s".into(), + stop, + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes::default(), + inputs: vec![message()], + incomplete: None, + error: None, + }; + let scenario = scenario(vec![probe("identity", ProbeKind::MustShow)]); + let message_event = event( + 1, + ["input", "message"], + json!({"user": {"content": "message"}}), + ); + let consumed = event(2, ["input", "consumed"], json!({"input_id": "m1"})); + + assert!( + fixture_incomplete(&driven("turns"), &scenario, &message_event).is_some(), + "the input the run left unrun is what the fixture check reads" + ); + assert_eq!( + incomplete_reason( + &driven("idle"), + &scenario, + &message_event, + &NotesCheck::Observed + ), + None, + "a run that ended idle is not the harness's stop" + ); + + let no_request = [message_event, consumed].join("\n"); + assert!( + fixture_incomplete(&driven("turns"), &scenario, &no_request) + .is_some_and(|reason| reason.contains("no request ran after")), + "the consumed input without a request is what the fixture check reads" + ); + assert_eq!( + incomplete_reason( + &driven("idle"), + &scenario, + &no_request, + &NotesCheck::Observed + ), + None, + "a run that ended idle is not the harness's stop" + ); + + let idle = record( + "current", + &scenario, + &[("identity", ProbeVerdict::Unparsed)], + JudgeOutcome::Judged, + ); + assert!(!idle.failed, "idle is not one of the failed stops"); + let mut metrics = Metrics::default(); + metrics.add(&scenario, &idle); + assert_eq!( + (metrics.runs, metrics.failed, metrics.unjudged), + (1, 0, 0), + "the idle run is counted, as it was before the class existed" + ); + assert_eq!( + metrics + .probes + .get(&("case".to_owned(), "identity".to_owned())), + Some(&ProbeCounts { passed: 0, runs: 1 }), + "the probe the run left unanswered is counted as a loss" + ); + } + /// A switch that has started its target stays with it: a tool line opened /// afterwards has its own purpose, so the retry of a move promotes the /// line that started rather than the newer line (model-prompts §9.8). From c3d480a4965f5801af011fc1f4530d72a91a0316 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 03:29:13 +0800 Subject: [PATCH 20/25] fix(scenario-eval): read a switch note check as a reason or none The switch note check answers with a reason or with none: the three classes a run can end in live in switch_note_check, which reads the notes once with the turn cap's exemption and, when nothing is missing, once more without it. A note only that exemption hid was kept from the model by the cap, not by a missing note, so the incomplete class stays the cap's and every other missing note still fails the run. The test a_request_that_consumed_a_follow_up_without_its_note_is_unseen asserts the check's own answer again, as its text reads on main, and the tests added here read the three classes from switch_note_check. --- xtask/src/scenario_eval.rs | 163 +++++++++++++++++++------------------ 1 file changed, 82 insertions(+), 81 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index da48f11437..c45bc57027 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -6231,39 +6231,52 @@ enum NotesCheck { Observed, /// The run's turn cap stopped the note's request before its model call: /// the note was not at fault, and the probe has no request to read. - CapCut { - line: String, - }, + CapCut, /// The request never reached the model for another reason. Unseen(String), } /// The run's switch notes as the export shows them (Timeline branches §12.4). -/// A run that already failed is not checked. +/// A run that already failed is not checked. The notes are read once with the +/// turn cap's exemption; when nothing is missing, they are read again without +/// it: a note only the exemption hid was kept from the model by the cap, not +/// by a missing note, and the run is incomplete rather than scored +/// (issue #2140). fn switch_note_check(driven: &Driven, export: &str) -> NotesCheck { if driven.error.is_some() { return NotesCheck::Observed; } let cap_stop = (driven.stop == "turns").then(|| budget_stop_reason(driven.stop)); - switch_notes_unseen(export, &driven.switch_notes.expected, cap_stop.as_deref()) + let notes = &driven.switch_notes.expected; + if let Some(error) = switch_notes_unseen(export, notes, cap_stop.as_deref()) { + return NotesCheck::Unseen(error); + } + if cap_stop.is_some() && switch_notes_unseen(export, notes, None).is_some() { + return NotesCheck::CapCut; + } + NotesCheck::Observed } -/// Why a scored switch follow-up did not see its note, or [`NotesCheck::Observed`] -/// when every consumed follow-up's note reached the model: the first request -/// the line began after it consumed the input whose model call exists, and the -/// note's exact text (Timeline branches §12.4). An input no request consumed is -/// not checked: no answer of that line is scored. A request a steer replaced +/// Why a scored switch follow-up did not see its note, or `None` when every +/// consumed follow-up's note reached the model: the first request the line +/// began after it consumed the input whose model call exists, and the note's +/// exact text (Timeline branches §12.4). An input no request consumed is not +/// checked: no answer of that line is scored. A request a steer replaced /// before its model call is not checked either: the note travels in the /// request that replaces it in the same turn. A request the run's own -/// turn-budget stop ended, whose reason `cap_stop` carries, is -/// [`NotesCheck::CapCut`]: that stop, not the note, kept it from the model -/// (issue #2140), and the run is incomplete rather than scored. Every other -/// request that never reached the model is [`NotesCheck::Unseen`], because no +/// turn-budget stop ended, whose reason `cap_stop` carries, is not reported +/// either: that stop, not the note, kept it from the model (issue #2140), and +/// [`switch_note_check`] reads that shape by asking again without the stop. +/// Every other request that never reached the model is reported, because no /// request of the line carried the text being evaluated. A request whose /// `step/model-start` carries no turn id is exempted by neither: without the /// turn, neither the steer that replaced it nor the stop that ended it can be /// placed. -fn switch_notes_unseen(export: &str, notes: &[SwitchNote], cap_stop: Option<&str>) -> NotesCheck { +fn switch_notes_unseen( + export: &str, + notes: &[SwitchNote], + cap_stop: Option<&str>, +) -> Option { /// One `input/message` of the export, the line it is on, and the note it /// carries when it is one. struct Message { @@ -6386,10 +6399,9 @@ fn switch_notes_unseen(export: &str, notes: &[SwitchNote], cap_stop: Option<&str cut.insert((in_flight.branch.clone(), in_flight.request.clone())); } } - let mut cap_cut: Option = None; for note in notes { let Some(message) = messages.get(¬e.input) else { - return NotesCheck::Unseen(format!( + return Some(format!( "the switch input {} on line {} is not in the export", note.input, note.line )); @@ -6408,7 +6420,7 @@ fn switch_notes_unseen(export: &str, notes: &[SwitchNote], cap_stop: Option<&str .collect(); requests.sort_by_key(|start| start.sequence); let Some(first) = requests.first() else { - return NotesCheck::Unseen(format!( + return Some(format!( "line {} consumed the switch input {} but started no request after it", note.line, note.input )); @@ -6423,10 +6435,9 @@ fn switch_notes_unseen(export: &str, notes: &[SwitchNote], cap_stop: Option<&str // A steer can replace the request a line began before it reaches the // model; the note then travels in the request that replaces it, so a // replaced request is passed over (issue #2140). So is a request the - // run's turn budget stopped: the cap ended it, not the note. Any other - // request without a model call ended before the note reached the model. + // run's turn budget stopped: the cap ended it, not the note. let mut call = None; - let mut note_cap_cut = None; + let mut cap_cut = false; for start in &requests { let key = (start.branch.clone(), start.request.clone()); if let Some(found) = calls.get(&key) { @@ -6438,18 +6449,17 @@ fn switch_notes_unseen(export: &str, notes: &[SwitchNote], cap_stop: Option<&str continue; } if cut.contains(&key) { - note_cap_cut = Some(start.branch.clone()); + cap_cut = true; continue; } } break; } let Some(call) = call else { - if let Some(line) = note_cap_cut { - cap_cut.get_or_insert(line); + if cap_cut { continue; } - return NotesCheck::Unseen(format!( + return Some(format!( "line {} consumed the switch input {} but its request never reached the model", note.line, note.input )); @@ -6466,16 +6476,13 @@ fn switch_notes_unseen(export: &str, notes: &[SwitchNote], cap_stop: Option<&str .iter() .any(|text| request_carries(&call["messages"], text)) { - return NotesCheck::Unseen(format!( + return Some(format!( "the request that consumed the switch input on line {} does not carry the note it must answer under", note.line )); } } - match cap_cut { - Some(line) => NotesCheck::CapCut { line }, - None => NotesCheck::Observed, - } + None } /// Whether any string in `value` carries `needle`: a request is JSON, so a @@ -6492,8 +6499,9 @@ fn request_carries(value: &Value, needle: &str) -> bool { /// Why the run's fixture was never observed, when it was not: its own message /// and every request after the first idle must be consumed and followed by a /// model request on their line, and a scenario with that step must have run -/// it. A run its own budget stopped before such a request is incomplete, not a -/// losing candidate: the probe has no request to read (model-prompts §8.1). +/// it. [`incomplete_reason`] decides which stops make a run that never ran +/// such a request an incomplete fixture rather than a losing candidate: the +/// probe has no request to read (model-prompts §8.1). fn fixture_incomplete(driven: &Driven, scenario: &Scenario, export: &str) -> Option { if scenario.after_idle.is_some() && !driven @@ -6575,9 +6583,10 @@ fn incomplete_reason( return None; } fixture_incomplete(driven, scenario, export).or_else(|| match notes { - NotesCheck::CapCut { line } => Some(format!( - "line {line}: the switch follow-up's request was stopped by the run's turn budget before it reached the model" - )), + NotesCheck::CapCut => Some( + "the switch follow-up's request was stopped by the run's turn budget before it reached the model" + .to_owned(), + ), NotesCheck::Observed | NotesCheck::Unseen(_) => None, }) } @@ -9739,7 +9748,7 @@ mod tests { fn unseen_note(check: NotesCheck) -> Option { match check { NotesCheck::Unseen(error) => Some(error), - NotesCheck::Observed | NotesCheck::CapCut { .. } => None, + NotesCheck::Observed | NotesCheck::CapCut => None, } } fn metrics(scenario: &Scenario, records: &[RunRecord]) -> Metrics { @@ -10432,18 +10441,11 @@ mod tests { other: "main".into(), }]; assert!( - matches!( - switch_notes_unseen(&export(note), ¬es, None), - NotesCheck::Observed - ), + switch_notes_unseen(&export(note), ¬es, None).is_none(), "the request carries the note" ); - let unseen = unseen_note(switch_notes_unseen( - &export("the follow-up was answered"), - ¬es, - None, - )) - .expect("the request without the note is unseen"); + let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, None) + .expect("the request without the note is unseen"); assert!(unseen.contains("line 2"), "{unseen}"); } @@ -10493,18 +10495,11 @@ mod tests { other: "main".into(), }]; assert!( - matches!( - switch_notes_unseen(&export(note), ¬es, None), - NotesCheck::Observed - ), + switch_notes_unseen(&export(note), ¬es, None).is_none(), "the replacement request carries the note" ); - let unseen = unseen_note(switch_notes_unseen( - &export("the follow-up was answered"), - ¬es, - None, - )) - .expect("the request without the note is still unseen"); + let unseen = switch_notes_unseen(&export("the follow-up was answered"), ¬es, None) + .expect("the request without the note is still unseen"); assert!(unseen.contains("does not carry the note"), "{unseen}"); } @@ -10553,10 +10548,10 @@ mod tests { default: true, other: "main".into(), }]; - let unseen = unseen_note(switch_notes_unseen(&export(true), ¬es, None)) + let unseen = switch_notes_unseen(&export(true), ¬es, None) .expect("the closed request never reached the model"); assert!(unseen.contains("never reached the model"), "{unseen}"); - let unseen = unseen_note(switch_notes_unseen(&export(false), ¬es, None)) + let unseen = switch_notes_unseen(&export(false), ¬es, None) .expect("no request started after the consumption"); assert!(unseen.contains("started no request after it"), "{unseen}"); } @@ -10594,20 +10589,34 @@ mod tests { .map(|record| serde_json::to_string(record).unwrap()) .collect::>() .join("\n"); - let notes = [SwitchNote { + let switch_note = || SwitchNote { line: "2".into(), input: "f1".into(), default: true, other: "main".into(), - }]; + }; + let notes = [switch_note()]; + let driven = Driven { + session: "s".into(), + stop: "turns", + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes { + expected: vec![switch_note()], + }, + inputs: Vec::new(), + incomplete: None, + error: None, + }; assert!( - matches!( - switch_notes_unseen(&export, ¬es, Some("budget: turns")), - NotesCheck::CapCut { ref line } if line == "2" - ), + matches!(switch_note_check(&driven, &export), NotesCheck::CapCut), "the run's turn budget ended the request before its model call" ); - let unseen = unseen_note(switch_notes_unseen(&export, ¬es, None)) + let unseen = switch_notes_unseen(&export, ¬es, None) .expect("any other stop still reports the note"); assert!(unseen.contains("never reached the model"), "{unseen}"); } @@ -10724,7 +10733,7 @@ mod tests { other: "main".into(), }, ]; - let unseen = unseen_note(switch_notes_unseen(&export, ¬es, Some("budget: turns"))); + let unseen = switch_notes_unseen(&export, ¬es, Some("budget: turns")); assert!( unseen.as_deref().is_some_and( |error| error.contains("line 3") && error.contains("never reached the model") @@ -10796,12 +10805,8 @@ mod tests { json!({"turn_id": "t1", "status": "completed", "reason": "end_turn"}), ), ] { - let unseen = unseen_note(switch_notes_unseen( - &export(end), - ¬es, - Some("budget: turns"), - )) - .expect("a request that ended before the stop still needs its note"); + let unseen = switch_notes_unseen(&export(end), ¬es, Some("budget: turns")) + .expect("a request that ended before the stop still needs its note"); assert!(unseen.contains("never reached the model"), "{unseen}"); } } @@ -10850,7 +10855,7 @@ mod tests { .map(|record| serde_json::to_string(record).unwrap()) .collect::>() .join("\n"); - let unseen = unseen_note(switch_notes_unseen(&export, ¬es, Some("budget: turns"))) + let unseen = switch_notes_unseen(&export, ¬es, Some("budget: turns")) .expect("an unplaced request is not exempted by the stop"); assert!(unseen.contains("never reached the model"), "{unseen}"); } @@ -11074,15 +11079,11 @@ mod tests { incomplete: None, error: None, }; - let reason = incomplete_reason( - &driven, - &scenario(Vec::new()), - &export, - &NotesCheck::CapCut { line: "2".into() }, - ) - .unwrap(); + let reason = + incomplete_reason(&driven, &scenario(Vec::new()), &export, &NotesCheck::CapCut) + .unwrap(); assert!( - reason.contains("line 2") && reason.contains("turn budget"), + reason.contains("switch follow-up") && reason.contains("turn budget"), "{reason}" ); } From 98f53eaa43d2e7bf2e50dcb86969ea6752d2c5e1 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 10:35:35 +0800 Subject: [PATCH 21/25] fix(scenario-eval): compare only the runs with an outcome and read each fixture input in its turn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An incomplete fixture no longer enters the failed-run or unjudged-run denominator. The rates count the runs an arm had something to compare in — its judged, failed and unjudged runs — and the report states the arm's attempts and its incomplete fixtures beside them. FLOOR, delta and alpha stay as they were. Every input the runner submits keeps a receipt: the message, every request the step after the first idle submits, a switch's follow-up on either line, and a steer. One resolver reads what became of it: the turn its line consumed it in, the first model start after that consumption with no turn boundary in between, and that request's own model call or the call of a request that replaced it in the same turn. The fixture check and the switch-note check share it, so a later turn's request no longer answers for an input, and a switch follow-up the turn cap stopped before any consumption leaves an incomplete fixture. Both languages of model-prompts §8.1 state the denominator and what carries an input. New tests pin the resolver, the switch receipt and the report's denominator. --- docs/design/model-prompts.md | 2 +- docs/zh/design/model-prompts.md | 2 +- xtask/src/scenario_eval.rs | 896 +++++++++++++++++++++++--------- 3 files changed, 666 insertions(+), 234 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index d19ee951a9..8890c6e90f 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -163,7 +163,7 @@ A probe's rate counts judged, non-failed runs only, and failed runs are compared The last row is the rule's limit at the floor: catching that loss 80% of the time needs about 44–51 runs per scenario per arm. The report therefore prints both arms' counts, both rates, the loss, the p-value and the Holm threshold for every comparison, so a reader sees a loss the rule did not flag as well as one it did. The measured table resamples whole runs, which keeps each run's probes together. The pooled rows do not: they count each probe of each run as an observation, and the probes of one run share a transcript, so those p-values are optimistic. That errs toward rejecting, which means failing a candidate, and the per-probe rows compare one probe over whole runs. -**Failed and unjudged runs.** A failed run is one that ended on an error or its wall-clock budget, or one whose judging did not happen: there was nothing the judge could be asked, or a judge call failed — a window overflow, a transport or an HTTP error, or a reply cut off at its output cap. An unjudged run is one the judge answered but gave no usable verdicts for after two re-asks, or one whose view does not fit the judge's budget, which is never asked: it enters none of its arm's probe rates, and the report counts it and lists it with its reason; the unjudged-run rate compares it. A failed run is out of the probe rates too, and is compared once, as the failed-run rate. An incomplete run is one the harness's turn cap stopped before a request its probes read existed: the step after the first idle never ran, an input the runner submitted never reached the model, or the request a switch follow-up needed was stopped by the cap. A run its wall clock stopped is a failed run, not an incomplete one, and a run that ended idle is scored for the requests its export holds. It is neither a failed nor a judged run: it enters none of its arm's probe rates, does not count toward the floor, and the report lists it with its reason apart from the failed and unjudged runs, so a probe no request could answer is not read as the candidate's loss. A re-asked verdict comes from a longer conversation with the same judge at the same settings, and both arms are re-asked by the same rule. A run is judged through a view of its export: each request is given against the previous request of its line — the messages added since that request, or the whole message list after a history change — and every other field of the request appears in full only when it changed, or as an unchanged marker when it did not, so nothing is dropped. A request's consecutive `step/thinking` deltas are one line carrying their text in order, because a delta line is mostly an event id and field names and the judge reads the run as a whole. The judge reads the view in one call. A view that does not fit the judge's declared window — the window less the reply's `maxTokens` — is not split into parts: a probe that counts, orders or holds over a whole run cannot be answered from one part, so the run is unjudged before any call, and the report gives the estimate and the budget. The estimate is the runner's own and is taken before any call, so a predicted overflow is never asked. A call the provider refuses for a window overflow therefore means the declared window or the estimate was wrong, and it stays a failed run: a refusal is how a run outgrowing its model's real window shows up, and failed runs are compared between the arms. The scenario judge is asked for `present` or `absent`; the verdict parser the scenario and summary evaluations share also accepts `contradicted`, which a `must_not_show` probe treats as not shown. An evaluation whose judge declares no window fails before its first call. +**Failed and unjudged runs.** A failed run is one that ended on an error or its wall-clock budget, or one whose judging did not happen: there was nothing the judge could be asked, or a judge call failed — a window overflow, a transport or an HTTP error, or a reply cut off at its output cap. An unjudged run is one the judge answered but gave no usable verdicts for after two re-asks, or one whose view does not fit the judge's budget, which is never asked: it enters none of its arm's probe rates, and the report counts it and lists it with its reason; the unjudged-run rate compares it. A failed run is out of the probe rates too, and is compared once, as the failed-run rate. Those two rates count the runs an arm had something to compare in — its judged, failed and unjudged runs — and an incomplete fixture is not one of them: it lowers neither rate, and the report states the arm's attempts and its incomplete fixtures beside the rates. An incomplete run is one the harness's turn cap stopped before a request its probes read existed: the step after the first idle never ran, or an input the runner submitted — the message, a request that step submitted, a switch follow-up or a steer — was not carried by the request of the turn that consumed it. A request carries an input when nothing begins or ends a turn between the consumption and the request's `step/model-start`, and either the request's own model call exists or the call of a request that replaced it in the same turn does. A run its wall clock stopped is a failed run, not an incomplete one, and a run that ended idle is scored for the requests its export holds. An incomplete run is neither a failed nor a judged run: it enters none of its arm's probe rates, does not count toward the floor, and the report lists it with its reason apart from the failed and unjudged runs, so a probe no request could answer is not read as the candidate's loss. A re-asked verdict comes from a longer conversation with the same judge at the same settings, and both arms are re-asked by the same rule. A run is judged through a view of its export: each request is given against the previous request of its line — the messages added since that request, or the whole message list after a history change — and every other field of the request appears in full only when it changed, or as an unchanged marker when it did not, so nothing is dropped. A request's consecutive `step/thinking` deltas are one line carrying their text in order, because a delta line is mostly an event id and field names and the judge reads the run as a whole. The judge reads the view in one call. A view that does not fit the judge's declared window — the window less the reply's `maxTokens` — is not split into parts: a probe that counts, orders or holds over a whole run cannot be answered from one part, so the run is unjudged before any call, and the report gives the estimate and the budget. The estimate is the runner's own and is taken before any call, so a predicted overflow is never asked. A call the provider refuses for a window overflow therefore means the declared window or the estimate was wrong, and it stays a failed run: a refusal is how a run outgrowing its model's real window shows up, and failed runs are compared between the arms. The scenario judge is asked for `present` or `absent`; the verdict parser the scenario and summary evaluations share also accepts `contradicted`, which a `must_not_show` probe treats as not shown. An evaluation whose judge declares no window fails before its first call. **The candidate runs through the shipped assembly.** It is put in place at its author's factory configuration, as the summary strategy's optional system prompt member specified in [ContextCompaction §13.4](plugins/ContextCompaction.md#134-evaluation) allows a candidate prompt to replace the fixed one — the product profile never sets it — and never by patching strings in an evaluation-only path, so both arms run the shipped request building, chunking and failure handling. diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index 35b16a9ac4..c436215d77 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -163,7 +163,7 @@ 最后一行就是规则在下限处的极限:要以 80% 的概率发现它,每场景每臂需要约 44–51 次运行。因此报告为每个比较项打印两臂的计数、两个比率、落败、p 值与 Holm 阈值,读者既能看见规则标出的落败,也能看见它没有标出的落败。实测表按整次运行重采样,每次运行的探针因此保持在一起。汇总行不是:它把每次运行的每个探针算作一个观测,而同一次运行的探针共享一份对话记录,所以这些 p 值偏乐观。偏乐观的方向是多判回退,也就是多判候选失败;逐探针的行则是同一个探针跨整次运行比较。 -**失败运行与未判运行。** 失败运行是结束于错误或墙钟预算的那次运行,或者判分没有发生的那次:没有能交给判分模型的东西,或者判分调用失败——窗口溢出、传输错误或 HTTP 错误,或回复在输出上限处被截断。未判运行是判分模型回答了、但两次重问后仍给不出可用结论的那次运行,或者视图放不进判分模型预算、因此从未被询问的那次运行:它不计入所在臂的任何探针比率,报告会统计、连同原因一起列出它;未判运行率比较它。失败运行同样不在探针比率里,只比较一次,即失败运行率。不完整运行是 harness 的轮数上限在探针要读的请求出现之前就停下的那次运行:第一次 idle 之后的步骤没有跑、runner 提交的输入没有到达模型,或者 switch 动作的跟进请求被上限停掉;墙钟到点的运行是失败运行,不是不完整运行,idle 结束的运行按它导出里实际有的请求计分。它既不是失败运行也不是已判运行:不进所在臂的任何探针比率,不计入下限,报告会连同原因和失败、未判运行分开列出,因此没有任何请求可回答的探针不会被读成候选文本的损失。重问得到的结论来自同一个判分模型、同样设置下更长的一段对话,两臂按同一规则重问。一次运行的判分读的是它导出的一幅视图:每条请求对照同一行上前一次请求给出——自那次请求以来新增的消息,历史变化后则是整份消息列表——请求的其余字段只在变化时完整给出,未变化时读作未变化标记,因此不丢弃任何东西。同一请求连续的 `step/thinking` 增量渲染成一行,按顺序带上它们的文本:一行增量大部分是事件 id 和字段名,而判分模型读的是整次运行。判分模型一次调用读完这幅视图。视图放不进判分模型声明的窗口(扣除回复的 `maxTokens`)时不分部分判分:统计、排序或贯穿整次运行的探针无法从单独一部分回答,因此该运行在做出任何调用之前就是未判运行,报告给出估算与预算。估算由 runner 自己在调用前给出,因此预测的溢出从不被询问。因窗口溢出被提供方拒绝的调用则说明声明的窗口或估算有误,它仍是失败运行:拒绝是运行超出模型真实窗口的显现方式,而失败运行数在两臂之间比较。场景判分模型被要求回答 `present` 或 `absent`;场景评估与摘要评估共用的判定解析器也接受 `contradicted`,`must_not_show` 探针把它视为没有出现。判分模型没有声明窗口的评估在第一次调用之前就失败。 +**失败运行与未判运行。** 失败运行是结束于错误或墙钟预算的那次运行,或者判分没有发生的那次:没有能交给判分模型的东西,或者判分调用失败——窗口溢出、传输错误或 HTTP 错误,或回复在输出上限处被截断。未判运行是判分模型回答了、但两次重问后仍给不出可用结论的那次运行,或者视图放不进判分模型预算、因此从未被询问的那次运行:它不计入所在臂的任何探针比率,报告会统计、连同原因一起列出它;未判运行率比较它。失败运行同样不在探针比率里,只比较一次,即失败运行率。这两个比率的分母只数该臂有可比内容的运行——已判、失败与未判的运行——不完整夹具不是其中之一:它不让任何一个比率变低,报告在比率旁列出该臂的尝试次数和不完整夹具数。不完整运行是 harness 的轮数上限在探针要读的请求出现之前就停下的那次运行:第一次 idle 之后的步骤没有跑,或者 runner 提交的某个输入——场景消息、那一步提交的请求、switch 的跟进输入或一条 steer——没有被消费它的那个 turn 的请求带上。当消费与请求的 `step/model-start` 之间没有任何 turn 开始或结束,且该请求自己的 `model/call` 存在、或者同一 turn 内替换它的请求的 `model/call` 存在时,这个请求才算带上该输入。墙钟到点的运行是失败运行,不是不完整运行;idle 结束的运行按它导出里实际有的请求计分。不完整运行既不是失败运行也不是已判运行:不进所在臂的任何探针比率,不计入下限,报告会连同原因和失败、未判运行分开列出,因此没有任何请求可回答的探针不会被读成候选文本的损失。重问得到的结论来自同一个判分模型、同样设置下更长的一段对话,两臂按同一规则重问。一次运行的判分读的是它导出的一幅视图:每条请求对照同一行上前一次请求给出——自那次请求以来新增的消息,历史变化后则是整份消息列表——请求的其余字段只在变化时完整给出,未变化时读作未变化标记,因此不丢弃任何东西。同一请求连续的 `step/thinking` 增量渲染成一行,按顺序带上它们的文本:一行增量大部分是事件 id 和字段名,而判分模型读的是整次运行。判分模型一次调用读完这幅视图。视图放不进判分模型声明的窗口(扣除回复的 `maxTokens`)时不分部分判分:统计、排序或贯穿整次运行的探针无法从单独一部分回答,因此该运行在做出任何调用之前就是未判运行,报告给出估算与预算。估算由 runner 自己在调用前给出,因此预测的溢出从不被询问。因窗口溢出被提供方拒绝的调用则说明声明的窗口或估算有误,它仍是失败运行:拒绝是运行超出模型真实窗口的显现方式,而失败运行数在两臂之间比较。场景判分模型被要求回答 `present` 或 `absent`;场景评估与摘要评估共用的判定解析器也接受 `contradicted`,`must_not_show` 探针把它视为没有出现。判分模型没有声明窗口的评估在第一次调用之前就失败。 **候选走 shipped 装配。** 它放在作者的工厂配置里,就像摘要策略可选的 system prompt 成员([ContextCompaction §13.4](plugins/ContextCompaction.md#134-评估))让候选提示词替换固定那份——产品配置从不设置它——绝不在评估专用路径里改字符串;两臂因此跑的都是 shipped 的请求构建、分块与失败处理。 diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index c45bc57027..cc79a7b582 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -2388,10 +2388,13 @@ struct SwitchNote { /// The run's switch follow-ups and the notes they must follow: a move waits /// for each note before it submits the input its line answers, and the run is -/// not judged when a request consumed an input without its note. +/// not judged when a request consumed an input without its note. Every input +/// the move submitted is a receipt like the message's, whether or not its line +/// owes a note. #[derive(Default)] struct SwitchNotes { expected: Vec, + inputs: Vec, } /// The step a scenario runs after its first idle: every line that did not @@ -2407,9 +2410,9 @@ pub(crate) struct AfterIdle { } /// One input the runner submitted on the fixture's behalf. A run that its own -/// budget stopped before a request ran after the input was consumed did not -/// run the fixture its probe reads: it is incomplete, not scored -/// (model-prompts §8.1). +/// budget stopped before a request carried the input to the model did not run +/// the fixture its probe reads: it is incomplete, not scored (model-prompts +/// §8.1). struct FixtureInput { /// What the input is, named in the report when it was not observed. what: &'static str, @@ -2423,6 +2426,12 @@ struct FixtureInput { const MESSAGE_INPUT: &str = "the message"; /// One of the requests the step after the first idle submitted. const AFTER_IDLE_INPUT: &str = "the request after the idle"; +/// The input a move sends to the line it moved to. +const SWITCH_INPUT: &str = "the switch's follow-up"; +/// The input a move sends to the line it moved away from. +const FORMER_INPUT: &str = "the former line's request after the switch"; +/// A steer the fixture scheduled. +const STEER_INPUT: &str = "the steer"; /// One source a scenario declares through the `eventHub` service, and /// optionally subscribes its Session's `main` branch to (EventHub design A.1, @@ -6229,49 +6238,66 @@ fn budget_stop_reason(stop: &str) -> String { #[derive(Debug)] enum NotesCheck { Observed, - /// The run's turn cap stopped the note's request before its model call: - /// the note was not at fault, and the probe has no request to read. + /// The run's turn cap stopped a switch input before its model call: the + /// note was not at fault, and the probe has no request to read. CapCut, /// The request never reached the model for another reason. Unseen(String), } -/// The run's switch notes as the export shows them (Timeline branches §12.4). -/// A run that already failed is not checked. The notes are read once with the -/// turn cap's exemption; when nothing is missing, they are read again without -/// it: a note only the exemption hid was kept from the model by the cap, not -/// by a missing note, and the run is incomplete rather than scored -/// (issue #2140). +/// The run's switch inputs and notes as the export shows them (Timeline +/// branches §12.4). A run that already failed is not checked. Every input a +/// move submitted must be carried by the request of the turn that consumed it: +/// one the run's own turn cap stopped leaves the probe with no request to +/// read, and the run is an incomplete fixture rather than a missing note +/// (model-prompts §8.1, issue #2140). Every other input that never reached the +/// model fails the run as a missing note before the judge. The notes are then +/// read over the inputs that did reach the model. fn switch_note_check(driven: &Driven, export: &str) -> NotesCheck { if driven.error.is_some() { return NotesCheck::Observed; } let cap_stop = (driven.stop == "turns").then(|| budget_stop_reason(driven.stop)); - let notes = &driven.switch_notes.expected; - if let Some(error) = switch_notes_unseen(export, notes, cap_stop.as_deref()) { - return NotesCheck::Unseen(error); + for input in &driven.switch_notes.inputs { + let Some(id) = input.input.as_deref() else { + return NotesCheck::Unseen(format!( + "session.submit answered no input id for {}", + input.what + )); + }; + match carried_request(export, &input.line, id, cap_stop.as_deref()) { + Carried::Call(_) => {} + // An input no turn consumed is not checked: no answer of its line + // is scored. When the run stopped on its turn cap, that cap is + // what left it unobserved. + Carried::Unconsumed if cap_stop.is_some() => return NotesCheck::CapCut, + Carried::Unconsumed => {} + Carried::CapCut => return NotesCheck::CapCut, + Carried::Unreached => { + return NotesCheck::Unseen(format!( + "line {} consumed {} but its request never reached the model", + input.line, input.what + )); + } + } } - if cap_stop.is_some() && switch_notes_unseen(export, notes, None).is_some() { - return NotesCheck::CapCut; + match switch_notes_unseen(export, &driven.switch_notes.expected, cap_stop.as_deref()) { + Some(error) => NotesCheck::Unseen(error), + None => NotesCheck::Observed, } - NotesCheck::Observed } /// Why a scored switch follow-up did not see its note, or `None` when every -/// consumed follow-up's note reached the model: the first request the line -/// began after it consumed the input whose model call exists, and the note's -/// exact text (Timeline branches §12.4). An input no request consumed is not -/// checked: no answer of that line is scored. A request a steer replaced -/// before its model call is not checked either: the note travels in the -/// request that replaces it in the same turn. A request the run's own -/// turn-budget stop ended, whose reason `cap_stop` carries, is not reported -/// either: that stop, not the note, kept it from the model (issue #2140), and -/// [`switch_note_check`] reads that shape by asking again without the stop. -/// Every other request that never reached the model is reported, because no -/// request of the line carried the text being evaluated. A request whose -/// `step/model-start` carries no turn id is exempted by neither: without the -/// turn, neither the steer that replaced it nor the stop that ended it can be -/// placed. +/// consumed follow-up's note reached the model: the request +/// [`carried_request`] reads for the input, and the note's exact text +/// (Timeline branches §12.4). An input no request consumed is not checked: no +/// answer of that line is scored. A request a steer replaced before its model +/// call is not checked either: the note travels in the request that replaces +/// it in the same turn. A request the run's own turn-budget stop ended, whose +/// reason `cap_stop` carries, is not reported either: that stop, not the note, +/// kept it from the model (issue #2140). Every other request that never +/// reached the model is reported, because no request of the line carried the +/// text being evaluated. fn switch_notes_unseen( export: &str, notes: &[SwitchNote], @@ -6283,54 +6309,123 @@ fn switch_notes_unseen( branch: String, note: Option, } - /// One `step/model-start`: the request it began, and its line and turn. - /// `turn` is `None` when the start carries no turn id. + let mut messages: BTreeMap = BTreeMap::new(); + for line in export.lines() { + let Ok(record) = serde_json::from_str::(line) else { + continue; + }; + if record["kind"] != "event" { + continue; + } + let branch = record["branch_id"].as_str().unwrap_or_default().to_owned(); + let event = &record["event"]; + if (event["type"].as_str(), event["name"].as_str()) != (Some("input"), Some("message")) { + continue; + } + messages.insert( + event["id"].as_str().unwrap_or_default().to_owned(), + Message { + note: branch_line_note(event, &branch), + branch, + }, + ); + } + for note in notes { + let Some(message) = messages.get(¬e.input) else { + return Some(format!( + "the switch input {} on line {} is not in the export", + note.input, note.line + )); + }; + let call = match carried_request(export, &message.branch, ¬e.input, cap_stop) { + Carried::Unconsumed | Carried::CapCut => continue, + Carried::Unreached => { + return Some(format!( + "line {} consumed the switch input {} but its request never reached the model", + note.line, note.input + )); + } + Carried::Call(call) => call, + }; + let marker = note_marker(note.default, ¬e.other); + let texts: Vec<&str> = messages + .values() + .filter(|message| message.branch == note.line) + .filter_map(|message| message.note.as_ref()) + .filter(|seen| seen.default == note.default && seen.text.contains(&marker)) + .map(|seen| seen.text.as_str()) + .collect(); + if !texts + .iter() + .any(|text| request_carries(&call["messages"], text)) + { + return Some(format!( + "the request that consumed the switch input on line {} does not carry the note it must answer under", + note.line + )); + } + } + None +} + +/// What an export shows of one input the runner submitted: whether its line +/// consumed it, and the model call the request of that turn made (Timeline +/// branches §12.4, model-prompts §8.1). +#[derive(Debug)] +enum Carried { + /// The line never consumed the input, so no request of its own answers it. + Unconsumed, + /// The request that began after the consumption reached the model; its + /// call carries the request body. + Call(Value), + /// The run's own turn cap stopped that request before its model call, when + /// the caller names the cap's reason. + CapCut, + /// No request the consuming turn began reached the model. + Unreached, +} + +/// Reads one input the runner submitted from `export`: the turn its line +/// consumed it in, and the first `step/model-start` after that consumption +/// when no turn begins or ends in between. Only that request's own +/// `model/call` answers for the input, or the call of a request that replaced +/// it inside the same turn through `replaced by steer`. A start without a turn +/// id joins no other start's turn and replaces nothing. +fn carried_request(export: &str, branch: &str, input: &str, cap_stop: Option<&str>) -> Carried { + /// One `step/model-start` on the input's line. struct Start { - branch: String, turn: Option, sequence: u64, request: String, } - let mut messages: BTreeMap = BTreeMap::new(); - let mut consumed: Vec<(String, u64, String)> = Vec::new(); + let mut consumed_at: Option = None; + let mut turns: Vec = Vec::new(); let mut starts: Vec = Vec::new(); - let mut calls: BTreeMap<(String, String), Value> = BTreeMap::new(); - let mut replaced: BTreeSet<(String, String)> = BTreeSet::new(); - let mut cut: BTreeSet<(String, String)> = BTreeSet::new(); - let mut ended: BTreeMap<(String, String), u64> = BTreeMap::new(); - let mut ended_turns: BTreeMap<(String, String), u64> = BTreeMap::new(); - let mut interrupted: Vec<(String, u64)> = Vec::new(); + let mut calls: BTreeMap = BTreeMap::new(); + let mut replaced: BTreeSet = BTreeSet::new(); + let mut cut: BTreeSet = BTreeSet::new(); + let mut ended: BTreeMap = BTreeMap::new(); + let mut ended_turns: BTreeMap = BTreeMap::new(); + let mut interrupted: Vec = Vec::new(); for line in export.lines() { let Ok(record) = serde_json::from_str::(line) else { continue; }; - if record["kind"] != "event" { + if record["kind"] != "event" || record["branch_id"].as_str() != Some(branch) { continue; } - let branch = record["branch_id"].as_str().unwrap_or_default().to_owned(); let event = &record["event"]; let sequence = event["sequence"].as_u64().unwrap_or_default(); - let id = event["id"].as_str().unwrap_or_default().to_owned(); match (event["type"].as_str(), event["name"].as_str()) { - (Some("input"), Some("message")) => { - messages.insert( - id, - Message { - note: branch_line_note(event, &branch), - branch, - }, - ); - } (Some("input"), Some("consumed")) => { - if let Some(input) = event["data"]["input_id"].as_str() { - consumed.push((branch, sequence, input.to_owned())); + if event["data"]["input_id"].as_str() == Some(input) { + consumed_at = Some(consumed_at.map_or(sequence, |at| at.min(sequence))); } } (Some("step"), Some("model-start")) => { if let Some(request) = event["data"]["request_id"].as_str() { starts.push(Start { turn: event["data"]["turn_id"].as_str().map(str::to_owned), - branch, sequence, request: request.to_owned(), }); @@ -6338,31 +6433,30 @@ fn switch_notes_unseen( } (Some("model"), Some("call")) => { if let Some(request) = event["data"]["request_id"].as_str() { - calls.insert( - (branch, request.to_owned()), - event["data"]["request"].clone(), - ); + calls.insert(request.to_owned(), event["data"]["request"].clone()); } } (Some("step"), Some("model-output-end")) => { let reason = event["data"]["reason"].as_str().unwrap_or_default(); if let Some(request) = event["data"]["request_id"].as_str() { if event["data"]["status"] == "cancelled" && reason == "replaced by steer" { - replaced.insert((branch, request.to_owned())); + replaced.insert(request.to_owned()); } else if Some(reason) == cap_stop { - cut.insert((branch, request.to_owned())); + cut.insert(request.to_owned()); } else { ended - .entry((branch, request.to_owned())) + .entry(request.to_owned()) .and_modify(|at| *at = (*at).min(sequence)) .or_insert(sequence); } } } + (Some("turn"), Some("start")) => turns.push(sequence), (Some("turn"), Some("end")) => { + turns.push(sequence); if let Some(turn) = event["data"]["turn_id"].as_str() { ended_turns - .entry((branch, turn.to_owned())) + .entry(turn.to_owned()) .and_modify(|at| *at = (*at).min(sequence)) .or_insert(sequence); } @@ -6370,119 +6464,76 @@ fn switch_notes_unseen( (Some("stop"), Some("interrupt")) if cap_stop.is_some() && event["data"]["reason"].as_str() == cap_stop => { - interrupted.push((branch, sequence)); + interrupted.push(sequence); } _ => {} } } // The requests the run's own turn-budget stop ended: the one each of its - // interrupts found in flight on its line, and one whose own end names that + // interrupts found in flight on the line, and one whose own end names that // stop, which the Loop writes when the interrupt lands before the // request's `step/model-start`. A request that had already ended on its own // was not in flight when the interrupt landed, and the stop sends to every // line, idle ones included. - for (branch, at) in &interrupted { - if let Some(in_flight) = starts + for at in &interrupted { + if let Some(start) = starts .iter() - .filter(|start| &start.branch == branch && start.sequence < *at) + .filter(|start| start.sequence < *at) .filter(|start| { - let request = (start.branch.clone(), start.request.clone()); - let turn = start - .turn - .as_ref() - .map(|turn| (start.branch.clone(), turn.clone())); - !ended.get(&request).is_some_and(|end| end < at) - && !turn.is_some_and(|turn| ended_turns.get(&turn).is_some_and(|end| end < at)) + !ended.get(&start.request).is_some_and(|end| end < at) + && !start + .turn + .as_ref() + .is_some_and(|turn| ended_turns.get(turn).is_some_and(|end| end < at)) }) .max_by_key(|start| start.sequence) { - cut.insert((in_flight.branch.clone(), in_flight.request.clone())); + cut.insert(start.request.clone()); } } - for note in notes { - let Some(message) = messages.get(¬e.input) else { - return Some(format!( - "the switch input {} on line {} is not in the export", - note.input, note.line - )); + let Some(consumed_at) = consumed_at else { + return Carried::Unconsumed; + }; + let Some(first) = starts + .iter() + .filter(|start| start.sequence > consumed_at) + .min_by_key(|start| start.sequence) + else { + return Carried::Unreached; + }; + // The input belongs to the turn that consumed it: a turn boundary between + // the consumption and the first start means that start is another turn's. + if turns + .iter() + .any(|sequence| *sequence > consumed_at && *sequence < first.sequence) + { + return Carried::Unreached; + } + let mut request = first; + loop { + if let Some(call) = calls.get(&request.request) { + return Carried::Call(call.clone()); + } + let Some(turn) = request.turn.clone() else { + return Carried::Unreached; }; - let Some(consumed_at) = consumed + if !replaced.contains(&request.request) { + return if cap_stop.is_some() && cut.contains(&request.request) { + Carried::CapCut + } else { + Carried::Unreached + }; + } + let Some(next) = starts .iter() - .filter(|(branch, _, input)| branch == &message.branch && input == ¬e.input) - .map(|(_, sequence, _)| *sequence) - .min() + .filter(|start| start.sequence > request.sequence) + .filter(|start| start.turn.as_deref() == Some(turn.as_str())) + .min_by_key(|start| start.sequence) else { - continue; + return Carried::Unreached; }; - let mut requests: Vec<&Start> = starts - .iter() - .filter(|start| start.branch == message.branch && start.sequence > consumed_at) - .collect(); - requests.sort_by_key(|start| start.sequence); - let Some(first) = requests.first() else { - return Some(format!( - "line {} consumed the switch input {} but started no request after it", - note.line, note.input - )); - }; - // A steer replaces a request inside the turn that began it, so the - // requests that can answer for this note are that turn's own: a later - // turn's request carries the note as context and cannot stand in for a - // request that never reached the model. A start without a turn id - // joins no other start's turn, and the loop below exempts none of them. - let turn = first.turn.clone(); - requests.retain(|start| start.turn == turn); - // A steer can replace the request a line began before it reaches the - // model; the note then travels in the request that replaces it, so a - // replaced request is passed over (issue #2140). So is a request the - // run's turn budget stopped: the cap ended it, not the note. - let mut call = None; - let mut cap_cut = false; - for start in &requests { - let key = (start.branch.clone(), start.request.clone()); - if let Some(found) = calls.get(&key) { - call = Some(found); - break; - } - if start.turn.is_some() { - if replaced.contains(&key) { - continue; - } - if cut.contains(&key) { - cap_cut = true; - continue; - } - } - break; - } - let Some(call) = call else { - if cap_cut { - continue; - } - return Some(format!( - "line {} consumed the switch input {} but its request never reached the model", - note.line, note.input - )); - }; - let marker = note_marker(note.default, ¬e.other); - let texts: Vec<&str> = messages - .values() - .filter(|message| message.branch == note.line) - .filter_map(|message| message.note.as_ref()) - .filter(|seen| seen.default == note.default && seen.text.contains(&marker)) - .map(|seen| seen.text.as_str()) - .collect(); - if !texts - .iter() - .any(|text| request_carries(&call["messages"], text)) - { - return Some(format!( - "the request that consumed the switch input on line {} does not carry the note it must answer under", - note.line - )); - } + request = next; } - None } /// Whether any string in `value` carries `needle`: a request is JSON, so a @@ -6496,10 +6547,10 @@ fn request_carries(value: &Value, needle: &str) -> bool { } } -/// Why the run's fixture was never observed, when it was not: its own message -/// and every request after the first idle must be consumed and followed by a -/// model request on their line, and a scenario with that step must have run -/// it. [`incomplete_reason`] decides which stops make a run that never ran +/// Why the run's fixture was never observed, when it was not: every input the +/// runner submitted must be carried by the request of the turn its line +/// consumed it in, and a scenario with the step after the first idle must have +/// run it. [`incomplete_reason`] decides which stops make a run that never ran /// such a request an incomplete fixture rather than a losing candidate: the /// probe has no request to read (model-prompts §8.1). fn fixture_incomplete(driven: &Driven, scenario: &Scenario, export: &str) -> Option { @@ -6514,28 +6565,6 @@ fn fixture_incomplete(driven: &Driven, scenario: &Scenario, export: &str) -> Opt driven.stop )); } - let mut consumed: Vec<(String, u64, String)> = Vec::new(); - let mut calls: Vec<(String, u64)> = Vec::new(); - for line in export.lines() { - let Ok(record) = serde_json::from_str::(line) else { - continue; - }; - if record["kind"] != "event" { - continue; - } - let event = &record["event"]; - let branch = record["branch_id"].as_str().unwrap_or_default().to_owned(); - let sequence = event["sequence"].as_u64().unwrap_or_default(); - match (event["type"].as_str(), event["name"].as_str()) { - (Some("input"), Some("consumed")) => { - if let Some(input) = event["data"]["input_id"].as_str() { - consumed.push((branch, sequence, input.to_owned())); - } - } - (Some("model"), Some("call")) => calls.push((branch, sequence)), - _ => {} - } - } for input in &driven.inputs { let Some(id) = input.input.as_deref() else { return Some(format!( @@ -6543,25 +6572,20 @@ fn fixture_incomplete(driven: &Driven, scenario: &Scenario, export: &str) -> Opt input.line, input.what )); }; - let Some(consumed_at) = consumed - .iter() - .filter(|(branch, _, seen)| branch == &input.line && seen == id) - .map(|(_, sequence, _)| *sequence) - .min() - else { - return Some(format!( - "line {}: {} was never consumed before the run stopped on {}", - input.line, input.what, driven.stop - )); - }; - if !calls - .iter() - .any(|(branch, sequence)| branch == &input.line && *sequence > consumed_at) - { - return Some(format!( - "line {}: no request ran after {} before the run stopped on {}", - input.line, input.what, driven.stop - )); + match carried_request(export, &input.line, id, None) { + Carried::Call(_) => {} + Carried::Unconsumed => { + return Some(format!( + "line {}: {} was never consumed before the run stopped on {}", + input.line, input.what, driven.stop + )); + } + Carried::CapCut | Carried::Unreached => { + return Some(format!( + "line {}: no request carried {} to the model before the run stopped on {}", + input.line, input.what, driven.stop + )); + } } } None @@ -6584,7 +6608,7 @@ fn incomplete_reason( } fixture_incomplete(driven, scenario, export).or_else(|| match notes { NotesCheck::CapCut => Some( - "the switch follow-up's request was stopped by the run's turn budget before it reached the model" + "the run's turn budget stopped the run before the switch follow-up reached the model" .to_owned(), ), NotesCheck::Observed | NotesCheck::Unseen(_) => None, @@ -6946,7 +6970,16 @@ async fn drive( // The idle requests the quiet check keeps outstanding, one per line. let mut calls = IdleCalls::default(); loop { - match fire_due(client, &session, &mut steers, started).await { + match fire_due( + client, + &session, + &mut steers, + &default, + &mut driven.inputs, + started, + ) + .await + { Ok(submitted) => awaiting |= submitted, Err(error) => { driven.stop = "error"; @@ -7199,7 +7232,16 @@ async fn drive( if let Some(pending) = switches.front_mut() { pending.notice(&branch, &event); } - match fire_triggered(client, &session, &mut steers, &event).await { + match fire_triggered( + client, + &session, + &mut steers, + &default, + &mut driven.inputs, + &event, + ) + .await + { Ok(submitted) => awaiting |= submitted, Err(error) => { driven.stop = "error"; @@ -8403,6 +8445,11 @@ async fn send_switch_follow_ups( let input = receipt.clone().ok_or_else(|| { format!("session.submit answered no input id for the switch to {target}") })?; + gate.inputs.push(FixtureInput { + what: SWITCH_INPUT, + line: message_line.clone(), + input: Some(input.clone()), + }); for (line, default, other) in &wanted { if *line == message_line { gate.expected.push(SwitchNote { @@ -8416,18 +8463,23 @@ async fn send_switch_follow_ups( } if let Some(message) = pending.switch.former_message.as_deref() { let receipt = submit(client, session, message, None, Some(former.as_str())).await?; - if let Some(gate) = notes.as_mut() - && former != "main" - { + if let Some(gate) = notes.as_mut() { let input = receipt.ok_or_else(|| { format!("session.submit answered no input id for the switch to {target}") })?; - gate.expected.push(SwitchNote { + gate.inputs.push(FixtureInput { + what: FORMER_INPUT, line: former.clone(), - input, - default: false, - other: target.clone(), + input: Some(input.clone()), }); + if former != "main" { + gate.expected.push(SwitchNote { + line: former.clone(), + input, + default: false, + other: target.clone(), + }); + } } } if let Some(next) = switches.front_mut() { @@ -8436,11 +8488,15 @@ async fn send_switch_follow_ups( Ok(SwitchFire::Fired) } -/// Sends the timed steers that are due, and whether it sent one. +/// Sends the timed steers that are due, and whether it sent one. A steer is a +/// fixture input: its receipt names the line the Session's default branch was +/// when it was sent. async fn fire_due( client: &mut Client, session: &str, steers: &mut [(Steer, bool)], + line: &str, + inputs: &mut Vec, started: Instant, ) -> std::result::Result { let mut sent = false; @@ -8450,7 +8506,13 @@ async fn fire_due( .is_some_and(|after| started.elapsed().as_secs_f64() >= after); if due && !*fired { *fired = true; - let _ = submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; + let receipt = + submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; + inputs.push(FixtureInput { + what: STEER_INPUT, + line: line.to_owned(), + input: receipt, + }); sent = true; } } @@ -8463,6 +8525,8 @@ async fn fire_triggered( client: &mut Client, session: &str, steers: &mut [(Steer, bool)], + line: &str, + inputs: &mut Vec, event: &Value, ) -> std::result::Result { if event["type"] != "step" || event["name"] != "tool-use" { @@ -8477,7 +8541,13 @@ async fn fire_triggered( .is_some_and(|trigger| data.contains(trigger.as_str())); if triggered && !*fired { *fired = true; - let _ = submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; + let receipt = + submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; + inputs.push(FixtureInput { + what: STEER_INPUT, + line: line.to_owned(), + input: receipt, + }); sent = true; } } @@ -9074,7 +9144,9 @@ struct ProbeCounts { /// The arm's metrics over its scenarios and runs (model-prompts §8.1). An /// unjudged or failed run adds nothing to the probe rates; the arm counts it -/// in its own rate. +/// in its own rate. An incomplete fixture is compared with neither: it is +/// reported apart, and its arm's rates are read over the runs it attempted +/// that had something to compare. #[derive(Default)] struct Metrics { /// `(scenario, probe)` → its counted runs and the passes among them. @@ -9088,15 +9160,22 @@ struct Metrics { /// Runs the judge gave no answer to, that did not fail on their own, /// left out of every other count. unjudged: u32, - /// Every run of the arm, failed and unjudged included. + /// The runs the arm's rates are computed over: judged, failed and unjudged. runs: u32, + /// Every run the arm attempted, the incomplete fixtures included. + attempted: u32, + /// Runs the harness's turn cap stopped before the request its probe reads + /// existed, left out of `runs` (model-prompts §8.1). + incomplete: u32, } impl Metrics { fn add(&mut self, scenario: &Scenario, record: &RunRecord) { - self.runs += 1; + self.attempted += 1; if record.incomplete.is_some() { + self.incomplete += 1; return; } + self.runs += 1; if record.unjudged() { self.unjudged += 1; return; @@ -9371,6 +9450,9 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] }; metrics.entry(record.arm).or_default().add(scenario, record); } + let empty = Metrics::default(); + let current = metrics.get("current").unwrap_or(&empty); + let candidate = metrics.get("candidate").unwrap_or(&empty); let window = instrument.judge_window.map_or_else(String::new, |window| { format!( ", window {}, max output {}", @@ -9427,6 +9509,13 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] carried(&instrument.judge_configuration), instrument.runs, ); + // The rates quote the runs with something to compare; the arm's attempts + // and the fixtures its own turn cap left unobserved are reported beside + // them, and enter no rate (model-prompts §8.1). + text += &format!( + "| attempted runs | current {}, candidate {} |\n| incomplete fixtures | current {}, candidate {} |\n", + current.attempted, candidate.attempted, current.incomplete, candidate.incomplete, + ); if instrument.sources.is_none() { let tokens: Vec = instrument .tokens @@ -9495,9 +9584,6 @@ fn report(instrument: &Instrument, scenarios: &[Scenario], records: &[RunRecord] ); text.push('\n'); } - let empty = Metrics::default(); - let current = metrics.get("current").unwrap_or(&empty); - let candidate = metrics.get("candidate").unwrap_or(&empty); // The fewest judged runs an arm ran a scenario: the floor the verdict // needs. Failed and unjudged runs are compared in their own rows and do // not count here, because they enter no probe rate (model-prompts §8.1). @@ -10553,7 +10639,7 @@ mod tests { assert!(unseen.contains("never reached the model"), "{unseen}"); let unseen = switch_notes_unseen(&export(false), ¬es, None) .expect("no request started after the consumption"); - assert!(unseen.contains("started no request after it"), "{unseen}"); + assert!(unseen.contains("never reached the model"), "{unseen}"); } /// A run that stopped on its turn budget ended the request before its @@ -10607,6 +10693,11 @@ mod tests { switch_retries: 0, switch_notes: SwitchNotes { expected: vec![switch_note()], + inputs: vec![FixtureInput { + what: SWITCH_INPUT, + line: "2".into(), + input: Some("f1".into()), + }], }, inputs: Vec::new(), incomplete: None, @@ -10905,6 +10996,7 @@ mod tests { default: true, other: "main".into(), }], + inputs: Vec::new(), }, inputs: Vec::new(), incomplete: None, @@ -10957,7 +11049,18 @@ mod tests { json!({"user": {"content": "message"}}), ), event("main", 2, ["input", "consumed"], json!({"input_id": "m1"})), - event("main", 3, ["model", "call"], json!({"request": {}})), + event( + "main", + 3, + ["step", "model-start"], + json!({"turn_id": "t1", "request_id": "r1"}), + ), + event( + "main", + 4, + ["model", "call"], + json!({"request_id": "r1", "request": {}}), + ), ] .join("\n"); let reason = fixture_incomplete(&driven, &scenario, &export).unwrap(); @@ -10974,20 +11077,31 @@ mod tests { let consumed = [ event( "main", - 4, + 6, ["input", "message"], json!({"user": {"content": "Re-run the tests."}}), ), - event("main", 5, ["input", "consumed"], json!({"input_id": "f1"})), + event("main", 7, ["input", "consumed"], json!({"input_id": "f1"})), ] .join("\n"); let reason = fixture_incomplete(&driven, &scenario, &format!("{export}\n{consumed}")).unwrap(); - assert!(reason.contains("no request ran after"), "{reason}"); + assert!(reason.contains("no request carried"), "{reason}"); let after = [ consumed.clone(), - event("main", 6, ["model", "call"], json!({"request": {}})), + event( + "main", + 8, + ["step", "model-start"], + json!({"turn_id": "t2", "request_id": "r2"}), + ), + event( + "main", + 9, + ["model", "call"], + json!({"request_id": "r2", "request": {}}), + ), ] .join("\n"); assert_eq!( @@ -11058,7 +11172,16 @@ mod tests { json!({"user": {"content": "message"}}), ), event(2, ["input", "consumed"], json!({"input_id": "m1"})), - event(3, ["model", "call"], json!({"request": {}})), + event( + 3, + ["step", "model-start"], + json!({"turn_id": "t1", "request_id": "r1"}), + ), + event( + 4, + ["model", "call"], + json!({"request_id": "r1", "request": {}}), + ), ] .join("\n"); let driven = Driven { @@ -11088,6 +11211,211 @@ mod tests { ); } + /// An input belongs to the turn that consumed it: a later turn's request + /// does not carry it, a call with no `step/model-start` is no request, and + /// a request a steer replaced inside the same turn answers for it + /// (model-prompts §8.1). + #[test] + fn a_fixture_input_is_carried_only_by_the_request_of_its_turn() { + let event = |sequence: u64, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": "main", + "event": {"id": format!("e{sequence}"), "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + .to_string() + }; + let driven = Driven { + session: "s".into(), + stop: "turns", + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes::default(), + inputs: vec![FixtureInput { + what: MESSAGE_INPUT, + line: "main".into(), + input: Some("m1".into()), + }], + incomplete: None, + error: None, + }; + let scenario = scenario(vec![probe("identity", ProbeKind::MustShow)]); + let message: Vec = vec![ + event( + 1, + ["input", "message"], + json!({"user": {"content": "message"}}), + ), + event(2, ["input", "consumed"], json!({"input_id": "m1"})), + ]; + let mut later_turn = message.clone(); + later_turn.extend([ + event( + 3, + ["turn", "end"], + json!({"turn_id": "t1", "status": "cancelled", "reason": "end_turn"}), + ), + event(4, ["turn", "start"], json!({"turn_id": "t2"})), + event( + 5, + ["step", "model-start"], + json!({"turn_id": "t2", "request_id": "r2"}), + ), + event( + 6, + ["model", "call"], + json!({"request_id": "r2", "request": {}}), + ), + ]); + assert!( + fixture_incomplete(&driven, &scenario, &later_turn.join("\n")) + .is_some_and(|reason| reason.contains("no request carried")), + "a later turn's request does not carry the input" + ); + let mut call_only = message.clone(); + call_only.push(event( + 3, + ["model", "call"], + json!({"request_id": "r1", "request": {}}), + )); + assert!( + fixture_incomplete(&driven, &scenario, &call_only.join("\n")).is_some(), + "a call with no request start did not carry the input" + ); + let mut replaced = message.clone(); + replaced.extend([ + event( + 3, + ["step", "model-start"], + json!({"turn_id": "t1", "request_id": "r1"}), + ), + event( + 4, + ["step", "model-output-end"], + json!({"turn_id": "t1", "request_id": "r1", "status": "cancelled", + "reason": "replaced by steer"}), + ), + event( + 5, + ["step", "model-start"], + json!({"turn_id": "t1", "request_id": "r2"}), + ), + event( + 6, + ["model", "call"], + json!({"request_id": "r2", "request": {}}), + ), + ]); + assert_eq!( + fixture_incomplete(&driven, &scenario, &replaced.join("\n")), + None, + "the request that replaced it in the same turn carries the input" + ); + } + + /// A switch follow-up the run's turn cap stopped before any turn consumed + /// it leaves the probe with no request to read: the run is an incomplete + /// fixture, not a scored answer, and a run that ended idle keeps the + /// scoring it had (model-prompts §8.1). + #[test] + fn a_switch_follow_up_no_turn_consumed_is_an_incomplete_fixture() { + let export = json!({"kind": "event", "branch_id": "2", + "event": {"id": "e1", "sequence": 1, "type": "model", "name": "call", + "data": {"request_id": "r1", "request": {}}}}) + .to_string(); + let driven = |stop: &'static str| Driven { + session: "s".into(), + stop, + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes { + expected: Vec::new(), + inputs: vec![FixtureInput { + what: SWITCH_INPUT, + line: "2".into(), + input: Some("f1".into()), + }], + }, + inputs: Vec::new(), + incomplete: None, + error: None, + }; + assert!( + matches!( + switch_note_check(&driven("turns"), &export), + NotesCheck::CapCut + ), + "the turn cap left the follow-up unobserved" + ); + assert!( + matches!( + switch_note_check(&driven("idle"), &export), + NotesCheck::Observed + ), + "an input no turn consumed is not checked on an idle run" + ); + } + + /// A switch input belongs to the turn its line consumed it in: a request a + /// later turn began does not answer for it, even when it carries the note + /// (Timeline branches §12.4). + #[test] + fn a_later_turn_does_not_answer_for_a_switch_input() { + let note = "\nswitched from line main.\n"; + let event = |sequence: u64, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": "2", + "event": {"id": format!("e{sequence}"), "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + .to_string() + }; + let export = [ + event( + 1, + ["input", "message"], + json!({"blocks": [{"type": "raw", "key": "branch:line", "text": note}]}), + ), + event(2, ["input", "message"], json!({})), + event(3, ["input", "consumed"], json!({"input_id": "e2"})), + event( + 4, + ["turn", "end"], + json!({"turn_id": "t1", "status": "cancelled", "reason": "end_turn"}), + ), + event(5, ["turn", "start"], json!({"turn_id": "t2"})), + event( + 6, + ["step", "model-start"], + json!({"turn_id": "t2", "request_id": "r2"}), + ), + event( + 7, + ["model", "call"], + json!({"request_id": "r2", + "request": {"messages": [{"role": "user", "content": note}]}}), + ), + ] + .join("\n"); + let notes = [SwitchNote { + line: "2".into(), + input: "e2".into(), + default: true, + other: "main".into(), + }]; + let unseen = switch_notes_unseen(&export, ¬es, None); + assert!( + unseen + .as_deref() + .is_some_and(|error| error.contains("never reached the model")), + "a later turn does not answer for the input: {unseen:?}" + ); + } + /// A run that ended idle is scored as it was before the incomplete class /// existed: the stop is the product's state, not the harness's turn cap, /// so an input it left unrun is the candidate's outcome, not a fixture @@ -11145,7 +11473,7 @@ mod tests { let no_request = [message_event, consumed].join("\n"); assert!( fixture_incomplete(&driven("turns"), &scenario, &no_request) - .is_some_and(|reason| reason.contains("no request ran after")), + .is_some_and(|reason| reason.contains("no request carried")), "the consumed input without a request is what the fixture check reads" ); assert_eq!( @@ -11262,6 +11590,58 @@ mod tests { ); } + /// Every follow-up a move sends keeps a receipt: the input on the line its + /// message went to and the one on the line it left, the root included. A + /// run whose turn cap stops a follow-up before a turn consumes it has no + /// request to score (model-prompts §8.1). + #[tokio::test] + async fn a_move_keeps_a_receipt_for_each_follow_up_it_sends() { + let turn_start = json!({"type": "turn", "name": "start", "data": {}}); + let switch = Switch { + to: SwitchTarget::Id("2".into()), + message: "to the tool line".into(), + branch_id: Some("main".into()), + former_message: Some("report to the user".into()), + }; + let mut switches: VecDeque = + [PendingSwitch::new(switch, None, false)].into(); + let mut default = "main".to_owned(); + let mut client = SwitchRecorder { + inputs: ["i1".to_owned(), "i2".to_owned()].into(), + ..SwitchRecorder::default() + }; + let mut notes = SwitchNotes::default(); + switches + .front_mut() + .expect("the move is pending") + .notice("2", &turn_start); + assert!( + matches!( + fire_switch( + &mut client, + "session", + &mut switches, + &mut default, + None, + Some(&mut notes) + ) + .await, + Ok(SwitchFire::Fired) + ), + "the move fires" + ); + let received: Vec<(&str, &str)> = notes + .inputs + .iter() + .map(|input| (input.what, input.line.as_str())) + .collect(); + assert_eq!( + received, + [(SWITCH_INPUT, "main"), (FORMER_INPUT, "main")], + "both follow-ups keep their receipt, on the line they went to" + ); + } + /// The switch's calls, recorded, and the refusals its /// `session.branch_set_default` calls answer, in order; no Session stands /// behind it. @@ -13183,6 +13563,50 @@ mod tests { assert_eq!(failed.candidate, Counts::new(1, 21)); } + /// An incomplete fixture is not compared: the failed-run and unjudged-run + /// rates count the judged, failed and unjudged runs, and the report states + /// the arm's attempts and its incomplete fixtures beside them + /// (model-prompts §8.1). + #[test] + fn the_report_counts_an_incomplete_fixture_apart_from_the_compared_runs() { + let scenario = scenario(vec![probe("reports", ProbeKind::MustShow)]); + let mut records = arm(&scenario, "current", 1, 1); + records.extend(arm(&scenario, "candidate", 1, 1)); + for arm in ["current", "candidate"] { + let mut incomplete = record( + arm, + &scenario, + &[("reports", ProbeVerdict::Unparsed)], + JudgeOutcome::Unobserved, + ); + incomplete.stop = "turns"; + incomplete.incomplete = + Some("the run stopped on turns before the step after the first idle".into()); + records.push(incomplete); + } + let text = report( + &instrument(model()), + std::slice::from_ref(&scenario), + &records, + ); + assert!( + text.contains("| case/reports (must_show) | 1/1 (1.000) | 1/1 (1.000) |"), + "the probe counts only the judged run: {text}" + ); + assert!( + text.contains("| failed runs | 0/1 (0.000) | 0/1 (0.000) |"), + "the incomplete fixture is not in the failed-run denominator: {text}" + ); + assert!( + text.contains("| attempted runs | current 2, candidate 2 |"), + "the report counts the attempt: {text}" + ); + assert!( + text.contains("| incomplete fixtures | current 1, candidate 1 |"), + "the report counts the incomplete fixture apart: {text}" + ); + } + /// A candidate that violates a `must_not_show` probe more often fails /// through the probe's row and the pooled row beside it, and the report /// prints both arms' counts (model-prompts §8.1). @@ -15873,8 +16297,16 @@ mod tests { "the probe counts no run in either arm: {report}" ); assert!( - report.contains("| failed runs | 0/1 (0.000) | 0/1 (0.000) |"), - "an incomplete run is not a failed run: {report}" + report.contains("| attempted runs | current 1, candidate 1 |"), + "the report counts the attempt: {report}" + ); + assert!( + report.contains("| incomplete fixtures | current 1, candidate 1 |"), + "the report counts the incomplete fixture apart: {report}" + ); + assert!( + report.contains("| failed runs | – | – |"), + "an incomplete run leaves the failed-run comparison: {report}" ); } From e8bcde4b583d6db50309660a1207d4c5dff865b7 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 11:23:26 +0800 Subject: [PATCH 22/25] test(scenario-eval): pin a steer receipt and an unseen switch input The timed steer and the tool-triggered steer each keep a receipt: a test reads the input id the Session answers and the line the runner sent it from through the same fake the switch tests use, so the reading needs no live Session. A consumed switch input whose request never reached the model is unseen on the root line too, which owes no note: a test reads that outcome from the check before the judge. --- xtask/src/scenario_eval.rs | 145 ++++++++++++++++++++++++++++++++++++- 1 file changed, 143 insertions(+), 2 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index cc79a7b582..d8cb35ca5b 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -8492,7 +8492,7 @@ async fn send_switch_follow_ups( /// fixture input: its receipt names the line the Session's default branch was /// when it was sent. async fn fire_due( - client: &mut Client, + client: &mut impl SwitchClient, session: &str, steers: &mut [(Steer, bool)], line: &str, @@ -8522,7 +8522,7 @@ async fn fire_due( /// Sends the event-triggered steers whose substring the notice's /// `step/tool-use` event carries, and whether it sent one. async fn fire_triggered( - client: &mut Client, + client: &mut impl SwitchClient, session: &str, steers: &mut [(Steer, bool)], line: &str, @@ -11362,6 +11362,65 @@ mod tests { ); } + /// A switch input the line consumed, whose request never reached the model + /// for any reason other than the run's turn cap, fails the run before the + /// judge: no request of the consuming turn carried the input, on the root + /// line that owes no note as on any other (Timeline branches §12.4, + /// model-prompts §8.1). + #[test] + fn a_consumed_switch_input_whose_request_never_reached_the_model_is_unseen() { + let event = |sequence: u64, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": "main", + "event": {"id": format!("e{sequence}"), "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + .to_string() + }; + let export = [ + event(1, ["input", "message"], json!({})), + event(2, ["input", "consumed"], json!({"input_id": "f1"})), + event( + 3, + ["step", "model-start"], + json!({"turn_id": "t1", "request_id": "r1"}), + ), + event( + 4, + ["step", "model-output-end"], + json!({"turn_id": "t1", "request_id": "r1", "status": "cancelled", + "reason": "timeline closed"}), + ), + ] + .join("\n"); + let driven = Driven { + session: "s".into(), + stop: "idle", + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes { + expected: Vec::new(), + inputs: vec![FixtureInput { + what: FORMER_INPUT, + line: "main".into(), + input: Some("f1".into()), + }], + }, + inputs: Vec::new(), + incomplete: None, + error: None, + }; + let unseen = unseen_note(switch_note_check(&driven, &export)) + .expect("the request that consumed the input never reached the model"); + assert!( + unseen.contains("line main consumed the former line's request after the switch"), + "{unseen}" + ); + assert!(unseen.contains("never reached the model"), "{unseen}"); + } + /// A switch input belongs to the turn its line consumed it in: a request a /// later turn began does not answer for it, even when it carries the note /// (Timeline branches §12.4). @@ -11642,6 +11701,88 @@ mod tests { ); } + /// A steer the fixture submits keeps a receipt: the input the Session + /// answered, on the line the runner sent it from, whether it was due on + /// the clock or triggered by a tool call (model-prompts §8.1). + #[tokio::test] + async fn a_sent_steer_keeps_a_receipt_on_the_line_it_went_to() { + let mut steers = vec![ + ( + Steer { + after_seconds: Some(0.1), + when_tool_call: None, + text: "timed".into(), + }, + false, + ), + ( + Steer { + after_seconds: None, + when_tool_call: Some("read".into()), + text: "triggered".into(), + }, + false, + ), + ]; + let mut inputs = Vec::new(); + let mut client = SwitchRecorder { + inputs: ["s1".to_owned(), "s2".to_owned()].into(), + ..SwitchRecorder::default() + }; + let started = Instant::now() - Duration::from_secs(1); + assert!( + fire_due( + &mut client, + "session", + &mut steers, + "main", + &mut inputs, + started + ) + .await + .expect("the timed steer is sent"), + "the timed steer is due" + ); + let event = json!({"type": "step", "name": "tool-use", + "data": {"name": "read", "arguments": {"path": "parser/expr.py"}}}); + assert!( + fire_triggered( + &mut client, + "session", + &mut steers, + "line-2", + &mut inputs, + &event + ) + .await + .expect("the triggered steer is sent"), + "the tool call triggers the steer" + ); + let received: Vec<(&str, &str, Option<&str>)> = inputs + .iter() + .map(|input| (input.what, input.line.as_str(), input.input.as_deref())) + .collect(); + assert_eq!( + received, + [ + (STEER_INPUT, "main", Some("s1")), + (STEER_INPUT, "line-2", Some("s2")), + ], + "each steer keeps the line the runner sent it from and the id the Session answered" + ); + assert_eq!( + client.methods(), + ["session.submit", "session.submit"], + "a steer is one submission" + ); + assert!( + client.calls.iter().all(|(_, params)| { + params["mode"] == "steer" && params.get("branchId").is_none() + }), + "a steer goes to the default branch and names no line" + ); + } + /// The switch's calls, recorded, and the refusals its /// `session.branch_set_default` calls answer, in order; no Session stands /// behind it. From 74874fa6ee9f5466597248187d04b95857263708 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 13:38:15 +0800 Subject: [PATCH 23/25] test(scenario-eval): pin the cap-cut precedence over a confirmed failure The tests read a run's record through the note check, the incomplete reason and the metrics: a receipt the turn cap cut must not hide another receipt that reached the model without its note, or a later receipt whose request never reached the model. Both cases assert the run is a failed run in gate 1, not an incomplete fixture. --- xtask/src/scenario_eval.rs | 350 +++++++++++++++++++++++++++++++++++++ 1 file changed, 350 insertions(+) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index d8cb35ca5b..9d3fef278f 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -11475,6 +11475,356 @@ mod tests { ); } + /// The outcome a run's record takes from its note check and its incomplete + /// reason, in the order the runner reads them (model-prompts §8.1): a note + /// check that finds an unseen request fails the run before the judge, and + /// only a run without one is an incomplete fixture. + fn scored_switch_run(driven: &Driven, export: &str) -> (NotesCheck, Option, Metrics) { + let scenario = scenario(Vec::new()); + let check = switch_note_check(driven, export); + let mut stop = driven.stop; + let mut error = driven.error.clone(); + let mut incomplete = None; + let judge = if let NotesCheck::Unseen(message) = &check { + stop = "switch_note_missing"; + error = Some(message.clone()); + JudgeOutcome::NotAsked + } else { + incomplete = incomplete_reason(driven, &scenario, export, &check); + if incomplete.is_some() { + JudgeOutcome::NotAsked + } else { + JudgeOutcome::Judged + } + }; + let mut record = record("current", &scenario, &[], judge); + record.stop = stop; + record.failed = failed(stop, error.as_deref(), judge); + record.incomplete = incomplete.clone(); + let mut metrics = Metrics::default(); + metrics.add(&scenario, &record); + (check, incomplete, metrics) + } + + /// A run whose receipt the turn cap left unobserved still fails on every + /// confirmed failure it shows, and enters gate 1's failed runs rather than + /// the report's incomplete fixtures (model-prompts §8.1). + fn assert_confirmed_failure( + case: &str, + check: &NotesCheck, + incomplete: &Option, + metrics: &Metrics, + needle: &str, + ) { + match check { + NotesCheck::Unseen(error) => { + assert!(error.contains(needle), "{case}: {error}"); + } + NotesCheck::Observed | NotesCheck::CapCut => { + panic!( + "{case}: the receipt the cap cut hid the failure this run confirms: {check:?}" + ) + } + } + assert_eq!( + incomplete, &None, + "{case}: a confirmed failure is not an incomplete fixture" + ); + assert_eq!( + ( + metrics.attempted, + metrics.runs, + metrics.failed, + metrics.incomplete + ), + (1, 1, 1, 0), + "{case}: a confirmed failure enters gate 1's failed runs, not its incomplete fixtures" + ); + } + + /// A receipt the run's turn cap left unobserved does not hide another + /// receipt that reached the model without its note, whether the missing + /// note came before or after the cap-cut one (Timeline branches §12.4, + /// model-prompts §8.1). + #[test] + fn a_cap_cut_receipt_does_not_hide_a_request_that_reached_the_model_without_its_note() { + let note = "\nswitched from line main.\n"; + let event = |branch: &str, sequence: u64, id: &str, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": branch, + "event": {"id": id, "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + }; + let missing_note = || -> Vec { + vec![ + event( + "2", + 1, + "n2", + ["input", "message"], + json!({"blocks": [{"type": "raw", "key": "branch:line", "text": note}]}), + ), + event("2", 2, "f2", ["input", "message"], json!({})), + event( + "2", + 3, + "c2", + ["input", "consumed"], + json!({"input_id": "f2"}), + ), + event( + "2", + 4, + "s2", + ["step", "model-start"], + json!({"turn_id": "t2", "request_id": "r2"}), + ), + event( + "2", + 5, + "m2", + ["model", "call"], + json!({"request_id": "r2", + "request": {"messages": [{"role": "user", + "content": "the follow-up was answered"}]}}), + ), + ] + }; + let cap_cut = || -> Vec { + vec![ + event("3", 1, "f3", ["input", "message"], json!({})), + event( + "3", + 2, + "c3", + ["input", "consumed"], + json!({"input_id": "f3"}), + ), + event( + "3", + 3, + "s3", + ["step", "model-start"], + json!({"turn_id": "t3", "request_id": "r3"}), + ), + event( + "3", + 4, + "i3", + ["stop", "interrupt"], + json!({"reason": "budget: turns", "scope": "turn"}), + ), + event( + "3", + 5, + "o3", + ["step", "model-output-end"], + json!({"turn_id": "t3", "request_id": "r3", "status": "cancelled", + "reason": "budget: turns"}), + ), + ] + }; + let unconsumed = || -> Vec { + vec![ + event("3", 1, "f3", ["input", "message"], json!({})), + event( + "3", + 2, + "s3", + ["step", "model-start"], + json!({"turn_id": "t3", "request_id": "r3"}), + ), + ] + }; + let receipt = |line: &str, input: &str| FixtureInput { + what: SWITCH_INPUT, + line: line.into(), + input: Some(input.into()), + }; + let driven = |inputs: Vec| Driven { + session: "s".into(), + stop: "turns", + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes { + expected: vec![SwitchNote { + line: "2".into(), + input: "f2".into(), + default: true, + other: "main".into(), + }], + inputs, + }, + inputs: Vec::new(), + incomplete: None, + error: None, + }; + let cases = [ + ( + "the missing note's receipt first", + vec![receipt("2", "f2"), receipt("3", "f3")], + [missing_note(), cap_cut()].concat(), + ), + ( + "the cap-cut receipt first", + vec![receipt("3", "f3"), receipt("2", "f2")], + [cap_cut(), missing_note()].concat(), + ), + ( + "the cap left the other receipt unconsumed", + vec![receipt("2", "f2"), receipt("3", "f3")], + [missing_note(), unconsumed()].concat(), + ), + ]; + for (case, inputs, export) in cases { + let export = export + .iter() + .map(|event| serde_json::to_string(event).unwrap()) + .collect::>() + .join("\n"); + let (check, incomplete, metrics) = scored_switch_run(&driven(inputs), &export); + assert_confirmed_failure( + case, + &check, + &incomplete, + &metrics, + "does not carry the note", + ); + } + } + + /// A receipt the run's turn cap left unobserved does not hide a later + /// receipt whose request never reached the model, whether that later + /// receipt is on another line or on the root (Timeline branches §12.4, + /// model-prompts §8.1). + #[test] + fn a_cap_cut_receipt_does_not_hide_a_later_request_that_never_reached_the_model() { + let event = |branch: &str, sequence: u64, id: &str, kind: [&str; 2], data: Value| { + json!({"kind": "event", "branch_id": branch, + "event": {"id": id, "sequence": sequence, + "type": kind[0], "name": kind[1], "data": data}}) + }; + let cap_cut = || -> Vec { + vec![ + event("2", 1, "f2", ["input", "message"], json!({})), + event( + "2", + 2, + "c2", + ["input", "consumed"], + json!({"input_id": "f2"}), + ), + event( + "2", + 3, + "s2", + ["step", "model-start"], + json!({"turn_id": "t2", "request_id": "r2"}), + ), + event( + "2", + 4, + "i2", + ["stop", "interrupt"], + json!({"reason": "budget: turns", "scope": "turn"}), + ), + event( + "2", + 5, + "o2", + ["step", "model-output-end"], + json!({"turn_id": "t2", "request_id": "r2", "status": "cancelled", + "reason": "budget: turns"}), + ), + ] + }; + let unconsumed = + || -> Vec { vec![event("2", 1, "f2", ["input", "message"], json!({}))] }; + let unreached = |branch: &str| -> Vec { + vec![ + event(branch, 1, "u1", ["input", "message"], json!({})), + event( + branch, + 2, + "u2", + ["input", "consumed"], + json!({"input_id": "u1"}), + ), + event( + branch, + 3, + "u3", + ["turn", "end"], + json!({"turn_id": "tu", "status": "cancelled", "reason": "end_turn"}), + ), + event( + branch, + 4, + "u4", + ["step", "model-start"], + json!({"turn_id": "t4", "request_id": "r4"}), + ), + ] + }; + let receipt = |line: &str, input: &str| FixtureInput { + what: SWITCH_INPUT, + line: line.into(), + input: Some(input.into()), + }; + let driven = |inputs: Vec| Driven { + session: "s".into(), + stop: "turns", + timed_out: false, + cleanup_deadline: None, + turns: 1, + window: None, + decline_retries: 0, + switch_retries: 0, + switch_notes: SwitchNotes { + expected: Vec::new(), + inputs, + }, + inputs: Vec::new(), + incomplete: None, + error: None, + }; + let cases = [ + ( + "a later request on another line never reached the model", + vec![receipt("2", "f2"), receipt("3", "u1")], + [cap_cut(), unreached("3")].concat(), + ), + ( + "a later request on the root never reached the model", + vec![receipt("2", "f2"), receipt("main", "u1")], + [cap_cut(), unreached("main")].concat(), + ), + ( + "the cap left the first receipt unconsumed", + vec![receipt("2", "f2"), receipt("3", "u1")], + [unconsumed(), unreached("3")].concat(), + ), + ]; + for (case, inputs, export) in cases { + let export = export + .iter() + .map(|event| serde_json::to_string(event).unwrap()) + .collect::>() + .join("\n"); + let (check, incomplete, metrics) = scored_switch_run(&driven(inputs), &export); + assert_confirmed_failure( + case, + &check, + &incomplete, + &metrics, + "never reached the model", + ); + } + } + /// A run that ended idle is scored as it was before the incomplete class /// existed: the stop is the product's state, not the harness's turn cap, /// so an input it left unrun is the candidate's outcome, not a fixture From 12477bbc2e9177c5f18634fb637b39c4562b2884 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 13:50:34 +0800 Subject: [PATCH 24/25] fix(scenario-eval): report a confirmed switch-note failure before the turn cap A run can carry one receipt the turn cap cut and another that reached the model without its note, or one whose request never reached the model. The check reads every receipt and the notes before it reports the cap, so a confirmed failure fails the run and enters gate 1's failed runs instead of leaving the report as an incomplete fixture. Only a run with no confirmed failure is an incomplete fixture. --- xtask/src/scenario_eval.rs | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 9d3fef278f..18e035fcaf 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -6247,17 +6247,20 @@ enum NotesCheck { /// The run's switch inputs and notes as the export shows them (Timeline /// branches §12.4). A run that already failed is not checked. Every input a -/// move submitted must be carried by the request of the turn that consumed it: -/// one the run's own turn cap stopped leaves the probe with no request to -/// read, and the run is an incomplete fixture rather than a missing note -/// (model-prompts §8.1, issue #2140). Every other input that never reached the -/// model fails the run as a missing note before the judge. The notes are then -/// read over the inputs that did reach the model. +/// move submitted must be carried by the request of the turn that consumed it, +/// and every note is read over the inputs that did reach the model. A request +/// that never reached the model fails the run as a missing note, and so does +/// one that reached it without its note. A receipt the run's own turn cap +/// stopped, or no turn consumed, leaves the probe with no request to read, but +/// the check reads every receipt and note before it reports that cap: the run +/// is an incomplete fixture rather than a missing note only when no receipt or +/// note confirms a failure (model-prompts §8.1, issue #2140). fn switch_note_check(driven: &Driven, export: &str) -> NotesCheck { if driven.error.is_some() { return NotesCheck::Observed; } let cap_stop = (driven.stop == "turns").then(|| budget_stop_reason(driven.stop)); + let mut cap_cut = false; for input in &driven.switch_notes.inputs { let Some(id) = input.input.as_deref() else { return NotesCheck::Unseen(format!( @@ -6268,11 +6271,12 @@ fn switch_note_check(driven: &Driven, export: &str) -> NotesCheck { match carried_request(export, &input.line, id, cap_stop.as_deref()) { Carried::Call(_) => {} // An input no turn consumed is not checked: no answer of its line - // is scored. When the run stopped on its turn cap, that cap is - // what left it unobserved. - Carried::Unconsumed if cap_stop.is_some() => return NotesCheck::CapCut, + // is scored. When the run stopped on its turn cap, that cap is what + // left it unobserved, and the run is incomplete only if no other + // receipt or note confirms a failure. + Carried::Unconsumed if cap_stop.is_some() => cap_cut = true, Carried::Unconsumed => {} - Carried::CapCut => return NotesCheck::CapCut, + Carried::CapCut => cap_cut = true, Carried::Unreached => { return NotesCheck::Unseen(format!( "line {} consumed {} but its request never reached the model", @@ -6283,6 +6287,7 @@ fn switch_note_check(driven: &Driven, export: &str) -> NotesCheck { } match switch_notes_unseen(export, &driven.switch_notes.expected, cap_stop.as_deref()) { Some(error) => NotesCheck::Unseen(error), + None if cap_cut => NotesCheck::CapCut, None => NotesCheck::Observed, } } From 646b3e5b295b95b0014d3e682d4deede85f399a9 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 14:10:50 +0800 Subject: [PATCH 25/25] test(scenario-eval): pin an unconsumed receipt before a missing note The turn cap can leave an earlier receipt unconsumed and a later one consumed, its request at the model without the note. The note check reads every receipt before it reports the cap, so that missing note still fails the run. --- xtask/src/scenario_eval.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 18e035fcaf..805cbcfd54 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -11683,6 +11683,11 @@ mod tests { vec![receipt("2", "f2"), receipt("3", "f3")], [missing_note(), unconsumed()].concat(), ), + ( + "the cap left the earlier receipt unconsumed", + vec![receipt("3", "f3"), receipt("2", "f2")], + [unconsumed(), missing_note()].concat(), + ), ]; for (case, inputs, export) in cases { let export = export