From 98de513f1b793e31c720d56ae135c9951d4b50eb Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 01:18:43 +0800 Subject: [PATCH 01/32] feat(xtask): switch the default branch in a scenario run A scenario may name a switch: the line to move to, by the latest tool line or by id, and the input to send afterwards. The runner calls session.branch_set_default after the target line's first turn/end and then submits the input, which names a line only when the scenario does. session.submit no longer pins branchId to main, so an input after a switch reaches the default branch. A scenario without a switch runs as before. The runner's two new unit tests cover the switch step and an input that names no line. --- docs/design/model-prompts.md | 1 + docs/zh/design/model-prompts.md | 1 + xtask/src/scenario_eval.rs | 366 ++++++++++++++++++++++++++++++-- 3 files changed, 348 insertions(+), 20 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index ceef1fa105..244b21a50d 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -252,6 +252,7 @@ SessionTitle is out of scope: its `SYSTEM` (`crates/dim-session-title/src/lib.rs **Owner:** the evaluation tooling, `xtask`; implemented under [#550](https://github.com/arcships/dim/issues/550). - **A scenario runner** with the candidate injection and the test of §8.1: the scenarios are the cases, both arms run the shipped assembly, and the result is reported in the pull request. It interleaves the arms run by run and accepts `--jobs` and repeated `--text`/`--candidate` pairs, so a change that spans two texts of one owner is judged as the one change it is (Goal §A.5.2). +- **A scenario may move the default branch mid-run.** Its `switch` step names the target line, by role (`latest_tool_line`) or id, and the runner calls `session.branch_set_default` after that line's first `turn/end` before sending the next input; an input that names no line lands on the default branch, and one that names a line keeps that target. - **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources, has no text or candidate-token row, and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. - **A run's file roots.** Each live run serves with three kinds of file-tool root: its workspace, which the model may read and write; its disposable home, which `~` resolves against and which the model may read; and the platform's fixed read-only roots, which carry the toolchain the run's commands read, such as the interpreter's own installation. A file-tool path outside them is refused with `outside_file_roots`, and the refusal leaves what is outside untouched. The roots bound the model's file-tool calls — `read`, `write`, `edit`, `glob` and `grep`; `exec` is bounded by the sandbox, and the client-initiated paths, `@` mention expansion and the App Server's `session.files.*` methods, are not calls the model makes and stay outside the roots. - **No absolute pass line and no CI run** (§8.1). diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index 1a9552fd83..2db306606d 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -251,6 +251,7 @@ SessionTitle 不在范围内:它的 `SYSTEM`(`crates/dim-session-title/src/l **所有者:** 评估工具,`xtask`;在 [#550](https://github.com/arcships/dim/issues/550) 下实现。 - **一个场景运行器**,带 §8.1 的候选注入与检验:场景即用例,两臂都跑 shipped 装配,结果写进 PR。它逐次交错两臂,并接受 `--jobs` 与重复的 `--text`/`--candidate` 对,因此一个跨同一所有者两段文本的改动按它本来就是的一次改动来判定(Goal §A.5.2)。 +- **场景可以在运行中途移动默认分支。** `switch` 步骤按角色(`latest_tool_line`)或 id 指定目标线;运行器在那条线第一次 `turn/end` 之后、发下一条输入之前调用 `session.branch_set_default`。不点名线的输入落到默认分支,点名线的输入仍以那个目标为准。 - **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告会列出它的来源,没有 text 行与 candidate-token 行;合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。 - **一次运行的文件根。** 每个 isolate 运行都以三类文件工具根提供服务:工作区,模型可读可写;一次性 home,`~` 解析到它,模型可读;以及平台固定的只读根,承载运行的命令要读取的工具链,例如解释器自身的安装目录。文件工具路径落在这些根之外时以 `outside_file_roots` 拒绝,且拒绝不触碰根外的任何内容。这些根约束模型的文件工具调用——`read`、`write`、`edit`、`glob`、`grep`;`exec` 由沙箱约束,而客户端发起的路径(`@` 提及展开与 App Server 的 `session.files.*` 方法)不是模型发起的调用,不在根内。 - **不用绝对通过线,不进 CI**(§8.1)。 diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index ee6aaf7649..29efcf5322 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -1666,9 +1666,85 @@ struct ScenarioFile { events: Vec, #[serde(default)] steers: Vec, + /// The mid-run move of the default branch, when the scenario runs one. + #[serde(default)] + switch: Option, budget: Budget, probes: Vec, } + +/// A scenario's mid-run move of the Session's default branch: after the +/// target line's first `turn/end`, the runner calls +/// `session.branch_set_default` and then sends the next input. A scenario +/// without the step runs as before. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Switch { + /// The line to move to. + pub(crate) to: SwitchTarget, + /// The input sent after the move. It carries no mode and is queued, like + /// the operator's first message. + pub(crate) message: String, + /// The line the next input names. Omitted, the input lands on the line + /// that just became the default branch; `main` names the root after a + /// switch. + #[serde(default)] + pub(crate) branch_id: Option, +} + +/// The line a [`Switch`] moves to, by role or by id. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) enum SwitchTarget { + Role(SwitchRole), + Id(String), +} + +/// The role a [`SwitchTarget`] names. A tool line is a line the branch tool +/// opened; the latest one is the line most recently opened that way. +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum SwitchRole { + LatestToolLine, +} + +/// A [`Switch`] as the run drives it: the target the role currently names, +/// kept current while the switch is pending. +struct PendingSwitch { + switch: Switch, + line: Option, +} +impl PendingSwitch { + fn new(switch: Switch) -> Self { + let line = match &switch.to { + SwitchTarget::Id(id) => Some(id.clone()), + SwitchTarget::Role(_) => None, + }; + Self { switch, line } + } + + /// Reads one notice: a tool `branch/create` renames the role's target, and + /// the target's first `turn/end` is when the move and the next input + /// happen. + fn notice(&mut self, branch: &str, event: &Value) -> Option { + if event["type"] == "branch" && event["name"] == "create" { + if matches!( + &self.switch.to, + SwitchTarget::Role(SwitchRole::LatestToolLine) + ) && event["data"]["source"]["kind"] == "tool" + && let Some(line) = event["data"]["branch"].as_str() + { + self.line = Some(line.to_owned()); + } + return None; + } + if event["type"] == "turn" && event["name"] == "end" && self.line.as_deref() == Some(branch) + { + return Some(branch.to_owned()); + } + None + } +} /// 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 @@ -1798,6 +1874,9 @@ pub(crate) struct Scenario { pub(crate) sources: Vec, pub(crate) events: Vec, pub(crate) steers: Vec, + /// The mid-run move of the default branch, when the scenario runs one. + #[serde(default)] + pub(crate) switch: Option, pub(crate) budget: Budget, probes: Vec, } @@ -1862,6 +1941,23 @@ fn into_scenario( } } } + if let Some(switch) = &raw.switch { + if switch.message.trim().is_empty() { + return Err("a switch needs the input to send after the move".into()); + } + if let SwitchTarget::Id(id) = &switch.to + && id.trim().is_empty() + { + return Err("a switch target id is empty".into()); + } + if switch + .branch_id + .as_deref() + .is_some_and(|branch| branch.trim().is_empty()) + { + return Err("a switch names an empty branch for its input".into()); + } + } for call in &raw.calls { if call.method.trim().is_empty() { return Err("a call needs a method".into()); @@ -1979,6 +2075,7 @@ fn into_scenario( sources: raw.sources, events: raw.events, steers: raw.steers, + switch: raw.switch, budget: raw.budget, probes: raw.probes, }) @@ -2823,7 +2920,7 @@ async fn product_probe( .rpc("session.attach", json!({"sessionId": probe})) .await .map_err(|error| format!("session.attach failed: {error}"))?; - submit(client, &probe, "PRODUCT-TOOLS\n", None) + submit(client, &probe, "PRODUCT-TOOLS\n", None, None) .await .map_err(|error| error.to_string())?; loop { @@ -2986,7 +3083,7 @@ async fn preflight_session( .rpc("session.attach", json!({"sessionId": session})) .await .map_err(|error| (Vec::new(), format!("session.attach failed: {error}")))?; - submit(client, &session, &message, None) + submit(client, &session, &message, None, None) .await .map_err(|error| (Vec::new(), error))?; // The tool results in arrival order: the scripted steps run one per @@ -4674,7 +4771,7 @@ async fn drive( return driven; } } - if let Err(error) = submit(client, &session, &scenario.message, None).await { + if let Err(error) = submit(client, &session, &scenario.message, None, None).await { driven.stop = "error"; driven.error = Some(error); return driven; @@ -4687,6 +4784,7 @@ async fn drive( .cloned() .map(|steer| (steer, false)) .collect(); + let mut switch = scenario.switch.clone().map(PendingSwitch::new); let mut last_event = Instant::now(); // The events still to publish, and whether each was. let mut events: Vec<(EventSpec, bool)> = scenario @@ -4813,6 +4911,14 @@ async fn drive( return driven; } } + match fire_switch(client, &session, &mut switch, &branch, &event).await { + Ok(submitted) => awaiting |= submitted, + Err(error) => { + driven.stop = "error"; + driven.error = Some(error); + return driven; + } + } match fire_triggered(client, &session, &mut steers, &event).await { Ok(submitted) => awaiting |= submitted, Err(error) => { @@ -5731,11 +5837,22 @@ async fn fire_events_after_subscribe( Ok((published, starts)) } -/// The `session.submit` params. A mode names how `main` takes the input: a -/// steer ends a wait and replaces a request that has produced no output yet, -/// while the operator's first message carries no mode and is queued. -fn submit_params(session: &str, text: &str, mode: Option) -> Value { - let mut params = json!({"sessionId": session, "branchId": "main", "text": text}); +/// The `session.submit` params. A mode names how the target line takes the +/// input: a steer ends a wait and replaces a request that has produced no +/// output yet, while the operator's first message carries no mode and is +/// queued. A call that names no `branchId` lands on the Session's default +/// branch (design §9, §14), which is what a scenario after a switch wants; a +/// scenario that names a line passes it here. +fn submit_params( + session: &str, + text: &str, + mode: Option, + branch: Option<&str>, +) -> Value { + let mut params = json!({"sessionId": session, "text": text}); + if let Some(branch) = branch { + params["branchId"] = json!(branch); + } if let Some(mode) = mode { params["mode"] = json!(mode); } @@ -5747,14 +5864,51 @@ async fn submit( session: &str, text: &str, mode: Option, + branch: Option<&str>, ) -> std::result::Result<(), String> { client - .rpc("session.submit", submit_params(session, text, mode)) + .rpc("session.submit", submit_params(session, text, mode, branch)) .await .map(|_| ()) .map_err(|error| format!("session.submit failed: {error}")) } +/// Runs the scenario's switch when this notice is the target line's first +/// `turn/end`, and whether it sent the input after the move: the Session's +/// default branch moves first, then the next input is submitted, naming a +/// line only when the scenario does. +async fn fire_switch( + client: &mut Client, + session: &str, + switch: &mut Option, + branch: &str, + event: &Value, +) -> std::result::Result { + let Some(pending) = switch.as_mut() else { + return Ok(false); + }; + let Some(line) = pending.notice(branch, event) else { + return Ok(false); + }; + let pending = switch.take().expect("the switch is pending"); + client + .rpc( + "session.branch_set_default", + json!({"sessionId": session, "branchId": line}), + ) + .await + .map_err(|error| format!("the switch to {line} failed: {error}"))?; + submit( + client, + session, + &pending.switch.message, + None, + pending.switch.branch_id.as_deref(), + ) + .await?; + Ok(true) +} + /// Sends the timed steers that are due, and whether it sent one. async fn fire_due( client: &mut Client, @@ -5769,7 +5923,7 @@ async fn fire_due( .is_some_and(|after| started.elapsed().as_secs_f64() >= after); if due && !*fired { *fired = true; - submit(client, session, &steer.text, Some(InputMode::Steer)).await?; + submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; sent = true; } } @@ -5796,7 +5950,7 @@ async fn fire_triggered( .is_some_and(|trigger| data.contains(trigger.as_str())); if triggered && !*fired { *fired = true; - submit(client, session, &steer.text, Some(InputMode::Steer)).await?; + submit(client, session, &steer.text, Some(InputMode::Steer), None).await?; sent = true; } } @@ -6818,6 +6972,7 @@ mod tests { sources: Vec::new(), events: Vec::new(), steers: Vec::new(), + switch: None, budget: Budget { turns: 4, seconds: 60., @@ -7004,28 +7159,128 @@ mod tests { } /// A scenario's steers are the operator's: they go out in Steer mode, so - /// a waiting `main` takes them, and the initial message carries no mode - /// and is queued input (issue #728). + /// a waiting line takes them, and the initial message carries no mode and + /// is queued input (issue #728). Neither names a line: an input without + /// `branchId` lands on the Session's default branch, which is the line a + /// steer after a switch reaches. #[test] fn a_steer_is_submitted_in_steer_mode_and_the_message_without_one() { - let params = submit_params("session", "go", None); + let params = submit_params("session", "go", None, None); assert!(params.get("mode").is_none(), "{params}"); + assert!(params.get("branchId").is_none(), "{params}"); let message: dim_app_server::protocol::Submit = serde_json::from_value(params).expect("the first message is a Submit"); assert_eq!(message.text.as_deref(), Some("go")); assert_eq!(message.mode, None); - let params = submit_params("session", "also", Some(InputMode::Steer)); + assert_eq!(message.branch_id, None); + let params = submit_params("session", "also", Some(InputMode::Steer), Some("main")); let steer: dim_app_server::protocol::Submit = serde_json::from_value(params).expect("a steer is a Submit"); assert_eq!(steer.text.as_deref(), Some("also")); assert_eq!(steer.mode, Some(InputMode::Steer)); + assert_eq!(steer.branch_id.as_deref(), Some("main")); + } + + /// A switch names the line to move to by role or by id, and the input + /// after the move; the runner moves the default branch after the target + /// line's first `turn/end` (Timeline branches §12.3). + #[test] + fn a_switch_step_names_a_line_and_its_next_input() { + let directory = + std::env::temp_dir().join(format!("dim-scenario-eval-switch-{}", std::process::id())); + std::fs::create_dir_all(directory.join("workspace")).unwrap(); + let parse = |switch: Value| { + let file: ScenarioFile = serde_json::from_value(json!({ + "message": "first", + "switch": switch, + "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 scenario = parse(json!({ + "to": {"role": "latest_tool_line"}, + "message": "second" + })) + .unwrap(); + let switch = scenario.switch.expect("the scenario switches"); + assert!(matches!( + switch.to, + SwitchTarget::Role(SwitchRole::LatestToolLine) + )); + assert_eq!(switch.message, "second"); + assert_eq!(switch.branch_id, None); + let scenario = parse(json!({ + "to": {"id": "3"}, + "message": "second", + "branchId": "main" + })) + .unwrap(); + let switch = scenario.switch.expect("the scenario switches"); + assert!(matches!(&switch.to, SwitchTarget::Id(id) if id == "3")); + assert_eq!(switch.branch_id.as_deref(), Some("main")); + assert!( + parse(json!({"to": {"role": "latest_tool_line"}, "message": " "})).is_err(), + "a switch needs the input to send after the move" + ); + assert!( + parse(json!({"to": {"id": ""}, "message": "second"})).is_err(), + "a switch target id is not empty" + ); + let _ = std::fs::remove_dir_all(&directory); + } + + /// The move's trigger is the target line's first `turn/end`: a tool + /// `branch/create` names the role's latest line, and another line's turn + /// does not fire it. The run drops the switch after the move, so one + /// scenario switches once. + #[test] + fn a_switch_fires_on_the_target_lines_first_turn_end() { + let turn_end = json!({"type": "turn", "name": "end", "data": {}}); + let create = |branch: &str, kind: &str| { + json!({"type": "branch", "name": "create", + "data": {"branch": branch, "source": {"kind": kind}}}) + }; + let mut pending = PendingSwitch::new(Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "next".into(), + branch_id: None, + }); + assert_eq!(pending.notice("main", &turn_end), None); + assert_eq!(pending.notice("main", &create("2", "tool")), None); + assert_eq!(pending.notice("2", &turn_end), Some("2".into())); + let mut pending = PendingSwitch::new(Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "next".into(), + branch_id: None, + }); + pending.notice("main", &create("2", "tool")); + assert_eq!( + pending.notice("3", &turn_end), + None, + "another line's turn ends no switch" + ); + pending.notice("main", &create("3", "user")); + assert_eq!( + pending.notice("3", &turn_end), + None, + "a line the user opened is not a tool line" + ); + let mut pending = PendingSwitch::new(Switch { + to: SwitchTarget::Id("4".into()), + message: "next".into(), + branch_id: None, + }); + assert_eq!(pending.notice("4", &turn_end), Some("4".into())); } - /// The committed set parses through the runner's own reader, and the two - /// pairs that share a premise stay equal: the compact scenario reuses - /// `redone-work`'s message and workspace, and `flooding` and - /// `never-ending` share one workspace (Timeline branches §12.3). No model - /// runs, so CI catches a schema, layout or pair drift before a manual run. + /// The committed set parses through the runner's own reader, its two + /// switch scenarios carry the move, and the two pairs that share a + /// premise stay equal: the compact scenario reuses `redone-work`'s + /// message and workspace, and `flooding` and `never-ending` share one + /// workspace (Timeline branches §12.3). No model runs, so CI catches a + /// schema, layout or pair drift before a manual run. #[test] fn the_committed_scenario_set_parses_and_its_shared_premises_stay_equal() { let root = repository().join("xtask").join("scenario-eval"); @@ -7037,6 +7292,77 @@ mod tests { .find(|scenario| scenario.id == id) .unwrap_or_else(|| panic!("{id} is in the committed set")) } + let ids: Vec<_> = branches + .iter() + .map(|scenario| scenario.id.as_str()) + .collect(); + assert_eq!( + ids, + [ + "asking-the-user", + "background-command-not-branch", + "flooding", + "long-work-and-a-flaky-test", + "main-moved-on", + "never-ending", + "over-splitting", + "ping-pong", + "redone-work", + "refactor-and-a-pasted-report", + "root-opens-after-switch", + "same-file-tradeoff", + "sibling-relay", + "switch-continue-directly", + "switch-then-open-lines", + ], + "the committed branch set is the fifteen scenarios" + ); + assert_eq!( + compact + .iter() + .map(|scenario| scenario.id.as_str()) + .collect::>(), + ["identity-after-compaction"], + "the committed compact set is the one scenario" + ); + for scenario in &branches { + assert_eq!( + scenario.budget.window, 131_072, + "{}: the branch scenarios declare one window", + scenario.id + ); + } + assert_eq!( + find(&compact, "identity-after-compaction").budget.window, + 16_000, + "the compact scenario declares the window that compacts it" + ); + for scenario in &branches { + let switches = matches!( + scenario.id.as_str(), + "switch-continue-directly" | "switch-then-open-lines" | "root-opens-after-switch" + ); + assert_eq!( + scenario.switch.is_some(), + switches, + "{}: only the switch scenarios carry the move", + scenario.id + ); + } + assert!( + find(&branches, "switch-then-open-lines") + .switch + .as_ref() + .is_some_and(|switch| switch.branch_id.is_none()), + "switch-then-open-lines sends its next input to the new default branch" + ); + assert!( + find(&branches, "root-opens-after-switch") + .switch + .as_ref() + .is_some_and(|switch| switch.branch_id.as_deref() == Some("main")), + "root-opens-after-switch names the root after the move" + ); let redone = find(&branches, "redone-work"); let identity = find(&compact, "identity-after-compaction"); assert_eq!( From 50158032d28c7918336ac9f19437271247a7c3d8 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 01:19:02 +0800 Subject: [PATCH 02/32] test(branch): evaluate the default branch Add the seven scenarios for the default branch's opening and switching roles: two should-open, two boundary and three switch scenarios, each with a 131,072-token window. Two switch scenarios and root-opens-after-switch use the runner's new switch step. The committed-set test now reads all sixteen scenarios and pins their windows and switches. The design pages name the added set and the runner's mid-run move. --- docs/design/timeline-branches.md | 4 +- docs/zh/design/timeline-branches.md | 4 +- .../scenario.json | 10 +++++ .../workspace/README.md | 6 +++ .../workspace/scripts/slow_audit.py | 12 ++++++ .../workspace/src/__init__.py | 0 .../workspace/src/date_util.py | 6 +++ .../workspace/tests/test_date_util.py | 19 ++++++++++ .../long-work-and-a-flaky-test/scenario.json | 10 +++++ .../workspace/README.md | 8 ++++ .../workspace/api/__init__.py | 0 .../workspace/api/list.py | 10 +++++ .../workspace/docs/flaky-retry.md | 3 ++ .../workspace/src/__init__.py | 0 .../workspace/src/retry.py | 15 ++++++++ .../workspace/tests/test_list.py | 30 +++++++++++++++ .../workspace/tests/test_retry.py | 28 ++++++++++++++ .../scenario.json | 10 +++++ .../workspace/README.md | 6 +++ .../workspace/docs/incident-4471.md | 3 ++ .../workspace/report/__init__.py | 0 .../workspace/report/export.py | 20 ++++++++++ .../workspace/runbooks/__init__.py | 0 .../workspace/runbooks/nightly.py | 25 +++++++++++++ .../workspace/tests/golden/daily.csv | 3 ++ .../workspace/tests/test_export.py | 29 +++++++++++++++ .../root-opens-after-switch/scenario.json | 15 ++++++++ .../workspace/README.md | 5 +++ .../root-opens-after-switch/workspace/cli.py | 18 +++++++++ .../workspace/report.py | 14 +++++++ .../workspace/tests/__init__.py | 0 .../workspace/tests/test_cli.py | 16 ++++++++ .../workspace/tests/test_report.py | 22 +++++++++++ .../same-file-tradeoff/scenario.json | 9 +++++ .../same-file-tradeoff/workspace/NOTES.md | 9 +++++ .../same-file-tradeoff/workspace/README.md | 5 +++ .../workspace/src/__init__.py | 0 .../workspace/src/rate_limiter.py | 23 ++++++++++++ .../workspace/tests/test_rate_limiter.py | 25 +++++++++++++ .../switch-continue-directly/scenario.json | 14 +++++++ .../workspace/README.md | 5 +++ .../workspace/docs/README.md | 3 ++ .../workspace/schema.toml | 3 ++ .../workspace/src/__init__.py | 0 .../workspace/src/config_loader.py | 37 +++++++++++++++++++ .../workspace/tests/test_config_loader.py | 23 ++++++++++++ .../switch-then-open-lines/scenario.json | 14 +++++++ .../workspace/README.md | 7 ++++ .../workspace/audit/__init__.py | 0 .../workspace/audit/exporter.py | 9 +++++ .../workspace/auth/__init__.py | 0 .../workspace/auth/token.py | 14 +++++++ .../workspace/cli/__init__.py | 0 .../workspace/cli/login.py | 26 +++++++++++++ .../workspace/docs/README.md | 3 ++ .../workspace/tests/test_exporter.py | 23 ++++++++++++ .../workspace/tests/test_login.py | 19 ++++++++++ .../workspace/tests/test_token.py | 21 +++++++++++ 58 files changed, 641 insertions(+), 2 deletions(-) create mode 100644 xtask/scenario-eval/timeline-branches/background-command-not-branch/scenario.json create mode 100644 xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/README.md create mode 100644 xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/scripts/slow_audit.py create mode 100644 xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/src/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/src/date_util.py create mode 100644 xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/tests/test_date_util.py create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/scenario.json create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/README.md create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/api/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/api/list.py create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/docs/flaky-retry.md create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/src/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/src/retry.py create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/tests/test_list.py create mode 100644 xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/tests/test_retry.py create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/scenario.json create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/README.md create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/docs/incident-4471.md create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/report/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/report/export.py create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/runbooks/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/runbooks/nightly.py create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/tests/golden/daily.csv create mode 100644 xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/tests/test_export.py create mode 100644 xtask/scenario-eval/timeline-branches/root-opens-after-switch/scenario.json create mode 100644 xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/README.md create mode 100644 xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/cli.py create mode 100644 xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/report.py create mode 100644 xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/test_cli.py create mode 100644 xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/test_report.py create mode 100644 xtask/scenario-eval/timeline-branches/same-file-tradeoff/scenario.json create mode 100644 xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/NOTES.md create mode 100644 xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/README.md create mode 100644 xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/src/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/src/rate_limiter.py create mode 100644 xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/tests/test_rate_limiter.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-continue-directly/scenario.json create mode 100644 xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/README.md create mode 100644 xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/docs/README.md create mode 100644 xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/schema.toml create mode 100644 xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/src/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/src/config_loader.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/tests/test_config_loader.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/README.md create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/audit/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/audit/exporter.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/auth/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/auth/token.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/cli/__init__.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/cli/login.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/docs/README.md create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_exporter.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_login.py create mode 100644 xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_token.py diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index c02b19c2ea..e868605bd0 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -510,10 +510,12 @@ The requirements that answer these items are in [Model-facing prompts](model-pro ### 12.3 Evaluation scenarios -The set lives in the repository, one directory per scenario, holding a `scenario.json` and the starting `workspace/` beside it: eight under [`xtask/scenario-eval/timeline-branches/`](../../xtask/scenario-eval/timeline-branches/), each declaring a window of 131,072 tokens, and `identity-after-compaction` under [`xtask/scenario-eval/timeline-branches-compact/`](../../xtask/scenario-eval/timeline-branches-compact/), declaring 16,000 so that compaction happens. `budget.window` is a check, not a setting: a run whose Session declares another window fails before its first turn, so a rerun needs a model that declares exactly the scenario's window, and a model that declares none falls back to 128,000 and fails too. These are run locally on real models, and the results are reported in the implementation PR. CI asserts only behavior. +The set lives in the repository, one directory per scenario, holding a `scenario.json` and the starting `workspace/` beside it: fifteen under [`xtask/scenario-eval/timeline-branches/`](../../xtask/scenario-eval/timeline-branches/), each declaring a window of 131,072 tokens, and `identity-after-compaction` under [`xtask/scenario-eval/timeline-branches-compact/`](../../xtask/scenario-eval/timeline-branches-compact/), declaring 16,000 so that compaction happens. `budget.window` is a check, not a setting: a run whose Session declares another window fails before its first turn, so a rerun needs a model that declares exactly the scenario's window, and a model that declares none falls back to 128,000 and fails too. These are run locally on real models, and the results are reported in the implementation PR. CI asserts only behavior. `main-moved-on` is the scenario for the parent block (§7.1.1): `main` works before the cut, opens a line, then keeps working; the line must read what `main` did after the cut before it answers or ends, and it must not page through all of `main`'s activity. It is the scenario for [§12.4](#124-texts-and-their-classes)'s parent-block policy sentence. +The opening and switching roles add seven scenarios: `long-work-and-a-flaky-test`, `refactor-and-a-pasted-report`, `same-file-tradeoff`, `background-command-not-branch`, `switch-continue-directly`, `switch-then-open-lines` and `root-opens-after-switch`. + `identity-after-compaction` reuses `redone-work`'s message and workspace, and `flooding` and `never-ending` share one workspace: each pair stays identical, and the no-model test that reads both committed directories fails when one copy changes alone. | Scenario | Scenario directory | Watch for | diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index d2dad6ebff..80357b3cd8 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -476,10 +476,12 @@ WorkspaceTools 不变。 ### 12.3 评估场景 -场景放在仓库里,一个场景一个目录,目录里是 `scenario.json` 和它旁边的起始 `workspace/`:八个在 [`xtask/scenario-eval/timeline-branches/`](../../../xtask/scenario-eval/timeline-branches/) 下,各自声明 131,072 tokens 的窗口;`identity-after-compaction` 在 [`xtask/scenario-eval/timeline-branches-compact/`](../../../xtask/scenario-eval/timeline-branches-compact/) 下,声明 16,000,以便发生压缩。`budget.window` 是校验而不是设置:Session 声明的窗口与之不同时,这次运行在第一轮之前就失败,所以复跑需要模型声明正好这个窗口;没有声明窗口的模型回退到 128,000,同样失败。这些场景在本地用真实模型运行,结果在实现 PR 里报告。CI 只断言行为。 +场景放在仓库里,一个场景一个目录,目录里是 `scenario.json` 和它旁边的起始 `workspace/`:十五个在 [`xtask/scenario-eval/timeline-branches/`](../../../xtask/scenario-eval/timeline-branches/) 下,各自声明 131,072 tokens 的窗口;`identity-after-compaction` 在 [`xtask/scenario-eval/timeline-branches-compact/`](../../../xtask/scenario-eval/timeline-branches-compact/) 下,声明 16,000,以便发生压缩。`budget.window` 是校验而不是设置:Session 声明的窗口与之不同时,这次运行在第一轮之前就失败,所以复跑需要模型声明正好这个窗口;没有声明窗口的模型回退到 128,000,同样失败。这些场景在本地用真实模型运行,结果在实现 PR 里报告。CI 只断言行为。 `main-moved-on` 是父线块(§7.1.1)的场景:`main` 在切点之前有工作,开一条线,然后继续工作;这条线在回答或结束之前必须读取 `main` 在切点之后做的事,并且不能逐页读遍 `main` 的全部活动。它是 [§12.4](#124-文本及其类别) 父线块策略句的场景。 +开线与切换角色新增七个场景:`long-work-and-a-flaky-test`、`refactor-and-a-pasted-report`、`same-file-tradeoff`、`background-command-not-branch`、`switch-continue-directly`、`switch-then-open-lines`、`root-opens-after-switch`。 + `identity-after-compaction` 沿用 `redone-work` 的消息和 workspace,`flooding` 与 `never-ending` 共用同一个 workspace:这两对保持完全相同,改动其中一份而不同步另一份时,读取两个提交目录的无模型测试会失败。 | 场景 | 场景目录 | 关注什么 | diff --git a/xtask/scenario-eval/timeline-branches/background-command-not-branch/scenario.json b/xtask/scenario-eval/timeline-branches/background-command-not-branch/scenario.json new file mode 100644 index 0000000000..348407657a --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/background-command-not-branch/scenario.json @@ -0,0 +1,10 @@ +{ + "description": "A slow command and a small bug fix; a background command is not a line", + "message": "Run `python3 scripts/slow_audit.py` and report what it finds. Also fix the leap-year bug in src/date_util.py and add the missing test in tests/test_date_util.py. Do not change anything else.", + "budget": {"turns": 20, "seconds": 600, "window": 131072}, + "probes": [ + {"id": "report-read", "kind": "must_show", "text": "the output of python3 scripts/slow_audit.py is reported to the user"}, + {"id": "bug-fixed-with-test", "kind": "must_show", "text": "is_leap handles century years correctly and tests/test_date_util.py covers it"}, + {"id": "no-line-for-the-command", "kind": "must_not_show", "text": "a branch line is opened to run or watch the audit command"} + ] +} diff --git a/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/README.md b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/README.md new file mode 100644 index 0000000000..67627cef6a --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/README.md @@ -0,0 +1,6 @@ +# ops-tools + +- `scripts/slow_audit.py`: the storage audit; it takes a few seconds. +- `src/date_util.py`: calendar helpers. + +Run the tests with `python3 -m unittest discover -s tests`. diff --git a/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/scripts/slow_audit.py b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/scripts/slow_audit.py new file mode 100644 index 0000000000..19d513b64f --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/scripts/slow_audit.py @@ -0,0 +1,12 @@ +"""A deliberately slow audit, so the caller has to wait for its report.""" + +import time + + +def main(): + time.sleep(5) + print("slow_audit: 3 stale locks, 1 orphaned temp file, 0 missing indexes") + + +if __name__ == "__main__": + main() diff --git a/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/src/__init__.py b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/src/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/src/date_util.py b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/src/date_util.py new file mode 100644 index 0000000000..6fcf65cea2 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/src/date_util.py @@ -0,0 +1,6 @@ +"""Calendar helpers.""" + + +def is_leap(year): + """Returns whether the year has 366 days.""" + return year % 4 == 0 diff --git a/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/tests/test_date_util.py b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/tests/test_date_util.py new file mode 100644 index 0000000000..7c5789a41c --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/background-command-not-branch/workspace/tests/test_date_util.py @@ -0,0 +1,19 @@ +import os +import sys +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src")) + +from date_util import is_leap + + +class DateUtilTest(unittest.TestCase): + def test_ordinary_leap_year(self): + self.assertTrue(is_leap(2024)) + + def test_non_leap_year(self): + self.assertFalse(is_leap(2023)) + + +if __name__ == "__main__": + unittest.main() 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 new file mode 100644 index 0000000000..02131cb6c8 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/scenario.json @@ -0,0 +1,10 @@ +{ + "description": "Two independent jobs, one a feature and one a flaky test; neither waits for the other", + "message": "Two independent jobs in this project, and neither waits for the other. First, add cursor pagination to api/list.py: `list_page(cursor=None, limit=10)` returns `{items, nextCursor, done}`, the tests in tests/test_list.py pass, and README.md gets a short section on the cursor format. Second, reproduce the flake in tests/test_retry.py, find its cause, and write both the cause and the evidence that reproduces it to docs/flaky-retry.md. Keep each job to its own files.", + "budget": {"turns": 30, "seconds": 900, "window": 131072}, + "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"} + ] +} diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/README.md b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/README.md new file mode 100644 index 0000000000..dd0e78de60 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/README.md @@ -0,0 +1,8 @@ +# list-service + +Two small modules: + +- `api/list.py`: the in-memory list endpoint. +- `src/retry.py`: retry and concurrency helpers. + +Run the tests with `python3 -m unittest discover -s tests`. diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/api/__init__.py b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/api/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/api/list.py b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/api/list.py new file mode 100644 index 0000000000..15c06b5216 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/api/list.py @@ -0,0 +1,10 @@ +"""In-memory list endpoint.""" + +ITEMS = list(range(1, 101)) + + +def list_items(limit=None): + """Returns the items, at most `limit`.""" + if limit is None: + return list(ITEMS) + return ITEMS[:limit] diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/docs/flaky-retry.md b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/docs/flaky-retry.md new file mode 100644 index 0000000000..fd9ba0133b --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/docs/flaky-retry.md @@ -0,0 +1,3 @@ +# Flaky retry test + +The intermittent failures in `tests/test_retry.py` are still unexplained. diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/src/__init__.py b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/src/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/src/retry.py b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/src/retry.py new file mode 100644 index 0000000000..2992ae77cf --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/src/retry.py @@ -0,0 +1,15 @@ +"""Retry and small concurrency helpers.""" + +import time + + +class Attempts: + """Counts attempts made by concurrent workers.""" + + def __init__(self): + self.count = 0 + + def record(self): + current = self.count + time.sleep(0) + self.count = current + 1 diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/tests/test_list.py b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/tests/test_list.py new file mode 100644 index 0000000000..69ced4a41e --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/tests/test_list.py @@ -0,0 +1,30 @@ +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from api.list import list_page + + +class ListPageTest(unittest.TestCase): + def test_first_page(self): + page = list_page(cursor=None, limit=10) + self.assertEqual(page["items"], list(range(1, 11))) + self.assertEqual(page["nextCursor"], "10") + self.assertFalse(page["done"]) + + def test_last_page(self): + page = list_page(cursor="95", limit=10) + self.assertEqual(page["items"], list(range(96, 101))) + self.assertIsNone(page["nextCursor"]) + self.assertTrue(page["done"]) + + def test_limit_is_capped(self): + page = list_page(cursor=None, limit=500) + self.assertEqual(len(page["items"]), 100) + self.assertTrue(page["done"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/tests/test_retry.py b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/tests/test_retry.py new file mode 100644 index 0000000000..e60c87d3bc --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/long-work-and-a-flaky-test/workspace/tests/test_retry.py @@ -0,0 +1,28 @@ +import os +import sys +import threading +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from src.retry import Attempts + + +class RetryTest(unittest.TestCase): + def test_concurrent_attempts_are_not_lost(self): + attempts = Attempts() + + def worker(): + for _ in range(250): + attempts.record() + + threads = [threading.Thread(target=worker) for _ in range(4)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + self.assertEqual(attempts.count, 1000) + + +if __name__ == "__main__": + unittest.main() 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 new file mode 100644 index 0000000000..3079f4c82d --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/scenario.json @@ -0,0 +1,10 @@ +{ + "description": "A refactor with golden files and a pasted traceback to triage; the two jobs are independent", + "message": "Two separate jobs in this project. First, move the CSV writing out of report/export.py into a new report/writer.py, and keep tests/test_export.py and the golden files passing. Second, triage this traceback from last night's run and write the cause and the fix in docs/incident-4471.md; the runbook that produced it is runbooks/nightly.py:\n\n```\nTraceback (most recent call last):\n File \"runbooks/nightly.py\", line 25, in \n main()\n File \"runbooks/nightly.py\", line 20, in main\n report = build_report(rows)\n File \"report/export.py\", line 10, in build_report\n total += row[\"total\"]\nKeyError: 'total'\n```\n\nKeep the refactor to report/, tests/test_export.py and tests/golden/.", + "budget": {"turns": 30, "seconds": 900, "window": 131072}, + "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"} + ] +} diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/README.md b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/README.md new file mode 100644 index 0000000000..ad88ed9375 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/README.md @@ -0,0 +1,6 @@ +# report-service + +`report/export.py` builds the nightly report and writes it as CSV. +`runbooks/nightly.py` is the scheduled entry point. + +Run the tests with `python3 -m unittest discover -s tests`. diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/docs/incident-4471.md b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/docs/incident-4471.md new file mode 100644 index 0000000000..77b08e7c1a --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/docs/incident-4471.md @@ -0,0 +1,3 @@ +# Incident 4471 + +Last night's nightly run failed with a `KeyError: 'total'`. diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/report/__init__.py b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/report/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/report/export.py b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/report/export.py new file mode 100644 index 0000000000..037c935d92 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/report/export.py @@ -0,0 +1,20 @@ +"""Report export.""" + +import csv + + +def build_report(rows): + """Returns the rows and their total.""" + total = 0 + for row in rows: + total += row["total"] + return {"rows": rows, "total": total} + + +def export_csv(path, rows): + """Writes the rows to path as CSV.""" + with open(path, "w", newline="") as handle: + writer = csv.writer(handle) + writer.writerow(["name", "total"]) + for row in rows: + writer.writerow([row["name"], row["total"]]) diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/runbooks/__init__.py b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/runbooks/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/runbooks/nightly.py b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/runbooks/nightly.py new file mode 100644 index 0000000000..bf5f44bb73 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/runbooks/nightly.py @@ -0,0 +1,25 @@ +"""Nightly report runbook.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from report.export import build_report, export_csv + + +def load_rows(): + return [ + {"name": "api", "amount": 12}, + {"name": "web", "amount": 30}, + ] + + +def main(): + rows = load_rows() + report = build_report(rows) + export_csv("daily.csv", report["rows"]) + + +if __name__ == "__main__": + main() diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/tests/golden/daily.csv b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/tests/golden/daily.csv new file mode 100644 index 0000000000..3fe989a87f --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/tests/golden/daily.csv @@ -0,0 +1,3 @@ +name,total +api,12 +web,30 diff --git a/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/tests/test_export.py b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/tests/test_export.py new file mode 100644 index 0000000000..f45f302ef9 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/refactor-and-a-pasted-report/workspace/tests/test_export.py @@ -0,0 +1,29 @@ +import csv +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from report.export import build_report, export_csv + + +class ExportTest(unittest.TestCase): + def test_build_report(self): + rows = [{"name": "api", "total": 12}, {"name": "web", "total": 30}] + self.assertEqual(build_report(rows)["total"], 42) + + def test_export_matches_the_golden_file(self): + rows = [{"name": "api", "total": 12}, {"name": "web", "total": 30}] + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "daily.csv") + export_csv(path, rows) + with open(path, newline="") as written, open( + os.path.join("tests", "golden", "daily.csv"), newline="" + ) as golden: + self.assertEqual(list(csv.reader(written)), list(csv.reader(golden))) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/root-opens-after-switch/scenario.json b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/scenario.json new file mode 100644 index 0000000000..5259ea9548 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/scenario.json @@ -0,0 +1,15 @@ +{ + "description": "The root opens a line after another line became the default branch; the new line starts from the root and reports to it", + "message": "Open one line to add a `--dry-run` option to cli.py with a test. While it works, update README.md with the new option and the project's test command.", + "switch": { + "to": {"role": "latest_tool_line"}, + "message": "Now add a `--json` output option to report.py with a test. Open a new line for it, from your own history.", + "branchId": "main" + }, + "budget": {"turns": 30, "seconds": 900, "window": 131072}, + "probes": [ + {"id": "root-opens-line", "kind": "must_show", "text": "after the default branch moved to the tool line, the root opens a new line with the branch tool in response to the user's second request"}, + {"id": "new-line-reports-to-root", "kind": "must_show", "text": "the new line is cut from the root's history and reports to the root, not to the line holding the default branch"}, + {"id": "default-line-does-not-take-it", "kind": "must_not_show", "text": "the line holding the default branch does the --json work itself"} + ] +} diff --git a/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/README.md b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/README.md new file mode 100644 index 0000000000..0310daea80 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/README.md @@ -0,0 +1,5 @@ +# tool + +`cli.py` reads a file; `report.py` writes JSON reports. + +Run the tests with `python3 -m unittest discover -s tests`. diff --git a/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/cli.py b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/cli.py new file mode 100644 index 0000000000..1c231a269b --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/cli.py @@ -0,0 +1,18 @@ +"""Small command-line tool.""" + +import argparse + + +def build_parser(): + parser = argparse.ArgumentParser(prog="tool", description="Run the tool.") + parser.add_argument("path", help="the file to read") + return parser + + +def main(argv=None): + args = build_parser().parse_args(argv) + print(f"reading {args.path}") + + +if __name__ == "__main__": + main() diff --git a/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/report.py b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/report.py new file mode 100644 index 0000000000..66b31c403b --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/report.py @@ -0,0 +1,14 @@ +"""Report formatting.""" + +import json + + +def render(rows): + """Returns the rows as a JSON string.""" + return json.dumps(rows) + + +def write(path, rows): + """Writes the rows to path.""" + with open(path, "w") as handle: + handle.write(render(rows)) diff --git a/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/__init__.py b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/test_cli.py b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/test_cli.py new file mode 100644 index 0000000000..2214b3ee97 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/test_cli.py @@ -0,0 +1,16 @@ +import unittest + +from cli import build_parser + + +class CliTest(unittest.TestCase): + def test_path_is_required(self): + with self.assertRaises(SystemExit): + build_parser().parse_args([]) + + def test_help_names_the_path(self): + self.assertIn("the file to read", build_parser().format_help()) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/test_report.py b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/test_report.py new file mode 100644 index 0000000000..52e5c489d9 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/root-opens-after-switch/workspace/tests/test_report.py @@ -0,0 +1,22 @@ +import json +import os +import tempfile +import unittest + +from report import render, write + + +class ReportTest(unittest.TestCase): + def test_render(self): + self.assertEqual(json.loads(render([{"name": "api"}])), [{"name": "api"}]) + + def test_write(self): + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "report.json") + write(path, [{"name": "api"}]) + with open(path) as handle: + self.assertEqual(json.load(handle), [{"name": "api"}]) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/same-file-tradeoff/scenario.json b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/scenario.json new file mode 100644 index 0000000000..a1cebb6726 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/scenario.json @@ -0,0 +1,9 @@ +{ + "description": "Two designs for one core file; the file must not change before the recommendation", + "message": "We need to choose between a token bucket and a sliding window for src/rate_limiter.py. Look at how each handles the burst cases in tests/test_rate_limiter.py, compare them, and write a concrete recommendation with the trade-offs in NOTES.md. Only after the recommendation is in NOTES.md, change src/rate_limiter.py to the design you recommended, keeping the tests passing.", + "budget": {"turns": 20, "seconds": 600, "window": 131072}, + "probes": [ + {"id": "both-designs-compared", "kind": "must_show", "text": "NOTES.md compares the token bucket and the sliding window on the burst cases in tests/test_rate_limiter.py"}, + {"id": "file-unchanged-before-recommendation", "kind": "must_not_show", "text": "src/rate_limiter.py is edited before NOTES.md holds the comparison and recommendation"} + ] +} diff --git a/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/NOTES.md b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/NOTES.md new file mode 100644 index 0000000000..5c9500b754 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/NOTES.md @@ -0,0 +1,9 @@ +# Rate limiter notes + +Requirements: + +- Bursts up to 20 requests must be allowed after an idle period. +- Sustained traffic must stay at 10 requests per second. +- A rejected request must not consume capacity. + +Decision: (not written yet) diff --git a/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/README.md b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/README.md new file mode 100644 index 0000000000..a3707ce344 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/README.md @@ -0,0 +1,5 @@ +# rate-limiter + +`src/rate_limiter.py` is the current fixed-window limiter. The burst requirements are in `NOTES.md`. + +Run the tests with `python3 -m unittest discover -s tests`. diff --git a/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/src/__init__.py b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/src/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/src/rate_limiter.py b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/src/rate_limiter.py new file mode 100644 index 0000000000..020abc94ba --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/src/rate_limiter.py @@ -0,0 +1,23 @@ +"""Fixed-window rate limiter.""" + +import time + + +class RateLimiter: + """Allows `limit` requests in each wall-clock window.""" + + def __init__(self, limit=10, window=1.0): + self.limit = limit + self.window = window + self.start = time.monotonic() + self.count = 0 + + def allow(self): + now = time.monotonic() + if now - self.start >= self.window: + self.start = now + self.count = 0 + if self.count >= self.limit: + return False + self.count += 1 + return True diff --git a/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/tests/test_rate_limiter.py b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/tests/test_rate_limiter.py new file mode 100644 index 0000000000..53408f960c --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/same-file-tradeoff/workspace/tests/test_rate_limiter.py @@ -0,0 +1,25 @@ +import os +import sys +import time +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src")) + +from rate_limiter import RateLimiter + + +class RateLimiterTest(unittest.TestCase): + def test_sustained_rate(self): + limiter = RateLimiter(limit=10, window=1.0) + allowed = sum(limiter.allow() for _ in range(20)) + self.assertEqual(allowed, 10) + + def test_burst_after_idle(self): + limiter = RateLimiter(limit=20, window=1.0) + time.sleep(1.05) + allowed = sum(limiter.allow() for _ in range(20)) + self.assertEqual(allowed, 20) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/switch-continue-directly/scenario.json b/xtask/scenario-eval/timeline-branches/switch-continue-directly/scenario.json new file mode 100644 index 0000000000..7216e21c85 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-continue-directly/scenario.json @@ -0,0 +1,14 @@ +{ + "description": "A line designs a layered-defaults merge, the runner makes it the default branch, and the next request asks for the implementation there", + "message": "Open one line to design a layered-defaults merge for src/config_loader.py: defaults first, then schema.toml, then environment overrides, with the precedence written down. Have it write the design to docs/layered-defaults.md without editing src/config_loader.py yet. While it works, read schema.toml and tell me which source wins today.", + "switch": { + "to": {"role": "latest_tool_line"}, + "message": "The layered-defaults design in docs/layered-defaults.md is the one I want. Implement it in src/config_loader.py here, with tests." + }, + "budget": {"turns": 20, "seconds": 600, "window": 131072}, + "probes": [ + {"id": "implemented-here", "kind": "must_show", "text": "after the switch, the new default branch edits src/config_loader.py to implement the layered-defaults design and runs its tests"}, + {"id": "no-line-for-the-implement-step", "kind": "must_not_show", "text": "the new default branch opens a line to implement the design instead of doing it itself"}, + {"id": "does-not-end-itself", "kind": "must_not_show", "text": "the new default branch calls the branch tool's end action on itself"} + ] +} diff --git a/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/README.md b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/README.md new file mode 100644 index 0000000000..b4b50e8c50 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/README.md @@ -0,0 +1,5 @@ +# config-loader + +`src/config_loader.py` reads `schema.toml` and merges it over the built-in defaults. Environment overrides are read by `from_environment`. + +Run the tests with `python3 -m unittest discover -s tests`. diff --git a/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/docs/README.md b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/docs/README.md new file mode 100644 index 0000000000..64bea5b688 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/docs/README.md @@ -0,0 +1,3 @@ +# Design notes + +Design documents for the configuration loader live here. diff --git a/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/schema.toml b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/schema.toml new file mode 100644 index 0000000000..1e9281d584 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/schema.toml @@ -0,0 +1,3 @@ +[server] +host = "localhost" +port = 8080 diff --git a/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/src/__init__.py b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/src/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/src/config_loader.py b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/src/config_loader.py new file mode 100644 index 0000000000..794d8184bb --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/src/config_loader.py @@ -0,0 +1,37 @@ +"""Configuration loading.""" + +import os + +DEFAULTS = { + "timeout": 30, + "retries": 3, +} + + +def _read_schema(path): + values = {} + with open(path) as handle: + for line in handle: + line = line.strip() + if not line or line.startswith("#") or line.startswith("["): + continue + key, _, value = line.partition("=") + value = value.strip() + values[key.strip()] = int(value) if value.isdigit() else value.strip('"') + return values + + +def load(path="schema.toml"): + """Returns the defaults merged with the schema file.""" + merged = dict(DEFAULTS) + merged.update(_read_schema(path)) + return merged + + +def from_environment(prefix="APP_"): + """Returns the environment overrides as a flat mapping.""" + overrides = {} + for name, value in os.environ.items(): + if name.startswith(prefix): + overrides[name[len(prefix):].lower()] = value + return overrides diff --git a/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/tests/test_config_loader.py b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/tests/test_config_loader.py new file mode 100644 index 0000000000..664c2ceb3e --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-continue-directly/workspace/tests/test_config_loader.py @@ -0,0 +1,23 @@ +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from src.config_loader import load + + +class ConfigLoaderTest(unittest.TestCase): + def test_defaults_are_used(self): + config = load() + self.assertEqual(config["timeout"], 30) + self.assertEqual(config["retries"], 3) + + def test_schema_values_win(self): + config = load() + self.assertEqual(config["host"], "localhost") + self.assertEqual(config["port"], 8080) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json new file mode 100644 index 0000000000..73bc6d3281 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json @@ -0,0 +1,14 @@ +{ + "description": "A line diagnoses an early-expiry bug; after the move, the new default branch fixes it and opens lines for two independent additions", + "message": "Open one line to diagnose the early-expiry bug in auth/token.py and write the diagnosis to docs/early-expiry.md. It should not change auth/token.py yet. While it works, check README.md for anything stale.", + "switch": { + "to": {"role": "latest_tool_line"}, + "message": "Fix the early-expiry bug here, with a test. Then add `--leeway` to cli/login.py and CSV output to audit/exporter.py, each with tests and help text. The two additions are independent." + }, + "budget": {"turns": 30, "seconds": 900, "window": 131072}, + "probes": [ + {"id": "both-additions-work", "kind": "must_show", "text": "the --leeway option and the CSV export are implemented, with tests and help text"}, + {"id": "former-default-opens-none-and-touches-none", "kind": "must_not_show", "text": "after the switch, the former default branch opens a line or edits any file"}, + {"id": "bug-fixed-with-test", "kind": "must_show", "text": "the early-expiry bug is fixed and a test covers it"} + ] +} diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/README.md b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/README.md new file mode 100644 index 0000000000..21c997389d --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/README.md @@ -0,0 +1,7 @@ +# auth-tools + +- `auth/token.py`: issues and validates access tokens. +- `cli/login.py`: the login command. +- `audit/exporter.py`: exports audit events. + +Run the tests with `python3 -m unittest discover -s tests`. diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/audit/__init__.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/audit/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/audit/exporter.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/audit/exporter.py new file mode 100644 index 0000000000..6cf8379c09 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/audit/exporter.py @@ -0,0 +1,9 @@ +"""Audit export.""" + +import json + + +def export(path, events): + """Writes the events as JSON.""" + with open(path, "w") as handle: + json.dump(events, handle) diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/auth/__init__.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/auth/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/auth/token.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/auth/token.py new file mode 100644 index 0000000000..b93878b5ee --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/auth/token.py @@ -0,0 +1,14 @@ +"""Access tokens.""" + +import time + + +def issue(ttl=60): + """Issues a token that is valid for ttl seconds.""" + return {"issued": time.time(), "ttl": ttl} + + +def is_valid(token, now=None): + """Returns whether the token is still valid.""" + now = time.time() if now is None else now + return now < token["issued"] + token["ttl"] - 1 diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/cli/__init__.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/cli/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/cli/login.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/cli/login.py new file mode 100644 index 0000000000..31f319de1a --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/cli/login.py @@ -0,0 +1,26 @@ +"""Login command.""" + +import argparse + +from auth.token import issue + + +def build_parser(): + parser = argparse.ArgumentParser(prog="login", description="Log a user in.") + parser.add_argument("user", help="the user to log in") + return parser + + +def login(user): + """Issues the user's token.""" + return issue(ttl=60) + + +def main(argv=None): + args = build_parser().parse_args(argv) + token = login(args.user) + print(f"logged in {args.user}; token valid for {token['ttl']}s") + + +if __name__ == "__main__": + main() diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/docs/README.md b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/docs/README.md new file mode 100644 index 0000000000..09d939f91b --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/docs/README.md @@ -0,0 +1,3 @@ +# Notes + +Diagnoses and incident notes live here. diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_exporter.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_exporter.py new file mode 100644 index 0000000000..13942dd707 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_exporter.py @@ -0,0 +1,23 @@ +import json +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from audit.exporter import export + + +class ExporterTest(unittest.TestCase): + def test_json_export(self): + events = [{"kind": "login", "user": "ada"}] + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "audit.json") + export(path, events) + with open(path) as handle: + self.assertEqual(json.load(handle), events) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_login.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_login.py new file mode 100644 index 0000000000..119281ca0a --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_login.py @@ -0,0 +1,19 @@ +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from cli.login import build_parser, login + + +class LoginTest(unittest.TestCase): + def test_login_issues_a_token(self): + self.assertEqual(login("ada")["ttl"], 60) + + def test_help_names_the_user(self): + self.assertIn("the user to log in", build_parser().format_help()) + + +if __name__ == "__main__": + unittest.main() diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_token.py b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_token.py new file mode 100644 index 0000000000..04a7a69fc5 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/workspace/tests/test_token.py @@ -0,0 +1,21 @@ +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from auth.token import is_valid, issue + + +class TokenTest(unittest.TestCase): + def test_token_is_valid_inside_ttl(self): + token = issue(ttl=60) + self.assertTrue(is_valid(token, now=token["issued"] + 59.5)) + + def test_token_expires_after_ttl(self): + token = issue(ttl=60) + self.assertFalse(is_valid(token, now=token["issued"] + 61)) + + +if __name__ == "__main__": + unittest.main() From 394222d509bfbccbc73c7dc105385ba5e7fabfe2 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 02:21:00 +0800 Subject: [PATCH 03/32] fix(xtask): fail a scenario run whose switch never fired A pending switch now keeps the run open, so a target line that never appears or never finishes its first turn is not mistaken for an idle run. A switch still pending when the loop ends stops the run as `switch_target_not_reached`, with the target in the reason and its own place in the failed-run count. A target whose line ended before the move answers `branch_ended`; the run stops as `switch_target_ended` instead of a harness error, and the reason names the line. The switch's order, single fire and error path are covered by a recording client: the default branch moves before the next input, a second trigger sends nothing, and a refused move sends no input. Both the swapped order and a switch that fires twice make the test fail. --- xtask/src/scenario_eval.rs | 236 +++++++++++++++++++++++++++++++++---- 1 file changed, 216 insertions(+), 20 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 29efcf5322..25e4c80f9d 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -1211,6 +1211,8 @@ fn stop_name(stop: &str) -> Result<&'static str> { "idle" => Ok("idle"), "turns" => Ok("turns"), "seconds" => Ok("seconds"), + "switch_target_not_reached" => Ok("switch_target_not_reached"), + "switch_target_ended" => Ok("switch_target_ended"), "error" => Ok("error"), other => Err(format!("the saved run has an unknown stop {other}").into()), } @@ -2089,7 +2091,8 @@ struct RunRecord { scenario: String, run: usize, session: Option, - /// `idle`, `turns`, `seconds` or `error`. + /// `idle`, `turns`, `seconds`, `switch_target_not_reached`, + /// `switch_target_ended` or `error`. stop: &'static str, turns: u32, window: Option, @@ -4272,6 +4275,8 @@ fn child_record( "idle" => "idle", "turns" => "turns", "seconds" => "seconds", + "switch_target_not_reached" => "switch_target_not_reached", + "switch_target_ended" => "switch_target_ended", _ => "error", }; let error = match &outcome.harness { @@ -4507,12 +4512,14 @@ async fn drive_once( } /// Whether the run is a failed run (model-prompts §8.1): it failed on its -/// own, an error or its wall-clock budget, or its judging did not happen — a -/// judge call failed, there was no export to judge, or no model host for the -/// judge. +/// own, an error, its wall-clock budget or a switch that could not happen, +/// or its judging did not happen — a judge call failed, there was no export +/// to judge, or no model host for the judge. fn failed(stop: &str, error: Option<&str>, judge_outcome: JudgeOutcome) -> bool { - stop == "seconds" - || error.is_some() + matches!( + stop, + "seconds" | "switch_target_not_reached" | "switch_target_ended" + ) || error.is_some() || matches!( judge_outcome, JudgeOutcome::CallFailed | JudgeOutcome::NotAsked @@ -4850,7 +4857,8 @@ async fn drive( // first in this pass, so a subscription the model made in its last // turn has already started the clock and keeps the run open here // (EventHub design A.4). - let pending = steers.iter().any(|(_, fired)| !fired) + let pending = switch.is_some() + || steers.iter().any(|(_, fired)| !fired) || events.iter().any(|(event, fired)| { !fired && (event.after_subscribed_seconds.is_none() || event.subscribed_at.is_some()) @@ -4912,7 +4920,15 @@ async fn drive( } } match fire_switch(client, &session, &mut switch, &branch, &event).await { - Ok(submitted) => awaiting |= submitted, + Ok(SwitchFire::Fired) => awaiting = true, + Ok(SwitchFire::NotFired) => {} + Ok(SwitchFire::TargetEnded { line, error }) => { + driven.stop = "switch_target_ended"; + driven.error = Some(format!( + "line {line} ended before the switch could move to it: {error}" + )); + return driven; + } Err(error) => { driven.stop = "error"; driven.error = Some(error); @@ -5014,6 +5030,27 @@ async fn drive( driven.stop = "error"; } } + if let Some(pending) = &switch { + let reason = match &pending.line { + Some(line) => format!( + "the switch never fired: line {line}'s first turn did not end before the run stopped on {}", + driven.stop + ), + None => format!( + "the switch never fired: no tool line was opened before the run stopped on {}", + driven.stop + ), + }; + if driven.stop == "error" { + driven.error = Some(match driven.error.take() { + Some(error) => format!("{error}; {reason}"), + None => reason, + }); + } else { + driven.stop = "switch_target_not_reached"; + driven.error = Some(reason); + } + } driven } @@ -5860,7 +5897,7 @@ fn submit_params( } async fn submit( - client: &mut Client, + client: &mut impl SwitchClient, session: &str, text: &str, mode: Option, @@ -5873,31 +5910,65 @@ async fn submit( .map_err(|error| format!("session.submit failed: {error}")) } +/// The one RPC a switch and its next input make; the tests' fake records the +/// calls and their order without a Session behind them. +trait SwitchClient { + async fn rpc(&mut self, method: &str, params: Value) -> dim_client::Result; +} + +impl SwitchClient for Client { + async fn rpc(&mut self, method: &str, params: Value) -> dim_client::Result { + Client::rpc(self, method, params).await + } +} + +/// What one notice did with the scenario's pending switch. +#[derive(Debug)] +enum SwitchFire { + /// The notice is not the trigger; the switch stays pending. + NotFired, + /// The default branch moved and the next input was sent. + Fired, + /// The target line had already ended, so the move answered + /// `branch_ended`: the run stops with its own outcome rather than a + /// harness error. + TargetEnded { line: String, error: String }, +} + /// Runs the scenario's switch when this notice is the target line's first -/// `turn/end`, and whether it sent the input after the move: the Session's -/// default branch moves first, then the next input is submitted, naming a -/// line only when the scenario does. +/// `turn/end`: the Session's default branch moves first, then the next input +/// is submitted, naming a line only when the scenario does. A switch fires +/// once, on the target line's first `turn/end`; a later notice leaves it +/// unfired. async fn fire_switch( - client: &mut Client, + client: &mut impl SwitchClient, session: &str, switch: &mut Option, branch: &str, event: &Value, -) -> std::result::Result { +) -> std::result::Result { let Some(pending) = switch.as_mut() else { - return Ok(false); + return Ok(SwitchFire::NotFired); }; let Some(line) = pending.notice(branch, event) else { - return Ok(false); + return Ok(SwitchFire::NotFired); }; let pending = switch.take().expect("the switch is pending"); - client + if let Err(error) = client .rpc( "session.branch_set_default", json!({"sessionId": session, "branchId": line}), ) .await - .map_err(|error| format!("the switch to {line} failed: {error}"))?; + { + if dim_client::app_error(&error) == Some("branch_ended") { + return Ok(SwitchFire::TargetEnded { + line: line.clone(), + error: error.to_string(), + }); + } + return Err(format!("the switch to {line} failed: {error}")); + } submit( client, session, @@ -5906,7 +5977,7 @@ async fn fire_switch( pending.switch.branch_id.as_deref(), ) .await?; - Ok(true) + Ok(SwitchFire::Fired) } /// Sends the timed steers that are due, and whether it sent one. @@ -7183,7 +7254,7 @@ mod tests { /// A switch names the line to move to by role or by id, and the input /// after the move; the runner moves the default branch after the target - /// line's first `turn/end` (Timeline branches §12.3). + /// line's first `turn/end` (model-prompts §9.8). #[test] fn a_switch_step_names_a_line_and_its_next_input() { let directory = @@ -7275,6 +7346,124 @@ mod tests { assert_eq!(pending.notice("4", &turn_end), Some("4".into())); } + /// The switch's calls, recorded, and the refusal its first call answers; + /// no Session stands behind it. + #[derive(Default)] + struct SwitchRecorder { + calls: Vec<(String, Value)>, + refusal: Option, + } + impl SwitchClient for SwitchRecorder { + async fn rpc(&mut self, method: &str, params: Value) -> dim_client::Result { + self.calls.push((method.to_owned(), params)); + match self.calls.len() { + 1 => match self.refusal.take() { + Some(refusal) => Err(refusal.into()), + None => Ok(json!({})), + }, + _ => Ok(json!({})), + } + } + } + + /// A switch moves the Session's default branch before it sends the next + /// input, and fires once: after the move the switch is gone, so the + /// target's later `turn/end` sends nothing (model-prompts §9.8). + #[tokio::test] + async fn a_switch_moves_the_default_branch_before_its_next_input_and_fires_once() { + let mut client = SwitchRecorder::default(); + let mut switch = Some(PendingSwitch::new(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + })); + let turn_end = json!({"type": "turn", "name": "end", "data": {}}); + assert!(matches!( + fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await, + Ok(SwitchFire::Fired) + )); + let calls: Vec<&str> = client + .calls + .iter() + .map(|(method, _)| method.as_str()) + .collect(); + assert_eq!( + calls, + ["session.branch_set_default", "session.submit"], + "the default branch moves before the next input is sent" + ); + assert_eq!(client.calls[0].1["branchId"], "2"); + assert_eq!(client.calls[1].1["text"], "next"); + assert!( + client.calls[1].1.get("branchId").is_none(), + "the next input lands on the new default branch" + ); + assert!(matches!( + fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await, + Ok(SwitchFire::NotFired) + )); + assert_eq!(client.calls.len(), 2, "a switch fires once"); + } + + /// A refused move answers the error that failed it and sends no input. + #[tokio::test] + async fn a_refused_switch_move_propagates_its_error_and_sends_no_input() { + let mut client = SwitchRecorder { + refusal: Some(dim_client::RpcError { + code: -32000, + message: "the tree is closing".into(), + data: Some(json!({"appError": "session_closed"})), + }), + ..SwitchRecorder::default() + }; + let mut switch = Some(PendingSwitch::new(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + })); + let turn_end = json!({"type": "turn", "name": "end", "data": {}}); + let error = match fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await { + Err(error) => error, + Ok(outcome) => panic!("the move was refused, not {outcome:?}"), + }; + assert!(error.contains("the switch to 2 failed"), "{error}"); + assert!(error.contains("the tree is closing"), "{error}"); + assert_eq!( + client.calls.len(), + 1, + "no input is sent after a refused move" + ); + } + + /// A target line that ended before the move is its own outcome, read from + /// the refusal's application code rather than its text, and not a harness + /// error (design §14, model-prompts §9.8). + #[tokio::test] + async fn a_target_that_ended_before_the_move_is_its_own_outcome() { + let mut client = SwitchRecorder { + refusal: Some(dim_client::RpcError { + code: -32000, + message: "branch 2 has ended".into(), + data: Some(json!({"appError": "branch_ended"})), + }), + ..SwitchRecorder::default() + }; + let mut switch = Some(PendingSwitch::new(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + })); + let turn_end = json!({"type": "turn", "name": "end", "data": {}}); + match fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await { + Ok(SwitchFire::TargetEnded { line, error }) => { + assert_eq!(line, "2"); + assert!(error.contains("branch_ended"), "{error}"); + } + outcome => panic!("the ended target is its own outcome, not {outcome:?}"), + } + assert_eq!(client.calls.len(), 1, "no input is sent to an ended line"); + } + /// The committed set parses through the runner's own reader, its two /// switch scenarios carry the move, and the two pairs that share a /// premise stay equal: the compact scenario reuses `redone-work`'s @@ -7356,6 +7545,13 @@ mod tests { .is_some_and(|switch| switch.branch_id.is_none()), "switch-then-open-lines sends its next input to the new default branch" ); + assert!( + find(&branches, "switch-continue-directly") + .switch + .as_ref() + .is_some_and(|switch| switch.branch_id.is_none()), + "switch-continue-directly sends its next input to the new default branch" + ); assert!( find(&branches, "root-opens-after-switch") .switch From 4c8bb61666037eb901b7870ad581bc76394deaeb Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 02:21:18 +0800 Subject: [PATCH 04/32] fix(branch): scope the former default's probe to the new work The switch-then-open-lines message also asks the former default, the root, to check README.md, and the root may open lines whatever the default branch is. The probe now names the files the new default branch owns, so the root's own README work is not a violation. --- .../timeline-branches/switch-then-open-lines/scenario.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json index 73bc6d3281..fb73e7f120 100644 --- a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json @@ -8,7 +8,7 @@ "budget": {"turns": 30, "seconds": 900, "window": 131072}, "probes": [ {"id": "both-additions-work", "kind": "must_show", "text": "the --leeway option and the CSV export are implemented, with tests and help text"}, - {"id": "former-default-opens-none-and-touches-none", "kind": "must_not_show", "text": "after the switch, the former default branch opens a line or edits any file"}, + {"id": "former-default-leaves-the-new-work", "kind": "must_not_show", "text": "after the switch, the former default branch opens a line for the new default branch's work or edits auth/token.py, cli/login.py, or audit/exporter.py"}, {"id": "bug-fixed-with-test", "kind": "must_show", "text": "the early-expiry bug is fixed and a test covers it"} ] } From 372d666f4c08903d089070ef3f5cf225db3db37a Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 02:21:18 +0800 Subject: [PATCH 05/32] docs(branch): sync the scenario table and evaluation list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Chinese scenario table gains the two switch rows the English table has and drops its duplicated row. model-prompts §9.4 names the sixteen scenarios instead of the original eight. --- docs/design/model-prompts.md | 2 +- docs/zh/design/model-prompts.md | 2 +- docs/zh/design/timeline-branches.md | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index 244b21a50d..e8707ac3b1 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -219,7 +219,7 @@ SessionTitle is out of scope: its `SYSTEM` (`crates/dim-session-title/src/lib.rs - **Protocol.** The marker names and attributes, the identity blocks' factual sentences, the branch tool's actions and modes, and its refusal codes change only with the branch mechanism, in the same change as the flow tests that assert them (§4). - **The coordination text for `main` covers the items of [Timeline branches §12.2](timeline-branches.md#122-items-for-the-prompt-layer-429).** -- **Evaluation.** These texts are policy: a change is evaluated with the scenarios of [Timeline branches §12.3](timeline-branches.md#123-evaluation-scenarios) — redone work, over-splitting, flooding, never ending, sibling relay, ping-pong, identity after compaction, asking the user — current against candidate (§8). +- **Evaluation.** These texts are policy: a change is evaluated with the sixteen scenarios of [Timeline branches §12.3](timeline-branches.md#123-evaluation-scenarios), current against candidate (§8). ### 9.5 Goal diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index 2db306606d..d1187a1039 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -218,7 +218,7 @@ SessionTitle 不在范围内:它的 `SYSTEM`(`crates/dim-session-title/src/l - **协议。** 标记名与属性、身份块里的事实句、branch 工具的 action 与 mode、以及它的拒绝码,只随分支机制一起改,并与断言它们的流程测试同一个改动(§4)。 - **`main` 的协调文字覆盖 [Timeline 分支 §12.2](timeline-branches.md#122-交给提示词层的事项429) 的事项。** -- **评估。** 这些文字是策略:改动用 [Timeline 分支 §12.3](timeline-branches.md#123-评估场景) 的场景评估——重做工作、过度拆线、刷屏、不肯结束、兄弟转达、乒乓、压缩后的身份、直接问用户——当前对照候选(§8)。 +- **评估。** 这些文字是策略:改动用 [Timeline 分支 §12.3](timeline-branches.md#123-评估场景) 的十六个场景评估,当前对照候选(§8)。 ### 9.5 Goal diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 80357b3cd8..001d2ea9b7 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -489,7 +489,6 @@ WorkspaceTools 不变。 | 线把自己当成默认分支 | — | 不是默认分支的线把 Session 的对话当成自己的、无视自己可以开线,或者已经是默认分支的线不再向开它的那条线汇报 | | 线在不能开线的地方开线 | — | 既不是根也不是当前默认分支的线自己开线,而不是告诉其中一条 | | 上限与那条路径 | — | Session 已经超过上限时线仍拒绝开线,或者为腾位置关闭一条线 | -| 线把自己当成默认分支 | — | 不是默认分支的线把 Session 的对话当成自己的,或者已经是默认分支的线不再向开它的那条线汇报 | | 重复劳动 | `timeline-branches/redone-work` | `main` 重做一条线正在做的事,或者两条线做同一件事 | | 过时的认识 | — | 一条线依据切点之后已经改变的文件或决定行事,却没有重新读取 | | 父线动了 | `timeline-branches/main-moved-on` | 一条线在回答或结束前没有读取父线在切点之后提交的活动,或者逐页读遍了父线的全部活动 | @@ -498,6 +497,8 @@ WorkspaceTools 不变。 | 不结束 | `timeline-branches/never-ending` | 一条线已经做完,却不调用 `end` | | 兄弟中转 | `timeline-branches/sibling-relay` | 用 `main` 在本该合成一条线的几条线之间传话 | | 压缩后的身份 | `timeline-branches-compact/identity-after-compaction` | `main` 和某条线各自压缩之后,仍知道自己是哪条线、哪些线是自己的 | +| 切换后继续在线上工作 | — | 成为默认分支的线对自己调用 `end`、把工作交给另一条线、不断用 idle 通知唤醒开它的线,或者根能开线而这条线不能 | +| 线持有角色时根开线 | `timeline-branches/root-opens-after-switch` | 另一条线成为默认分支后,用户向根要一条线:根必须开这条线,新线必须从根的历史开始,并向根汇报 | | 来回空转 | `timeline-branches/ping-pong` | 不推进工作的 steer 往复 | | 问用户 | `timeline-branches/asking-the-user` | 该问用户时,线直接问用户,而不是绕道 `main` | From 68f6ce3788d9aee69e7621364eeee48e9d060bd0 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 06:20:55 +0800 Subject: [PATCH 06/32] fix(xtask): treat a protected switch target as its own outcome A line that ends itself commits `branch/end` during its turn, so the move that follows the turn's end answers `branch_target_protected` rather than `branch_ended`. Both refusals now stop the run as `switch_target_ended`, with the tree's message, instead of recording a harness error; the test covers both codes. --- xtask/src/scenario_eval.rs | 72 +++++++++++++++++++++----------------- 1 file changed, 40 insertions(+), 32 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 25e4c80f9d..a456c1539a 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -5929,9 +5929,9 @@ enum SwitchFire { NotFired, /// The default branch moved and the next input was sent. Fired, - /// The target line had already ended, so the move answered - /// `branch_ended`: the run stops with its own outcome rather than a - /// harness error. + /// The target line had already ended, or a line above it was ending, so + /// the move answered `branch_ended` or `branch_target_protected`: the run + /// stops with its own outcome rather than a harness error. TargetEnded { line: String, error: String }, } @@ -5961,13 +5961,15 @@ async fn fire_switch( ) .await { - if dim_client::app_error(&error) == Some("branch_ended") { - return Ok(SwitchFire::TargetEnded { - line: line.clone(), - error: error.to_string(), - }); + match dim_client::app_error(&error) { + Some("branch_ended" | "branch_target_protected") => { + return Ok(SwitchFire::TargetEnded { + line: line.clone(), + error: error.to_string(), + }); + } + _ => return Err(format!("the switch to {line} failed: {error}")), } - return Err(format!("the switch to {line} failed: {error}")); } submit( client, @@ -7435,33 +7437,39 @@ mod tests { ); } - /// A target line that ended before the move is its own outcome, read from - /// the refusal's application code rather than its text, and not a harness - /// error (design §14, model-prompts §9.8). + /// A target line that ended, or whose chain was ending, before the move is + /// its own outcome, read from the refusal's application code rather than + /// its text, and not a harness error (design §14, §20.26a; model-prompts + /// §9.8). #[tokio::test] async fn a_target_that_ended_before_the_move_is_its_own_outcome() { - let mut client = SwitchRecorder { - refusal: Some(dim_client::RpcError { - code: -32000, - message: "branch 2 has ended".into(), - data: Some(json!({"appError": "branch_ended"})), - }), - ..SwitchRecorder::default() - }; - let mut switch = Some(PendingSwitch::new(Switch { - to: SwitchTarget::Id("2".into()), - message: "next".into(), - branch_id: None, - })); - let turn_end = json!({"type": "turn", "name": "end", "data": {}}); - match fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await { - Ok(SwitchFire::TargetEnded { line, error }) => { - assert_eq!(line, "2"); - assert!(error.contains("branch_ended"), "{error}"); + for (code, message) in [ + ("branch_ended", "branch 2 has ended"), + ("branch_target_protected", "line 2 is ending or ended"), + ] { + let mut client = SwitchRecorder { + refusal: Some(dim_client::RpcError { + code: -32000, + message: message.into(), + data: Some(json!({"appError": code})), + }), + ..SwitchRecorder::default() + }; + let mut switch = Some(PendingSwitch::new(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + })); + let turn_end = json!({"type": "turn", "name": "end", "data": {}}); + match fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await { + Ok(SwitchFire::TargetEnded { line, error }) => { + assert_eq!(line, "2"); + assert!(error.contains(code), "{code}: {error}"); + } + outcome => panic!("{code}: the ended target is its own outcome, not {outcome:?}"), } - outcome => panic!("the ended target is its own outcome, not {outcome:?}"), + assert_eq!(client.calls.len(), 1, "{code}: no input is sent to an ended line"); } - assert_eq!(client.calls.len(), 1, "no input is sent to an ended line"); } /// The committed set parses through the runner's own reader, its two From b187ed144af4c57a8d497b4da5bfb5f03c5a07b9 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 06:36:19 +0800 Subject: [PATCH 07/32] style(xtask): format the ended-target test rustfmt wraps the call-count assertion; no behavior changes. --- xtask/src/scenario_eval.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index a456c1539a..0975f5036a 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -7468,7 +7468,11 @@ mod tests { } outcome => panic!("{code}: the ended target is its own outcome, not {outcome:?}"), } - assert_eq!(client.calls.len(), 1, "{code}: no input is sent to an ended line"); + assert_eq!( + client.calls.len(), + 1, + "{code}: no input is sent to an ended line" + ); } } From 50ea6f791fa55e8509990fa506f0b989efc7db08 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 09:51:09 +0800 Subject: [PATCH 08/32] fix(xtask): switch when the target line starts its first turn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first turn can start before the line is marked ready, so the move now runs at the target's `turn/start` and retries a bounded number of times when the tree answers `unknown_branch`. A line that never becomes ready ends the run as `switch_target_unknown`; the runner records its retry count. The design sentence in model-prompts §9.8 follows the new trigger. Tests cover the trigger, the retry, the exhausted budget and the pending-switch outcome at a run's budget. --- docs/design/model-prompts.md | 2 +- docs/zh/design/model-prompts.md | 2 +- xtask/src/scenario_eval.rs | 426 ++++++++++++++++++++++++-------- 3 files changed, 330 insertions(+), 100 deletions(-) diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index e8707ac3b1..abf07c36b6 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -252,7 +252,7 @@ SessionTitle is out of scope: its `SYSTEM` (`crates/dim-session-title/src/lib.rs **Owner:** the evaluation tooling, `xtask`; implemented under [#550](https://github.com/arcships/dim/issues/550). - **A scenario runner** with the candidate injection and the test of §8.1: the scenarios are the cases, both arms run the shipped assembly, and the result is reported in the pull request. It interleaves the arms run by run and accepts `--jobs` and repeated `--text`/`--candidate` pairs, so a change that spans two texts of one owner is judged as the one change it is (Goal §A.5.2). -- **A scenario may move the default branch mid-run.** Its `switch` step names the target line, by role (`latest_tool_line`) or id, and the runner calls `session.branch_set_default` after that line's first `turn/end` before sending the next input; an input that names no line lands on the default branch, and one that names a line keeps that target. +- **A scenario may move the default branch mid-run.** Its `switch` step names the target line, by role (`latest_tool_line`) or id, and the runner calls `session.branch_set_default` at that line's first `turn/start` before sending the next input; the move is retried a few times while the line is not registered yet, and a line that never registers ends the run with its own outcome. An input that names no line lands on the default branch, and one that names a line keeps that target. - **A finished evaluation's saved runs are judged again or pooled.** `--rejudge DIR` judges them from the views they saved, with no model turn, keeping each run's own outcome and writing to a new `--out`; `--pool DIR` adds a finished evaluation's saved runs to a report under the same rule and format, and the flag may be repeated to pool several evaluations, writing to none of them, and an `--out` that resolves inside a source, through `..` or a link, is refused before anything is created. Such a report names its sources, has no text or candidate-token row, and in a pool its model and judge rows are the ones given, while each source's own report states the instrument its runs were judged with. Such a report also gives the declines the runner sent again and how many runs did not record it. - **A run's file roots.** Each live run serves with three kinds of file-tool root: its workspace, which the model may read and write; its disposable home, which `~` resolves against and which the model may read; and the platform's fixed read-only roots, which carry the toolchain the run's commands read, such as the interpreter's own installation. A file-tool path outside them is refused with `outside_file_roots`, and the refusal leaves what is outside untouched. The roots bound the model's file-tool calls — `read`, `write`, `edit`, `glob` and `grep`; `exec` is bounded by the sandbox, and the client-initiated paths, `@` mention expansion and the App Server's `session.files.*` methods, are not calls the model makes and stay outside the roots. - **No absolute pass line and no CI run** (§8.1). diff --git a/docs/zh/design/model-prompts.md b/docs/zh/design/model-prompts.md index d1187a1039..2178b5e422 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -251,7 +251,7 @@ SessionTitle 不在范围内:它的 `SYSTEM`(`crates/dim-session-title/src/l **所有者:** 评估工具,`xtask`;在 [#550](https://github.com/arcships/dim/issues/550) 下实现。 - **一个场景运行器**,带 §8.1 的候选注入与检验:场景即用例,两臂都跑 shipped 装配,结果写进 PR。它逐次交错两臂,并接受 `--jobs` 与重复的 `--text`/`--candidate` 对,因此一个跨同一所有者两段文本的改动按它本来就是的一次改动来判定(Goal §A.5.2)。 -- **场景可以在运行中途移动默认分支。** `switch` 步骤按角色(`latest_tool_line`)或 id 指定目标线;运行器在那条线第一次 `turn/end` 之后、发下一条输入之前调用 `session.branch_set_default`。不点名线的输入落到默认分支,点名线的输入仍以那个目标为准。 +- **场景可以在运行中途移动默认分支。** `switch` 步骤按角色(`latest_tool_line`)或 id 指定目标线;运行器在那条线第一次 `turn/start` 时、发下一条输入之前调用 `session.branch_set_default`。线还没注册好时,移动会有限次重试;始终注册不上的线让这次运行以自己的结局结束。不点名线的输入落到默认分支,点名线的输入仍以那个目标为准。 - **已完成评估的运行可以重判,也可以合并报告。** `--rejudge DIR` 按这些运行保存的视图重新判定,不产生模型轮次,保留每次运行自身的结局,写入新的 `--out`;`--pool DIR` 把一次已完成评估的运行加入报告,该参数可以重复给出,从而把多次已完成评估的运行按同一规则与同一格式一起报告,不写入其中任何一个,而解析后落在某个来源内部的 `--out`(经由 `..` 或链接)会在创建任何东西之前被拒绝。这样的报告会列出它的来源,没有 text 行与 candidate-token 行;合并报告里的 model 与 judge 两行是收到的参数,每个来源自己的报告才写着它的运行是凭什么判的。这样的报告还会给出再次发送 decline 的次数,以及有多少运行没有记录该次数。 - **一次运行的文件根。** 每个 isolate 运行都以三类文件工具根提供服务:工作区,模型可读可写;一次性 home,`~` 解析到它,模型可读;以及平台固定的只读根,承载运行的命令要读取的工具链,例如解释器自身的安装目录。文件工具路径落在这些根之外时以 `outside_file_roots` 拒绝,且拒绝不触碰根外的任何内容。这些根约束模型的文件工具调用——`read`、`write`、`edit`、`glob`、`grep`;`exec` 由沙箱约束,而客户端发起的路径(`@` 提及展开与 App Server 的 `session.files.*` 方法)不是模型发起的调用,不在根内。 - **不用绝对通过线,不进 CI**(§8.1)。 diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 0975f5036a..c680bef6aa 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -975,6 +975,7 @@ fn pooled_record(source: &Path, run: SavedRun, scenarios: &[Scenario]) -> Result judge_calls: run.judge_calls, temperature_dropped: run.temperature_dropped, decline_retries: run.decline_retries, + switch_retries: run.switch_retries, events: run.events, reply_calls: run.reply_calls, probes, @@ -1072,6 +1073,7 @@ async fn rejudge_one( judge_calls: judging.calls, temperature_dropped: Some(judging.temperature_dropped), decline_retries: saved.decline_retries, + switch_retries: saved.switch_retries, events: saved.events.clone(), reply_calls: saved.reply_calls.clone(), probes: judging.probes, @@ -1114,6 +1116,11 @@ struct SavedRun { /// before the runner recorded it. #[serde(default)] decline_retries: Option, + /// How many times the runner moved again after the target line answered + /// `unknown_branch`; `None` in a record written before the runner + /// recorded it. + #[serde(default)] + switch_retries: Option, /// The events the run published, as the run recorded them; `None` in a /// record written before the runner published any. #[serde(default)] @@ -1213,6 +1220,7 @@ fn stop_name(stop: &str) -> Result<&'static str> { "seconds" => Ok("seconds"), "switch_target_not_reached" => Ok("switch_target_not_reached"), "switch_target_ended" => Ok("switch_target_ended"), + "switch_target_unknown" => Ok("switch_target_unknown"), "error" => Ok("error"), other => Err(format!("the saved run has an unknown stop {other}").into()), } @@ -1675,8 +1683,8 @@ struct ScenarioFile { probes: Vec, } -/// A scenario's mid-run move of the Session's default branch: after the -/// target line's first `turn/end`, the runner calls +/// A scenario's mid-run move of the Session's default branch: at the +/// target line's first `turn/start`, the runner calls /// `session.branch_set_default` and then sends the next input. A scenario /// without the step runs as before. #[derive(Clone, serde::Serialize, serde::Deserialize)] @@ -1710,11 +1718,21 @@ pub(crate) enum SwitchRole { LatestToolLine, } +/// How many further moves a switch makes while the target line is not +/// registered yet (`unknown_branch`): its first input starts the line's first +/// turn before the line is marked ready. +const UNKNOWN_BRANCH_RETRIES: u32 = 3; + /// A [`Switch`] as the run drives it: the target the role currently names, /// kept current while the switch is pending. struct PendingSwitch { switch: Switch, line: Option, + /// The target line's first `turn/start` has been seen: the move and the + /// next input happen now, or on a retry while the line is not ready. + triggered: bool, + /// The further attempts left while the move answers `unknown_branch`. + retries_left: u32, } impl PendingSwitch { fn new(switch: Switch) -> Self { @@ -1722,13 +1740,18 @@ impl PendingSwitch { SwitchTarget::Id(id) => Some(id.clone()), SwitchTarget::Role(_) => None, }; - Self { switch, line } + Self { + switch, + line, + triggered: false, + retries_left: UNKNOWN_BRANCH_RETRIES, + } } /// Reads one notice: a tool `branch/create` renames the role's target, and - /// the target's first `turn/end` is when the move and the next input + /// the target's first `turn/start` is when the move and the next input /// happen. - fn notice(&mut self, branch: &str, event: &Value) -> Option { + fn notice(&mut self, branch: &str, event: &Value) { if event["type"] == "branch" && event["name"] == "create" { if matches!( &self.switch.to, @@ -1738,13 +1761,14 @@ impl PendingSwitch { { self.line = Some(line.to_owned()); } - return None; + return; } - if event["type"] == "turn" && event["name"] == "end" && self.line.as_deref() == Some(branch) + if event["type"] == "turn" + && event["name"] == "start" + && self.line.as_deref() == Some(branch) { - return Some(branch.to_owned()); + self.triggered = true; } - None } } /// One source a scenario declares through the `eventHub` service, and @@ -2092,7 +2116,7 @@ struct RunRecord { run: usize, session: Option, /// `idle`, `turns`, `seconds`, `switch_target_not_reached`, - /// `switch_target_ended` or `error`. + /// `switch_target_ended`, `switch_target_unknown` or `error`. stop: &'static str, turns: u32, window: Option, @@ -2117,6 +2141,10 @@ struct RunRecord { /// How many declines the runner sent again after `question_not_pending`; /// `None` in a record written before the runner recorded it. decline_retries: Option, + /// How many times the runner moved again after the target line answered + /// `unknown_branch`; `None` in a record written before the runner + /// recorded it. + switch_retries: Option, /// One entry per event the run published, in order: the receipt EventHub /// answered (EventHub design A.2). A receipt that is not `delivered` /// fails the run and is recorded here as it came. @@ -2344,6 +2372,7 @@ struct ChildOutcome { window: Option, duration_ms: f64, decline_retries: u32, + switch_retries: u32, error: Option, judge_outcome: JudgeOutcome, judge_error: Option, @@ -2376,6 +2405,7 @@ fn harness_outcome(error: String, preflight: Vec) -> ChildOutcom window: None, duration_ms: 0., decline_retries: 0, + switch_retries: 0, error: None, judge_outcome: JudgeOutcome::NotAsked, judge_error: None, @@ -2768,6 +2798,7 @@ async fn child_drive( window: driven.window, duration_ms: 0., decline_retries: driven.decline_retries, + switch_retries: driven.switch_retries, error: driven.error, judge_outcome: judging.outcome, judge_error: judging.error, @@ -4277,6 +4308,7 @@ fn child_record( "seconds" => "seconds", "switch_target_not_reached" => "switch_target_not_reached", "switch_target_ended" => "switch_target_ended", + "switch_target_unknown" => "switch_target_unknown", _ => "error", }; let error = match &outcome.harness { @@ -4301,6 +4333,7 @@ fn child_record( judge_calls: outcome.judge_calls.clone(), temperature_dropped: Some(outcome.temperature_dropped), decline_retries: Some(outcome.decline_retries), + switch_retries: Some(outcome.switch_retries), events: outcome.events.clone(), reply_calls: outcome.reply_calls.clone(), probes: outcome @@ -4365,6 +4398,7 @@ impl Finished { turns: 0, window: None, decline_retries: 0, + switch_retries: 0, error: Some(error), }, export: None, @@ -4518,7 +4552,7 @@ async fn drive_once( fn failed(stop: &str, error: Option<&str>, judge_outcome: JudgeOutcome) -> bool { matches!( stop, - "seconds" | "switch_target_not_reached" | "switch_target_ended" + "seconds" | "switch_target_not_reached" | "switch_target_ended" | "switch_target_unknown" ) || error.is_some() || matches!( judge_outcome, @@ -4635,6 +4669,9 @@ struct Driven { window: Option, /// How many declines the runner sent again after `question_not_pending`. decline_retries: u32, + /// How many times the runner moved again after the target line answered + /// `unknown_branch`. + switch_retries: u32, error: Option, } @@ -4670,6 +4707,7 @@ async fn drive( turns: 0, window: None, decline_retries: 0, + switch_retries: 0, error: Some(error), }; } @@ -4692,6 +4730,7 @@ async fn drive( turns: 0, window: None, decline_retries: 0, + switch_retries: 0, error: Some(format!("session.create failed: {error}")), }; } @@ -4702,6 +4741,7 @@ async fn drive( turns: 0, window: None, decline_retries: 0, + switch_retries: 0, error: None, }; if let Err(error) = client @@ -4850,6 +4890,30 @@ async fn drive( driven.error = Some(error); return driven; } + match fire_switch(client, &session, &mut switch).await { + Ok(SwitchFire::Retry) => driven.switch_retries += 1, + Ok(SwitchFire::Fired) => awaiting = true, + Ok(SwitchFire::NotFired) => {} + Ok(SwitchFire::TargetEnded { line, error }) => { + driven.stop = "switch_target_ended"; + driven.error = Some(format!( + "line {line} ended before the switch could move to it: {error}" + )); + return driven; + } + Ok(SwitchFire::TargetUnknown { line, error }) => { + driven.stop = "switch_target_unknown"; + driven.error = Some(format!( + "line {line} was not ready for the switch after {UNKNOWN_BRANCH_RETRIES} retries: {error}" + )); + return driven; + } + Err(error) => { + driven.stop = "error"; + driven.error = Some(error); + return driven; + } + } // An `afterSubscribedSeconds` event whose clock has not started is // not pending: only a subscription of the model's can start it, so a // model that never subscribed cannot make it fire, and the run ends @@ -4919,21 +4983,8 @@ async fn drive( return driven; } } - match fire_switch(client, &session, &mut switch, &branch, &event).await { - Ok(SwitchFire::Fired) => awaiting = true, - Ok(SwitchFire::NotFired) => {} - Ok(SwitchFire::TargetEnded { line, error }) => { - driven.stop = "switch_target_ended"; - driven.error = Some(format!( - "line {line} ended before the switch could move to it: {error}" - )); - return driven; - } - Err(error) => { - driven.stop = "error"; - driven.error = Some(error); - return driven; - } + if let Some(pending) = switch.as_mut() { + pending.notice(&branch, &event); } match fire_triggered(client, &session, &mut steers, &event).await { Ok(submitted) => awaiting |= submitted, @@ -5033,7 +5084,7 @@ async fn drive( if let Some(pending) = &switch { let reason = match &pending.line { Some(line) => format!( - "the switch never fired: line {line}'s first turn did not end before the run stopped on {}", + "the switch never fired: line {line}'s first turn did not start before the run stopped on {}", driven.stop ), None => format!( @@ -5925,35 +5976,53 @@ impl SwitchClient for Client { /// What one notice did with the scenario's pending switch. #[derive(Debug)] enum SwitchFire { - /// The notice is not the trigger; the switch stays pending. + /// The target line has not started its first turn; the switch stays + /// pending. NotFired, /// The default branch moved and the next input was sent. Fired, + /// The target line's move answered `unknown_branch`: the line's first turn + /// started before the line was marked ready, so the run tries again. + Retry, /// The target line had already ended, or a line above it was ending, so /// the move answered `branch_ended` or `branch_target_protected`: the run /// stops with its own outcome rather than a harness error. TargetEnded { line: String, error: String }, + /// The move still answered `unknown_branch` after its retries: the run + /// stops with its own outcome rather than a harness error. + TargetUnknown { line: String, error: String }, } -/// Runs the scenario's switch when this notice is the target line's first -/// `turn/end`: the Session's default branch moves first, then the next input -/// is submitted, naming a line only when the scenario does. A switch fires -/// once, on the target line's first `turn/end`; a later notice leaves it -/// unfired. +/// The tree's `unknown_branch`, as the Session protocol answers it: the +/// invalid-input code with the tree's own message. A line's first input can +/// start its first turn before the line is marked ready, so the move can meet +/// this transient state. +fn unknown_branch(error: &dim_client::Error) -> bool { + dim_client::app_error(error) == Some("session_invalid_input") + && error + .downcast_ref::() + .is_some_and(|error| error.message.starts_with("unknown branch:")) +} + +/// Runs the scenario's switch once the target line has started its first turn: +/// the Session's default branch moves first, then the next input is submitted, +/// naming a line only when the scenario does. A switch fires once; a later +/// call leaves it unfired. async fn fire_switch( client: &mut impl SwitchClient, session: &str, switch: &mut Option, - branch: &str, - event: &Value, ) -> std::result::Result { let Some(pending) = switch.as_mut() else { return Ok(SwitchFire::NotFired); }; - let Some(line) = pending.notice(branch, event) else { + if !pending.triggered { return Ok(SwitchFire::NotFired); - }; - let pending = switch.take().expect("the switch is pending"); + } + let line = pending + .line + .clone() + .expect("a triggered switch names its line"); if let Err(error) = client .rpc( "session.branch_set_default", @@ -5961,16 +6030,27 @@ async fn fire_switch( ) .await { - match dim_client::app_error(&error) { - Some("branch_ended" | "branch_target_protected") => { - return Ok(SwitchFire::TargetEnded { - line: line.clone(), - error: error.to_string(), - }); + if let Some("branch_ended" | "branch_target_protected") = dim_client::app_error(&error) { + switch.take(); + return Ok(SwitchFire::TargetEnded { + line: line.clone(), + error: error.to_string(), + }); + } + if unknown_branch(&error) { + if pending.retries_left > 0 { + pending.retries_left -= 1; + return Ok(SwitchFire::Retry); } - _ => return Err(format!("the switch to {line} failed: {error}")), + switch.take(); + return Ok(SwitchFire::TargetUnknown { + line: line.clone(), + error: error.to_string(), + }); } + return Err(format!("the switch to {line} failed: {error}")); } + let pending = switch.take().expect("the switch is pending"); submit( client, session, @@ -7077,6 +7157,7 @@ mod tests { judge_calls: Vec::new(), temperature_dropped: Some(false), decline_retries: Some(0), + switch_retries: Some(0), events: Vec::new(), reply_calls: Vec::new(), probes: verdicts @@ -7304,12 +7385,13 @@ mod tests { let _ = std::fs::remove_dir_all(&directory); } - /// The move's trigger is the target line's first `turn/end`: a tool + /// The move's trigger is the target line's first `turn/start`: a tool /// `branch/create` names the role's latest line, and another line's turn /// does not fire it. The run drops the switch after the move, so one /// scenario switches once. #[test] - fn a_switch_fires_on_the_target_lines_first_turn_end() { + fn a_switch_fires_on_the_target_lines_first_turn_start() { + let turn_start = json!({"type": "turn", "name": "start", "data": {}}); let turn_end = json!({"type": "turn", "name": "end", "data": {}}); let create = |branch: &str, kind: &str| { json!({"type": "branch", "name": "create", @@ -7320,24 +7402,27 @@ mod tests { message: "next".into(), branch_id: None, }); - assert_eq!(pending.notice("main", &turn_end), None); - assert_eq!(pending.notice("main", &create("2", "tool")), None); - assert_eq!(pending.notice("2", &turn_end), Some("2".into())); + pending.notice("main", &turn_start); + assert!(!pending.triggered, "main's turn starts no switch"); + pending.notice("main", &create("2", "tool")); + assert!(!pending.triggered, "opening the line is not its turn"); + pending.notice("2", &turn_end); + assert!(!pending.triggered, "a turn end is not the trigger"); + pending.notice("2", &turn_start); + assert!(pending.triggered, "the target's first turn start is"); + assert_eq!(pending.line.as_deref(), Some("2")); let mut pending = PendingSwitch::new(Switch { to: SwitchTarget::Role(SwitchRole::LatestToolLine), message: "next".into(), branch_id: None, }); pending.notice("main", &create("2", "tool")); - assert_eq!( - pending.notice("3", &turn_end), - None, - "another line's turn ends no switch" - ); + pending.notice("3", &turn_start); + assert!(!pending.triggered, "another line's turn starts no switch"); pending.notice("main", &create("3", "user")); - assert_eq!( - pending.notice("3", &turn_end), - None, + pending.notice("3", &turn_start); + assert!( + !pending.triggered, "a line the user opened is not a tool line" ); let mut pending = PendingSwitch::new(Switch { @@ -7345,43 +7430,59 @@ mod tests { message: "next".into(), branch_id: None, }); - assert_eq!(pending.notice("4", &turn_end), Some("4".into())); + pending.notice("4", &turn_start); + assert!(pending.triggered); } - /// The switch's calls, recorded, and the refusal its first call answers; - /// no Session stands behind it. + /// The switch's calls, recorded, and the refusals its + /// `session.branch_set_default` calls answer, in order; no Session stands + /// behind it. #[derive(Default)] struct SwitchRecorder { calls: Vec<(String, Value)>, - refusal: Option, + refusals: Vec, } impl SwitchClient for SwitchRecorder { async fn rpc(&mut self, method: &str, params: Value) -> dim_client::Result { self.calls.push((method.to_owned(), params)); - match self.calls.len() { - 1 => match self.refusal.take() { - Some(refusal) => Err(refusal.into()), - None => Ok(json!({})), - }, - _ => Ok(json!({})), + if method == "session.branch_set_default" && !self.refusals.is_empty() { + return Err(self.refusals.remove(0).into()); } + Ok(json!({})) + } + } + + /// A switch whose target has started its first turn, ready to move. + fn triggered_switch() -> Option { + let mut pending = PendingSwitch::new(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + }); + pending.notice("2", &json!({"type": "turn", "name": "start", "data": {}})); + assert!(pending.triggered); + Some(pending) + } + + /// The tree's `unknown_branch` as the Session protocol answers it: the + /// invalid-input code carrying the tree's message. + fn unknown_branch_refusal() -> dim_client::RpcError { + dim_client::RpcError { + code: -32000, + message: "unknown branch: 2".into(), + data: Some(json!({"appError": "session_invalid_input"})), } } /// A switch moves the Session's default branch before it sends the next - /// input, and fires once: after the move the switch is gone, so the - /// target's later `turn/end` sends nothing (model-prompts §9.8). + /// input, and fires once: after the move the switch is gone, so a later + /// call leaves it unfired (model-prompts §9.8). #[tokio::test] async fn a_switch_moves_the_default_branch_before_its_next_input_and_fires_once() { let mut client = SwitchRecorder::default(); - let mut switch = Some(PendingSwitch::new(Switch { - to: SwitchTarget::Id("2".into()), - message: "next".into(), - branch_id: None, - })); - let turn_end = json!({"type": "turn", "name": "end", "data": {}}); + let mut switch = triggered_switch(); assert!(matches!( - fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await, + fire_switch(&mut client, "session", &mut switch).await, Ok(SwitchFire::Fired) )); let calls: Vec<&str> = client @@ -7401,7 +7502,7 @@ mod tests { "the next input lands on the new default branch" ); assert!(matches!( - fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await, + fire_switch(&mut client, "session", &mut switch).await, Ok(SwitchFire::NotFired) )); assert_eq!(client.calls.len(), 2, "a switch fires once"); @@ -7411,20 +7512,15 @@ mod tests { #[tokio::test] async fn a_refused_switch_move_propagates_its_error_and_sends_no_input() { let mut client = SwitchRecorder { - refusal: Some(dim_client::RpcError { + refusals: vec![dim_client::RpcError { code: -32000, message: "the tree is closing".into(), data: Some(json!({"appError": "session_closed"})), - }), + }], ..SwitchRecorder::default() }; - let mut switch = Some(PendingSwitch::new(Switch { - to: SwitchTarget::Id("2".into()), - message: "next".into(), - branch_id: None, - })); - let turn_end = json!({"type": "turn", "name": "end", "data": {}}); - let error = match fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await { + let mut switch = triggered_switch(); + let error = match fire_switch(&mut client, "session", &mut switch).await { Err(error) => error, Ok(outcome) => panic!("the move was refused, not {outcome:?}"), }; @@ -7437,6 +7533,86 @@ mod tests { ); } + /// A move that meets the line before it is ready retries: one + /// `unknown_branch` leaves the switch pending, and the next call moves and + /// submits (model-prompts §9.8). + #[tokio::test] + async fn an_unknown_branch_move_retries_until_the_line_is_ready() { + let mut client = SwitchRecorder { + refusals: vec![unknown_branch_refusal()], + ..SwitchRecorder::default() + }; + let mut switch = triggered_switch(); + assert!(matches!( + fire_switch(&mut client, "session", &mut switch).await, + Ok(SwitchFire::Retry) + )); + assert!(switch.is_some(), "the switch stays pending for the retry"); + assert!(matches!( + fire_switch(&mut client, "session", &mut switch).await, + Ok(SwitchFire::Fired) + )); + let calls: Vec<&str> = client + .calls + .iter() + .map(|(method, _)| method.as_str()) + .collect(); + assert_eq!( + calls, + [ + "session.branch_set_default", + "session.branch_set_default", + "session.submit" + ], + "the retry moves before it sends the next input" + ); + assert_eq!(client.calls[2].1["text"], "next"); + assert!(switch.is_none()); + } + + /// A line that never becomes ready is its own outcome after the retry + /// budget, not a harness error (model-prompts §9.8). + #[tokio::test] + async fn a_target_that_never_becomes_ready_is_its_own_outcome() { + let mut client = SwitchRecorder { + refusals: (0..=UNKNOWN_BRANCH_RETRIES) + .map(|_| unknown_branch_refusal()) + .collect(), + ..SwitchRecorder::default() + }; + let mut switch = triggered_switch(); + for retry in 0..UNKNOWN_BRANCH_RETRIES { + assert!( + matches!( + fire_switch(&mut client, "session", &mut switch).await, + Ok(SwitchFire::Retry) + ), + "retry {retry}" + ); + assert!(switch.is_some(), "retry {retry}: still pending"); + } + match fire_switch(&mut client, "session", &mut switch).await { + Ok(SwitchFire::TargetUnknown { line, error }) => { + assert_eq!(line, "2"); + assert!(error.contains("unknown branch"), "{error}"); + } + outcome => panic!("the unready target is its own outcome, not {outcome:?}"), + } + assert!(switch.is_none()); + assert_eq!( + client.calls.len(), + UNKNOWN_BRANCH_RETRIES as usize + 1, + "the first move and every retry" + ); + assert!( + client + .calls + .iter() + .all(|(method, _)| method == "session.branch_set_default"), + "no input is sent to a line that never became ready" + ); + } + /// A target line that ended, or whose chain was ending, before the move is /// its own outcome, read from the refusal's application code rather than /// its text, and not a harness error (design §14, §20.26a; model-prompts @@ -7448,20 +7624,15 @@ mod tests { ("branch_target_protected", "line 2 is ending or ended"), ] { let mut client = SwitchRecorder { - refusal: Some(dim_client::RpcError { + refusals: vec![dim_client::RpcError { code: -32000, message: message.into(), data: Some(json!({"appError": code})), - }), + }], ..SwitchRecorder::default() }; - let mut switch = Some(PendingSwitch::new(Switch { - to: SwitchTarget::Id("2".into()), - message: "next".into(), - branch_id: None, - })); - let turn_end = json!({"type": "turn", "name": "end", "data": {}}); - match fire_switch(&mut client, "session", &mut switch, "2", &turn_end).await { + let mut switch = triggered_switch(); + match fire_switch(&mut client, "session", &mut switch).await { Ok(SwitchFire::TargetEnded { line, error }) => { assert_eq!(line, "2"); assert!(error.contains(code), "{code}: {error}"); @@ -11087,6 +11258,9 @@ mod tests { /// then answers that one and every later one as idle at /// [`PEER_SEQUENCE`]. HeldIdle, + /// The submitted turn starts and ends on `main`, and no other line is + /// ever opened: a scenario's switch can never reach its target. + SwitchNeverFires, } /// What a scripted peer read: the `requestId` of every decline, in order, @@ -11340,6 +11514,7 @@ mod tests { write.write_all(&frame(&request, body)).await.unwrap(); (declines == 3).then_some(("r1", 1)) } + PeerScript::SwitchNeverFires => None, }; if let Some((request, sequence)) = closed { if recorded.settled_at.load(Ordering::SeqCst) == 0 { @@ -11368,8 +11543,16 @@ mod tests { .await .unwrap(); // The held line asks nothing: the run's only work is the - // turn the peer holds open. - if matches!(script, PeerScript::HeldIdle) { + // turn the peer holds open. A switch that never fires + // likewise asks nothing: its turn starts and ends. + if matches!(script, PeerScript::HeldIdle | PeerScript::SwitchNeverFires) { + if matches!(script, PeerScript::SwitchNeverFires) { + write + .write_all(¬ice(json!({"type": "turn", "name": "end", + "sequence": 2, "data": {}}))) + .await + .unwrap(); + } continue; } let request = match &script { @@ -11463,6 +11646,53 @@ mod tests { ); } + /// 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 + /// (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_switch_that_never_fires_is_a_failed_outcome() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-switch-never-{}", + std::process::id() + )); + let (socket, _) = scripted_peer(&directory, 8_000, PeerScript::SwitchNeverFires).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.turns = 1; + scenario.budget.seconds = 10.; + scenario.switch = Some(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + }); + let driven = drive( + &mut client, + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let _ = std::fs::remove_dir_all(directory); + assert_eq!( + driven.stop, "switch_target_not_reached", + "{:?}", + driven.error + ); + let error = driven.error.as_deref().unwrap_or_default(); + assert!( + error.contains("line 2") && error.contains("turns"), + "{error}" + ); + assert!( + failed(driven.stop, None, JudgeOutcome::Judged), + "the outcome is a failed run on its own" + ); + } + /// A busy line does not multiply the declines: the peer refuses the first /// decline and streams a burst of unrelated notices at once, and the /// runner answers the decline again only once the quiet period has From 2122eecc8217b59ea1e6308c94b54281a599df99 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 09:51:15 +0800 Subject: [PATCH 09/32] test(branch): compact at a 29,000-token window Declare 29,000 for identity-after-compaction and update its window assertion and the design text in both languages. The window is chosen so the compaction trigger sits below the request peaks the scenario reaches. --- docs/design/timeline-branches.md | 2 +- docs/zh/design/timeline-branches.md | 2 +- .../identity-after-compaction/scenario.json | 2 +- xtask/src/scenario_eval.rs | 8 ++++---- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index e868605bd0..82284c4bb5 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -510,7 +510,7 @@ The requirements that answer these items are in [Model-facing prompts](model-pro ### 12.3 Evaluation scenarios -The set lives in the repository, one directory per scenario, holding a `scenario.json` and the starting `workspace/` beside it: fifteen under [`xtask/scenario-eval/timeline-branches/`](../../xtask/scenario-eval/timeline-branches/), each declaring a window of 131,072 tokens, and `identity-after-compaction` under [`xtask/scenario-eval/timeline-branches-compact/`](../../xtask/scenario-eval/timeline-branches-compact/), declaring 16,000 so that compaction happens. `budget.window` is a check, not a setting: a run whose Session declares another window fails before its first turn, so a rerun needs a model that declares exactly the scenario's window, and a model that declares none falls back to 128,000 and fails too. These are run locally on real models, and the results are reported in the implementation PR. CI asserts only behavior. +The set lives in the repository, one directory per scenario, holding a `scenario.json` and the starting `workspace/` beside it: fifteen under [`xtask/scenario-eval/timeline-branches/`](../../xtask/scenario-eval/timeline-branches/), each declaring a window of 131,072 tokens, and `identity-after-compaction` under [`xtask/scenario-eval/timeline-branches-compact/`](../../xtask/scenario-eval/timeline-branches-compact/), declaring 29,000 so that compaction happens. `budget.window` is a check, not a setting: a run whose Session declares another window fails before its first turn, so a rerun needs a model that declares exactly the scenario's window, and a model that declares none falls back to 128,000 and fails too. These are run locally on real models, and the results are reported in the implementation PR. CI asserts only behavior. `main-moved-on` is the scenario for the parent block (§7.1.1): `main` works before the cut, opens a line, then keeps working; the line must read what `main` did after the cut before it answers or ends, and it must not page through all of `main`'s activity. It is the scenario for [§12.4](#124-texts-and-their-classes)'s parent-block policy sentence. diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 001d2ea9b7..d6a0a4e525 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -476,7 +476,7 @@ WorkspaceTools 不变。 ### 12.3 评估场景 -场景放在仓库里,一个场景一个目录,目录里是 `scenario.json` 和它旁边的起始 `workspace/`:十五个在 [`xtask/scenario-eval/timeline-branches/`](../../../xtask/scenario-eval/timeline-branches/) 下,各自声明 131,072 tokens 的窗口;`identity-after-compaction` 在 [`xtask/scenario-eval/timeline-branches-compact/`](../../../xtask/scenario-eval/timeline-branches-compact/) 下,声明 16,000,以便发生压缩。`budget.window` 是校验而不是设置:Session 声明的窗口与之不同时,这次运行在第一轮之前就失败,所以复跑需要模型声明正好这个窗口;没有声明窗口的模型回退到 128,000,同样失败。这些场景在本地用真实模型运行,结果在实现 PR 里报告。CI 只断言行为。 +场景放在仓库里,一个场景一个目录,目录里是 `scenario.json` 和它旁边的起始 `workspace/`:十五个在 [`xtask/scenario-eval/timeline-branches/`](../../../xtask/scenario-eval/timeline-branches/) 下,各自声明 131,072 tokens 的窗口;`identity-after-compaction` 在 [`xtask/scenario-eval/timeline-branches-compact/`](../../../xtask/scenario-eval/timeline-branches-compact/) 下,声明 29,000,以便发生压缩。`budget.window` 是校验而不是设置:Session 声明的窗口与之不同时,这次运行在第一轮之前就失败,所以复跑需要模型声明正好这个窗口;没有声明窗口的模型回退到 128,000,同样失败。这些场景在本地用真实模型运行,结果在实现 PR 里报告。CI 只断言行为。 `main-moved-on` 是父线块(§7.1.1)的场景:`main` 在切点之前有工作,开一条线,然后继续工作;这条线在回答或结束之前必须读取 `main` 在切点之后做的事,并且不能逐页读遍 `main` 的全部活动。它是 [§12.4](#124-文本及其类别) 父线块策略句的场景。 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 d90aeea6c1..4e21a09a6c 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,7 +1,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.", - "budget": {"turns": 30, "seconds": 900, "window": 16000}, + "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": "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 c680bef6aa..7b27516a1f 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -83,8 +83,8 @@ //! "providers": [ //! {"id": "run", "kind": "openai-chat", "apiKeyEnv": "MODEL_KEY", //! "baseUrl": "https://example.invalid/v1", -//! "models": [{"id": "model-a", "contextWindow": 16000, -//! "maxOutputTokens": 1024, "config": {"maxTokens": 1024}}]}, +//! "models": [{"id": "model-a", "contextWindow": 29000, +//! "maxOutputTokens": 8192, "config": {"maxTokens": 8192}}]}, //! {"id": "judge", "kind": "openai-chat", "apiKeyEnv": "MODEL_KEY", //! "baseUrl": "https://example.invalid/v1", //! "models": [{"id": "model-a", "contextWindow": 1048576, @@ -93,7 +93,7 @@ //! } //! ``` //! -//! The run model above is declared for the scenarios' 16,000-token window and +//! The run model above is declared for the scenarios' 29,000-token window and //! the same upstream model judges with its own 1,048,576-token window, so //! `--judge judge/model-a` reads a view of that size in one call. //! @@ -7706,7 +7706,7 @@ mod tests { } assert_eq!( find(&compact, "identity-after-compaction").budget.window, - 16_000, + 29_000, "the compact scenario declares the window that compacts it" ); for scenario in &branches { From 39332c6cf654d33f64253e6b6076da46ad488804 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 11:09:38 +0800 Subject: [PATCH 10/32] docs(xtask): follow the new switch trigger in a test comment --- xtask/src/scenario_eval.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 7b27516a1f..aca28b1d5b 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -7336,8 +7336,8 @@ mod tests { } /// A switch names the line to move to by role or by id, and the input - /// after the move; the runner moves the default branch after the target - /// line's first `turn/end` (model-prompts §9.8). + /// after the move; the runner moves the default branch at the target + /// line's first `turn/start` (model-prompts §9.8). #[test] fn a_switch_step_names_a_line_and_its_next_input() { let directory = From 318d81eb6be3044628cd3b2538be1c4f9da6541d Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 11:51:41 +0800 Subject: [PATCH 11/32] fix(xtask): report a switch the budget stops after its trigger The wrap-up after a run stopped on its turn or wall-clock budget did not tell an untriggered switch from a triggered one: a move that kept answering `unknown_branch` while its retries were unspent was reported as "the first turn did not start", which the target's own `turn/start` contradicts. Report the unfinished move instead. The test drives a scripted peer whose target line starts and ends its first turn and whose `session.branch_set_default` answers `unknown_branch`, and stops the run on its turn budget with retries left. It fails on the previous wording with that reason. --- xtask/src/scenario_eval.rs | 101 ++++++++++++++++++++++++++++++++++--- 1 file changed, 95 insertions(+), 6 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index aca28b1d5b..0e958ad66e 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -5082,12 +5082,16 @@ async fn drive( } } if let Some(pending) = &switch { - let reason = match &pending.line { - Some(line) => format!( + let reason = match (&pending.line, pending.triggered) { + (Some(line), true) => format!( + "the move to line {line} did not complete before the run stopped on {}", + driven.stop + ), + (Some(line), false) => format!( "the switch never fired: line {line}'s first turn did not start before the run stopped on {}", driven.stop ), - None => format!( + (None, _) => format!( "the switch never fired: no tool line was opened before the run stopped on {}", driven.stop ), @@ -11261,6 +11265,10 @@ mod tests { /// The submitted turn starts and ends on `main`, and no other line is /// ever opened: a scenario's switch can never reach its target. SwitchNeverFires, + /// The target line `2` starts and ends its first turn, and every move + /// to it answers `unknown_branch`: the run can stop on its budget + /// while the switch still has retries left. + SwitchMoveRetries, } /// What a scripted peer read: the `requestId` of every decline, in order, @@ -11306,13 +11314,17 @@ mod tests { } format!("{frame}\n").into_bytes() } - /// One `session.event` notice of `event`. - fn notice(event: Value) -> Vec { + /// One `session.event` notice of `event` on `branch`. + fn notice_on(branch: &str, event: Value) -> Vec { let notice = json!({"jsonrpc": "2.0", "method": "session.event", - "params": {"sessionId": "peer", "branchId": "main", + "params": {"sessionId": "peer", "branchId": branch, "event": event}}); format!("{notice}\n").into_bytes() } + /// One `session.event` notice of `event` on `main`. + fn notice(event: Value) -> Vec { + notice_on("main", event) + } /// The refusal a client gets while the call has no waiter. fn not_pending() -> Value { json!({"error": {"code": -32000, "message": "No ask_user call is waiting for this answer", @@ -11515,6 +11527,7 @@ mod tests { (declines == 3).then_some(("r1", 1)) } PeerScript::SwitchNeverFires => None, + PeerScript::SwitchMoveRetries => None, }; if let Some((request, sequence)) = closed { if recorded.settled_at.load(Ordering::SeqCst) == 0 { @@ -11532,6 +11545,12 @@ mod tests { "session.create" => json!({"result": {"sessionId": "peer"}}), "session.context.usage" => json!({"result": {"contextWindow": window}}), "session.idle" => json!({"result": {"sequence": PEER_SEQUENCE}}), + "session.branch_set_default" + if matches!(script, PeerScript::SwitchMoveRetries) => + { + json!({"error": {"code": -32000, "message": "unknown branch: 2", + "data": {"appError": "session_invalid_input"}}}) + } _ => json!({"result": {}}), }; write.write_all(&frame(&request, body)).await.unwrap(); @@ -11555,6 +11574,19 @@ mod tests { } continue; } + if matches!(script, PeerScript::SwitchMoveRetries) { + for (name, sequence) in [("start", 1), ("end", 2)] { + write + .write_all(¬ice_on( + "2", + json!({"type": "turn", "name": name, + "sequence": sequence, "data": {}}), + )) + .await + .unwrap(); + } + continue; + } let request = match &script { PeerScript::Unkeyed => None, _ => Some("r1"), @@ -11693,6 +11725,63 @@ mod tests { ); } + /// A switch whose target has started its first turn is not reported as + /// one that never fired: when the move keeps answering `unknown_branch` + /// and the run stops on its budget, the run records the unfinished move + /// (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_switch_the_budget_stops_after_its_trigger_reports_the_move() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-switch-retry-{}", + std::process::id() + )); + let (socket, _) = scripted_peer(&directory, 8_000, PeerScript::SwitchMoveRetries).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.turns = 1; + scenario.budget.seconds = 10.; + scenario.switch = Some(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + }); + let driven = drive( + &mut client, + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let _ = std::fs::remove_dir_all(directory); + assert_eq!( + driven.stop, "switch_target_not_reached", + "{:?}", + driven.error + ); + let error = driven.error.as_deref().unwrap_or_default(); + assert!( + error.contains("line 2") + && error.contains("did not complete") + && error.contains("turns"), + "{error}" + ); + assert!( + !error.contains("first turn did not start"), + "the target's first turn started: {error}" + ); + assert!( + driven.switch_retries >= 1, + "the move was retried while the line was not registered" + ); + assert!( + failed(driven.stop, None, JudgeOutcome::Judged), + "the outcome is a failed run on its own" + ); + } + /// A busy line does not multiply the declines: the peer refuses the first /// decline and streams a burst of unrelated notices at once, and the /// runner answers the decline again only once the quiet period has From 591ae8b0441bae77d39c12a88b14c59c7cf8f701 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 13:25:24 +0800 Subject: [PATCH 12/32] fix(xtask): keep a triggered switch on the line that started A switch names its target by role, which moves to each tool `branch/create` until the target's first `turn/start`. A run could meet `unknown_branch` on the first move, then read a later line's create and promote that line before its own first turn, sending the scenario's next input to a line with another purpose. The line whose first turn started now keeps the switch: a later create no longer renames the target, so the retry and the next input stay with the line the scenario meant. The test starts A, retries the move, then reads B's create and asserts the retry promotes A. --- xtask/src/scenario_eval.rs | 67 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 0e958ad66e..561eca4836 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -1724,7 +1724,7 @@ pub(crate) enum SwitchRole { const UNKNOWN_BRANCH_RETRIES: u32 = 3; /// A [`Switch`] as the run drives it: the target the role currently names, -/// kept current while the switch is pending. +/// kept current while the switch is pending and that target has not started. struct PendingSwitch { switch: Switch, line: Option, @@ -1750,8 +1750,13 @@ impl PendingSwitch { /// Reads one notice: a tool `branch/create` renames the role's target, and /// the target's first `turn/start` is when the move and the next input - /// happen. + /// happen. Once that turn has started the target is fixed: a line opened + /// afterwards has its own purpose, and the move and the input after it + /// stay with the line that started. fn notice(&mut self, branch: &str, event: &Value) { + if self.triggered { + return; + } if event["type"] == "branch" && event["name"] == "create" { if matches!( &self.switch.to, @@ -7438,6 +7443,64 @@ mod tests { assert!(pending.triggered); } + /// 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). + #[tokio::test] + async fn a_retried_switch_stays_on_the_line_that_started() { + let create = |line: &str| { + json!({"type": "branch", "name": "create", + "data": {"branch": line, "source": {"kind": "tool"}}}) + }; + let turn_start = json!({"type": "turn", "name": "start", "data": {}}); + let mut switch = Some(PendingSwitch::new(Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "next".into(), + branch_id: None, + })); + let pending = switch.as_mut().expect("the switch is pending"); + pending.notice("main", &create("A")); + pending.notice("A", &turn_start); + assert!(pending.triggered); + let mut client = SwitchRecorder { + refusals: vec![unknown_branch_refusal()], + ..SwitchRecorder::default() + }; + assert!(matches!( + fire_switch(&mut client, "session", &mut switch).await, + Ok(SwitchFire::Retry) + )); + let pending = switch.as_mut().expect("the retry keeps the switch"); + pending.notice("main", &create("B")); + assert_eq!( + pending.line.as_deref(), + Some("A"), + "the line that started keeps the move" + ); + assert!(matches!( + fire_switch(&mut client, "session", &mut switch).await, + Ok(SwitchFire::Fired) + )); + let calls: Vec<&str> = client + .calls + .iter() + .map(|(method, _)| method.as_str()) + .collect(); + assert_eq!( + calls, + [ + "session.branch_set_default", + "session.branch_set_default", + "session.submit" + ], + "the retry moves before it sends the next input" + ); + assert_eq!( + client.calls[1].1["branchId"], "A", + "the retry promotes the line that started, not the line opened after it" + ); + } + /// The switch's calls, recorded, and the refusals its /// `session.branch_set_default` calls answer, in order; no Session stands /// behind it. From 01e5b2a42d8b144de3be91dd86d9fc0d47167a29 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 13:25:38 +0800 Subject: [PATCH 13/32] test(branch): require the new default to open a line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `switch-then-open-lines` asks for two independent additions after the move, but its probes only checked that both were done and that the former default branch left them alone: a run that did both on the new default branch itself passed. The new `new-default-opens-a-line` probe requires that line to open a line for one of the two additions. The scenario set test pins the probe, and §12.3 gains a row naming what the scenario watches for, in both languages. --- docs/design/timeline-branches.md | 1 + docs/zh/design/timeline-branches.md | 1 + .../switch-then-open-lines/scenario.json | 1 + xtask/src/scenario_eval.rs | 9 +++++++++ 4 files changed, 12 insertions(+) diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index 3fd6c2595b..f636b2df77 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -532,6 +532,7 @@ The opening and switching roles add seven scenarios: `long-work-and-a-flaky-test | 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 | | 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 | | Ping-pong | `timeline-branches/ping-pong` | Steer exchanges that do not move the work forward | | Asking the user | `timeline-branches/asking-the-user` | A line asks the user directly when it should, and does not route through `main` | diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 6c2ac8a119..07d0c2711f 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -498,6 +498,7 @@ WorkspaceTools 不变。 | 兄弟中转 | `timeline-branches/sibling-relay` | 用 `main` 在本该合成一条线的几条线之间传话 | | 压缩后的身份 | `timeline-branches-compact/identity-after-compaction` | `main` 和某条线各自压缩之后,仍知道自己是哪条线、哪些线是自己的 | | 切换后继续在线上工作 | — | 成为默认分支的线对自己调用 `end`、把工作交给另一条线、不断用 idle 通知唤醒开它的线,或者根能开线而这条线不能 | +| 切换后开线 | `timeline-branches/switch-then-open-lines` | 新的默认分支自己做掉两处互不相干的新增,而不是为其中一处开一条线;或者原默认分支接过新工作 | | 线持有角色时根开线 | `timeline-branches/root-opens-after-switch` | 另一条线成为默认分支后,用户向根要一条线:根必须开这条线,新线必须从根的历史开始,并向根汇报 | | 来回空转 | `timeline-branches/ping-pong` | 不推进工作的 steer 往复 | | 问用户 | `timeline-branches/asking-the-user` | 该问用户时,线直接问用户,而不是绕道 `main` | diff --git a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json index fb73e7f120..496ac79b48 100644 --- a/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json @@ -9,6 +9,7 @@ "probes": [ {"id": "both-additions-work", "kind": "must_show", "text": "the --leeway option and the CSV export are implemented, with tests and help text"}, {"id": "former-default-leaves-the-new-work", "kind": "must_not_show", "text": "after the switch, the former default branch opens a line for the new default branch's work or edits auth/token.py, cli/login.py, or audit/exporter.py"}, + {"id": "new-default-opens-a-line", "kind": "must_show", "text": "after the switch, the new default branch opens at least one line for one of the two additions, either --leeway in cli/login.py or CSV output in audit/exporter.py"}, {"id": "bug-fixed-with-test", "kind": "must_show", "text": "the early-expiry bug is fixed and a test covers it"} ] } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 561eca4836..16dd560721 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -7809,6 +7809,15 @@ mod tests { .is_some_and(|switch| switch.branch_id.as_deref() == Some("main")), "root-opens-after-switch names the root after the move" ); + assert!( + find(&branches, "switch-then-open-lines") + .probes + .iter() + .any(|probe| { + probe.id == "new-default-opens-a-line" && probe.kind == ProbeKind::MustShow + }), + "switch-then-open-lines requires the new default branch to open a line" + ); let redone = find(&branches, "redone-work"); let identity = find(&compact, "identity-after-compaction"); assert_eq!( From 631febaf7fbcee31920a58a9b4450ea3af54222e Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 13:25:48 +0800 Subject: [PATCH 14/32] fix(xtask): bound a switch by the scenario deadline The run called `session.branch_set_default` and submitted the next input before it checked its wall clock. Both calls go through `Client::rpc`, which waits on an open connection, so a reply that never came left the run without an outcome and held its worker indefinitely. The switch now runs inside the same absolute deadline the budget check uses, counted from the first submission. When that deadline passes first, the run records `seconds` with an error naming the line, instead of waiting on the connection. The scripted peer gains two stalling scripts, a move that never answers and a submit that never answers; the test asserts both stop on the deadline and return. --- xtask/src/scenario_eval.rs | 119 ++++++++++++++++++++++++++++++++++++- 1 file changed, 117 insertions(+), 2 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 16dd560721..016f65ef2b 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -4895,7 +4895,33 @@ async fn drive( driven.error = Some(error); return driven; } - match fire_switch(client, &session, &mut switch).await { + // The move and the input after it are bounded by the same absolute + // deadline the budget check below applies: a reply that never comes + // must not hold the run past its wall clock (model-prompts §8.1). + let line = switch.as_ref().and_then(|pending| pending.line.clone()); + let fired = match tokio::time::timeout( + time_left(started, &scenario.budget), + fire_switch(client, &session, &mut switch), + ) + .await + { + Ok(fired) => fired, + Err(_) => { + driven.stop = "seconds"; + driven.error = Some(match line { + Some(line) => format!( + "the switch to line {line} did not answer before the run's {}s budget ran out", + scenario.budget.seconds + ), + None => format!( + "the switch did not answer before the run's {}s budget ran out", + scenario.budget.seconds + ), + }); + return driven; + } + }; + match fired { Ok(SwitchFire::Retry) => driven.switch_retries += 1, Ok(SwitchFire::Fired) => awaiting = true, Ok(SwitchFire::NotFired) => {} @@ -6119,6 +6145,12 @@ async fn fire_triggered( Ok(sent) } +/// The wall clock left of the scenario's budget, counted from the first +/// submission; a run past its budget has none left. +fn time_left(started: Instant, budget: &Budget) -> Duration { + Duration::from_secs_f64((budget.seconds - started.elapsed().as_secs_f64()).max(0.)) +} + /// How long to wait for the next notice: until the next timed steer, the /// quiet check or the wall-clock budget, whichever comes first. fn wait_time( @@ -11341,6 +11373,13 @@ mod tests { /// to it answers `unknown_branch`: the run can stop on its budget /// while the switch still has retries left. SwitchMoveRetries, + /// The target line `2` starts and ends its first turn, and the move to + /// it never answers: the run must stop on its deadline instead of + /// waiting on the reply. + SwitchMoveStalls, + /// The target line `2` starts and ends its first turn and the move + /// answers, and the input after the move never does. + SwitchSubmitStalls, } /// What a scripted peer read: the `requestId` of every decline, in order, @@ -11460,6 +11499,9 @@ mod tests { _ => Vec::new(), }; let mut declines = 0; + // The `session.submit` calls read so far: the stalling scripts + // hold the one after the move. + let mut submits = 0; let mut first: Option = None; // The line is busy until the peer writes the call's result, the // way a running turn is: `session.idle` stays unanswered and the @@ -11600,6 +11642,7 @@ mod tests { } PeerScript::SwitchNeverFires => None, PeerScript::SwitchMoveRetries => None, + PeerScript::SwitchMoveStalls | PeerScript::SwitchSubmitStalls => None, }; if let Some((request, sequence)) = closed { if recorded.settled_at.load(Ordering::SeqCst) == 0 { @@ -11613,6 +11656,19 @@ mod tests { } continue; } + // The stalling scripts hold their reply: the move in one, the + // input after it in the other. + if method == "session.branch_set_default" + && matches!(script, PeerScript::SwitchMoveStalls) + { + continue; + } + if method == "session.submit" { + submits += 1; + if submits > 1 && matches!(script, PeerScript::SwitchSubmitStalls) { + continue; + } + } let body = match method { "session.create" => json!({"result": {"sessionId": "peer"}}), "session.context.usage" => json!({"result": {"contextWindow": window}}), @@ -11646,7 +11702,12 @@ mod tests { } continue; } - if matches!(script, PeerScript::SwitchMoveRetries) { + if matches!( + script, + PeerScript::SwitchMoveRetries + | PeerScript::SwitchMoveStalls + | PeerScript::SwitchSubmitStalls + ) { for (name, sequence) in [("start", 1), ("end", 2)] { write .write_all(¬ice_on( @@ -11854,6 +11915,60 @@ mod tests { ); } + /// A switch call that never answers is bounded by the scenario's wall + /// clock: the run records the timeout and returns instead of waiting on + /// the connection, so its worker is released (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_stalled_switch_call_stops_on_the_scenario_deadline() { + /// A run that has not returned by now waited on the reply. + const GUARD: Duration = Duration::from_secs(10); + for (script, name) in [ + (PeerScript::SwitchMoveStalls, "move"), + (PeerScript::SwitchSubmitStalls, "submit"), + ] { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-switch-stall-{name}-{}", + std::process::id() + )); + let (socket, _) = scripted_peer(&directory, 8_000, script).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.seconds = 0.5; + scenario.switch = Some(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + }); + let driven = tokio::time::timeout( + GUARD, + drive( + &mut client, + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ), + ) + .await + .unwrap_or_else(|_| panic!("{name}: the run waited on a reply that never came")); + let _ = std::fs::remove_dir_all(directory); + assert_eq!(driven.stop, "seconds", "{name}: {:?}", driven.error); + let error = driven.error.unwrap_or_default(); + assert!( + error.contains("line 2") + && error.contains("did not answer") + && error.contains("budget ran out"), + "{name}: {error}" + ); + assert!( + failed(driven.stop, None, JudgeOutcome::Judged), + "{name}: the timeout is a failed run on its own" + ); + } + } + /// A busy line does not multiply the declines: the peer refuses the first /// decline and streams a burst of unrelated notices at once, and the /// runner answers the decline again only once the quiet period has From 67a9a85b9cc3392824d08d310c5269d6798d2880 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 14:44:09 +0800 Subject: [PATCH 15/32] fix(xtask): bound a timed-out run's cleanup A run that stops on its wall clock gives its cleanup a bounded grace: the Session close, the remaining budget stops and the deferred window read, and the child's served App Server join. Cleanup that cannot settle within that grace keeps the timeout outcome; the child still prints it, so the parent's worker is released. The normal path is unchanged. Driven.timed_out records the wall-clock stop, because a pending switch renames the stop to switch_target_not_reached. The new scripted-peer test withholds the move reply and then the close reply, and drives both deadlines on a paused clock. --- xtask/Cargo.toml | 2 + xtask/src/scenario_eval.rs | 261 +++++++++++++++++++++++++++++++++---- 2 files changed, 237 insertions(+), 26 deletions(-) diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 2ce75fdb05..8e7aee7c18 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -41,6 +41,8 @@ axum = { workspace = true, features = ["json"] } [target.'cfg(unix)'.dependencies] libc = "0.2.189" [dev-dependencies] +# The cleanup tests drive the runner's own deadlines on a paused clock. +tokio = { workspace = true, features = ["test-util"] } [lints] workspace = true diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 31c2efb836..df224660aa 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -321,7 +321,9 @@ const QUIET: Duration = Duration::from_secs(1); /// How long one `session.idle` call may take before its line counts as busy. const IDLE_WAIT: Duration = Duration::from_secs(1); /// How long a failed run waits for its cancelled siblings to settle before -/// their futures are dropped (and their children's groups killed with them). +/// their futures are dropped (and their children's groups killed with them), +/// and how long a run that stopped on its wall clock waits for its cleanup +/// before it keeps the outcome it reached. const SETTLE_BOUND: Duration = Duration::from_secs(30); const JUDGE_SYSTEM: &str = "You check statements against the exported Timeline of a coding session. The Timeline is JSONL: a header line, one branch line per line of the Session, one event line per event, and an end line. A context/prepare or model/call event carries its request: addedMessages are the messages added since that line's previous request, with messageCount the whole request's count, and messages is the whole list when the history changed; every other field of the request appears in full only when it changed, and otherwise reads {\"unchanged\": true}. For each statement answer \"present\" when the run shows it and \"absent\" when it does not. Add the Timeline events that support the verdict as a short quote. Answer with a JSON array only, one object per statement: {\"id\": \"\", \"verdict\": \"present|absent\", \"quote\": \"\"}."; @@ -2377,6 +2379,8 @@ struct ChildOutcome { view: Option, session: Option, stop: String, + /// The run stopped because its wall-clock budget ran out. + timed_out: bool, turns: u32, window: Option, duration_ms: f64, @@ -2410,6 +2414,7 @@ fn harness_outcome(error: String, preflight: Vec) -> ChildOutcom view: None, session: None, stop: "error".into(), + timed_out: false, turns: 0, window: None, duration_ms: 0., @@ -2581,8 +2586,17 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child ) .await; let duration_ms = started.elapsed().as_secs_f64() * 1000.; + let timed_out = matches!(&outcome, Ok(outcome) if outcome.timed_out); server.shutdown(); - let _ = server.join().await; + // A run that stopped on its wall clock gives its served App Server the + // same bounded grace as its close: the tree close waits for the move the + // run stopped waiting on, and the child must print its outcome and exit + // so the parent's worker is released (model-prompts §8.1). + if timed_out { + let _ = tokio::time::timeout(SETTLE_BOUND, server.join()).await; + } else { + let _ = server.join().await; + } let mut outcome = outcome.unwrap_or_else(|error| { harness_outcome(format!("the run failed to finish: {error}"), Vec::new()) }); @@ -2803,6 +2817,7 @@ async fn child_drive( view: finished.view, session: (!driven.session.is_empty()).then_some(driven.session), stop: driven.stop.to_owned(), + timed_out: driven.timed_out, turns: driven.turns, window: driven.window, duration_ms: 0., @@ -4407,6 +4422,7 @@ impl Finished { driven: Driven { session: String::new(), stop: "error", + timed_out: false, turns: 0, window: None, decline_retries: 0, @@ -4499,9 +4515,17 @@ async fn drive_once( judging: Judging::not_asked(scenario, None), }); } - let _ = client - .rpc("session.close", json!({"sessionId": driven.session})) - .await; + let close = client.rpc("session.close", json!({"sessionId": driven.session})); + // A run that stopped on its wall clock gives the close a bounded grace: a + // move the run stopped waiting on keeps settling on the server, and the + // close waits behind it. Cleanup that cannot settle must not replace the + // outcome the run reached or hold the worker that runs it + // (model-prompts §8.1). + if driven.timed_out { + let _ = tokio::time::timeout(SETTLE_BOUND, close).await; + } else { + let _ = close.await; + } drop(client); let mut export = Vec::new(); let export = match dim_app_server::storage::export_timeline( @@ -4677,6 +4701,10 @@ async fn wait_for_plugins(client: &mut Client) -> Result<()> { struct Driven { session: String, stop: &'static str, + /// The run stopped because its wall-clock budget ran out. The stop can be + /// renamed afterwards (a pending switch makes its own outcome), so the + /// cleanup paths read this rather than the stop's spelling. + timed_out: bool, turns: u32, window: Option, /// How many declines the runner sent again after `question_not_pending`. @@ -4716,6 +4744,7 @@ async fn drive( return Driven { session: String::new(), stop: "error", + timed_out: false, turns: 0, window: None, decline_retries: 0, @@ -4739,6 +4768,7 @@ async fn drive( return Driven { session: String::new(), stop: "error", + timed_out: false, turns: 0, window: None, decline_retries: 0, @@ -4750,6 +4780,7 @@ async fn drive( let mut driven = Driven { session: session.clone(), stop: "idle", + timed_out: false, turns: 0, window: None, decline_retries: 0, @@ -4915,6 +4946,7 @@ async fn drive( Ok(fired) => fired, Err(_) => { driven.stop = "seconds"; + driven.timed_out = true; driven.error = Some(match line { Some(line) => format!( "the switch to line {line} did not answer before the run's {}s budget ran out", @@ -4967,6 +4999,7 @@ async fn drive( }); if started.elapsed().as_secs_f64() >= scenario.budget.seconds { driven.stop = "seconds"; + driven.timed_out = true; break; } if driven.turns >= scenario.budget.turns { @@ -5090,30 +5123,52 @@ async fn drive( } } if driven.stop == "turns" || driven.stop == "seconds" { - for branch in &branches { - let _ = client - .rpc( - "session.stop", - json!({"sessionId": session, "branchId": branch, - "reason": format!("budget: {}", driven.stop)}), - ) - .await; + let stop = async { + for branch in &branches { + let _ = client + .rpc( + "session.stop", + json!({"sessionId": session, "branchId": branch, + "reason": format!("budget: {}", driven.stop)}), + ) + .await; + } + }; + // A run that already spent its wall clock gives its cleanup a bounded + // grace: a server that keeps settling the operation the run stopped + // waiting on must not hold the run past the outcome it reached + // (model-prompts §8.1). + if driven.timed_out { + let _ = tokio::time::timeout(SETTLE_BOUND, stop).await; + } else { + stop.await; } } if window_deferred && driven.error.is_none() { - match client - .rpc( - "session.context.usage", - json!({"sessionId":session,"branchId":"main"}), - ) - .await - { - Ok(usage) => { + let usage = async { + client + .rpc( + "session.context.usage", + json!({"sessionId":session,"branchId":"main"}), + ) + .await + }; + let usage = if driven.timed_out { + tokio::time::timeout(SETTLE_BOUND, usage).await.ok() + } else { + Some(usage.await) + }; + match usage { + Some(Ok(usage)) => { driven.window = usage["contextWindow"].as_f64(); driven.error = window_mismatch(driven.window, scenario.budget.window); } - Err(error) if dim_client::app_error(&error) == Some("context_usage_unavailable") => {} - Err(error) => driven.error = Some(format!("Context window check failed: {error}")), + Some(Err(error)) + if dim_client::app_error(&error) == Some("context_usage_unavailable") => {} + Some(Err(error)) => { + driven.error = Some(format!("Context window check failed: {error}")) + } + None => {} } if driven.error.is_some() { driven.stop = "error"; @@ -11559,17 +11614,25 @@ mod tests { /// The target line `2` starts and ends its first turn and the move /// answers, and the input after the move never does. SwitchSubmitStalls, + /// The target line `2` starts and ends its first turn, the move to it + /// never answers, and the Session's close never answers either: a run + /// that stopped on its wall clock must still return, with cleanup + /// bounded. + SwitchMoveAndCloseStall, } /// What a scripted peer read: the `requestId` of every decline, in order, /// how many it had read when it first wrote a call's `step/tool-result`, - /// and how many `session.idle` calls it read while it held the line busy. + /// how many `session.idle` calls it read while it held the line busy, and + /// whether it read the attach and how many closes. #[cfg(unix)] #[derive(Default)] struct PeerReads { declines: Mutex>, settled_at: AtomicUsize, idles: AtomicUsize, + attached: tokio::sync::Notify, + closes: AtomicUsize, } /// How long [`PeerScript::HeldIdle`] keeps the line busy: five quiet @@ -11712,6 +11775,15 @@ mod tests { let Some(line) = line.unwrap() else { break }; let request: Value = serde_json::from_str(&line).unwrap(); let method = request["method"].as_str().unwrap_or_default(); + if method == "session.attach" { + recorded.attached.notify_one(); + } + if method == "session.close" { + recorded.closes.fetch_add(1, Ordering::SeqCst); + if matches!(script, PeerScript::SwitchMoveAndCloseStall) { + continue; + } + } if method == "session.idle" { if matches!(script, PeerScript::HeldIdle) { let at = *hold_until.get_or_insert_with(|| Instant::now() + HELD); @@ -11821,7 +11893,9 @@ mod tests { } PeerScript::SwitchNeverFires => None, PeerScript::SwitchMoveRetries => None, - PeerScript::SwitchMoveStalls | PeerScript::SwitchSubmitStalls => None, + PeerScript::SwitchMoveStalls + | PeerScript::SwitchSubmitStalls + | PeerScript::SwitchMoveAndCloseStall => None, }; if let Some((request, sequence)) = closed { if recorded.settled_at.load(Ordering::SeqCst) == 0 { @@ -11838,7 +11912,10 @@ mod tests { // The stalling scripts hold their reply: the move in one, the // input after it in the other. if method == "session.branch_set_default" - && matches!(script, PeerScript::SwitchMoveStalls) + && matches!( + script, + PeerScript::SwitchMoveStalls | PeerScript::SwitchMoveAndCloseStall + ) { continue; } @@ -11849,6 +11926,12 @@ mod tests { } } let body = match method { + "hello" => json!({"result": { + "instanceId": "peer", "serverVersion": "peer", + "protocolVersion": 4, + "features": ["session.create", "session.history"], + "daemonProfile": {"kind": "mock"}, + }}), "session.create" => json!({"result": {"sessionId": "peer"}}), "session.context.usage" => json!({"result": {"contextWindow": window}}), "session.idle" => json!({"result": {"sequence": PEER_SEQUENCE}}), @@ -11886,6 +11969,7 @@ mod tests { PeerScript::SwitchMoveRetries | PeerScript::SwitchMoveStalls | PeerScript::SwitchSubmitStalls + | PeerScript::SwitchMoveAndCloseStall ) { for (name, sequence) in [("start", 1), ("end", 2)] { write @@ -12148,6 +12232,131 @@ mod tests { } } + /// A run that stopped on its wall clock gives its cleanup a bounded + /// grace: its Session's close waits behind the move the run stopped + /// waiting on, and the run must still return the outcome it reached, so + /// the worker that runs it is released (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test] + async fn a_timed_out_run_closes_within_a_bounded_grace() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-close-grace-{}", + std::process::id() + )); + let (socket, reads) = + scripted_peer(&directory, 8_000, PeerScript::SwitchMoveAndCloseStall).await; + let server = app_server::serve_product(&directory.join("product"), |_| {}) + .await + .unwrap(); + let run_home = directory.join("run-home"); + private_directory(&run_home).unwrap(); + let settings = RunSettings { + overrides: Overrides::default(), + model_config: None, + unix_path: Some(socket), + defaults: None, + node: None, + js_runtime: None, + boundary: None, + plugin_tools: false, + }; + let mut scenario = scenario(Vec::new()); + scenario.budget.seconds = 0.5; + scenario.switch = Some(Switch { + to: SwitchTarget::Id("2".into()), + message: "next".into(), + branch_id: None, + }); + let cancel = CancellationToken::new(); + let model = peer_model(); + let judge = peer_model(); + let producer = ProducerState::default(); + let finished = { + let run = drive_once( + &server, + &settings, + &run_home, + &directory, + &scenario, + &model, + &judge, + JudgeWindow { + window: 128_000, + max_output: 2_048, + }, + &cancel, + &producer, + None, + ); + tokio::pin!(run); + // The client connects and the Session attaches with real I/O; + // only the run's own deadlines are on the paused clock below. + tokio::select! { + _ = reads.attached.notified() => {} + result = &mut run => panic!( + "the run ended before it attached: {:?}", + result.map(|finished| finished.driven.stop) + ), + } + tokio::time::pause(); + // Advance the paused clock in small steps until the close is on + // the wire, then past the cleanup grace. The switch deadline and + // the close bound are the only waits this drives, so no real + // sleep stands in for either. + let closer = reads.clone(); + let advancing = tokio::spawn(async move { + let step = Duration::from_millis(100); + for _ in 0..600 { + tokio::time::advance(step).await; + tokio::task::yield_now().await; + if closer.closes.load(Ordering::SeqCst) == 0 { + continue; + } + for _ in 0..=SETTLE_BOUND.as_millis() / step.as_millis() + 2 { + tokio::time::advance(step).await; + tokio::task::yield_now().await; + } + return; + } + }); + tokio::pin!(advancing); + tokio::select! { + biased; + result = &mut run => { + advancing.abort(); + tokio::time::resume(); + result.expect("the run failed to finish") + } + _ = &mut advancing => { + tokio::time::resume(); + tokio::time::timeout(Duration::from_secs(10), &mut run) + .await + .expect("the run kept waiting for cleanup after its timeout") + .expect("the run failed to finish") + } + } + }; + assert!( + reads.closes.load(Ordering::SeqCst) >= 1, + "the run tried to close the Session" + ); + assert_eq!( + finished.driven.stop, "seconds", + "{:?}", + finished.driven.error + ); + let error = finished.driven.error.as_deref().unwrap_or_default(); + assert!( + error.contains("line 2") + && error.contains("did not answer") + && error.contains("budget ran out"), + "{error}" + ); + server.shutdown(); + let _ = server.join().await; + let _ = std::fs::remove_dir_all(directory); + } + /// A busy line does not multiply the declines: the peer refuses the first /// decline and streams a burst of unrelated notices at once, and the /// runner answers the decline again only once the quiet period has From 0bcc797f2a2a542cf6db0c123327d446452ed2ce Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 15:48:03 +0800 Subject: [PATCH 16/32] fix(xtask): keep a timed-out run's stop if its window read fails The deferred window read is cleanup for a run that stopped on its wall clock. If it answers with an error other than the deferral, or with a window that does not match, the run keeps `seconds` and the error that ending carries instead of turning the stop into `error`. A read that succeeds still records the window. A run that did not time out takes the same path as before. The test scripts a peer whose first window read is unavailable and whose deferred read answers `session_reloading`, and the scenario's budget is zero, so the test waits on no clock. The assertions are the `seconds` stop, the peer's two window reads and the read's error not becoming the run's error. On 67a9a85b9 it fails with the stop recorded as `error`. --- xtask/src/scenario_eval.rs | 98 ++++++++++++++++++++++++++++++++------ 1 file changed, 84 insertions(+), 14 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index df224660aa..5d7c494fd9 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -5158,20 +5158,28 @@ async fn drive( } else { Some(usage.await) }; - match usage { - Some(Ok(usage)) => { + if driven.timed_out { + // The read belongs to the timed-out run's cleanup: what it returns + // cannot replace the ending the run reached (model-prompts §8.1). + if let Some(Ok(usage)) = usage { driven.window = usage["contextWindow"].as_f64(); - driven.error = window_mismatch(driven.window, scenario.budget.window); } - Some(Err(error)) - if dim_client::app_error(&error) == Some("context_usage_unavailable") => {} - Some(Err(error)) => { - driven.error = Some(format!("Context window check failed: {error}")) + } else { + match usage { + Some(Ok(usage)) => { + driven.window = usage["contextWindow"].as_f64(); + driven.error = window_mismatch(driven.window, scenario.budget.window); + } + Some(Err(error)) + if dim_client::app_error(&error) == Some("context_usage_unavailable") => {} + Some(Err(error)) => { + driven.error = Some(format!("Context window check failed: {error}")) + } + None => {} + } + if driven.error.is_some() { + driven.stop = "error"; } - None => {} - } - if driven.error.is_some() { - driven.stop = "error"; } } if let Some(pending) = &switch { @@ -11619,6 +11627,10 @@ mod tests { /// that stopped on its wall clock must still return, with cleanup /// bounded. SwitchMoveAndCloseStall, + /// The setup's context window read answers `context_usage_unavailable`, + /// so the check is deferred, and the deferred read answers + /// `session_reloading`: a failure that is not the deferral itself. + DeferredUsageFails, } /// What a scripted peer read: the `requestId` of every decline, in order, @@ -11631,6 +11643,7 @@ mod tests { declines: Mutex>, settled_at: AtomicUsize, idles: AtomicUsize, + usages: AtomicUsize, attached: tokio::sync::Notify, closes: AtomicUsize, } @@ -11896,6 +11909,7 @@ mod tests { PeerScript::SwitchMoveStalls | PeerScript::SwitchSubmitStalls | PeerScript::SwitchMoveAndCloseStall => None, + PeerScript::DeferredUsageFails => None, }; if let Some((request, sequence)) = closed { if recorded.settled_at.load(Ordering::SeqCst) == 0 { @@ -11933,7 +11947,18 @@ mod tests { "daemonProfile": {"kind": "mock"}, }}), "session.create" => json!({"result": {"sessionId": "peer"}}), - "session.context.usage" => json!({"result": {"contextWindow": window}}), + "session.context.usage" => { + let read = recorded.usages.fetch_add(1, Ordering::SeqCst) + 1; + match (matches!(script, PeerScript::DeferredUsageFails), read) { + (true, 1) => json!({"error": {"code": -32000, + "message": "the context window is not known yet", + "data": {"appError": "context_usage_unavailable"}}}), + (true, _) => json!({"error": {"code": -32000, + "message": "the Session is reloading", + "data": {"appError": "session_reloading"}}}), + _ => json!({"result": {"contextWindow": window}}), + } + } "session.idle" => json!({"result": {"sequence": PEER_SEQUENCE}}), "session.branch_set_default" if matches!(script, PeerScript::SwitchMoveRetries) => @@ -11954,8 +11979,16 @@ mod tests { // The held line asks nothing: the run's only work is the // turn the peer holds open. A switch that never fires // likewise asks nothing: its turn starts and ends. - if matches!(script, PeerScript::HeldIdle | PeerScript::SwitchNeverFires) { - if matches!(script, PeerScript::SwitchNeverFires) { + if matches!( + script, + PeerScript::HeldIdle + | PeerScript::SwitchNeverFires + | PeerScript::DeferredUsageFails + ) { + if matches!( + script, + PeerScript::SwitchNeverFires | PeerScript::DeferredUsageFails + ) { write .write_all(¬ice(json!({"type": "turn", "name": "end", "sequence": 2, "data": {}}))) @@ -12357,6 +12390,43 @@ mod tests { let _ = std::fs::remove_dir_all(directory); } + /// A run that stopped on its wall clock keeps that outcome when the + /// context window read it deferred fails afterwards: the read is + /// cleanup, and what it returns cannot replace `seconds` + /// (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test] + async fn a_timed_out_run_keeps_its_outcome_when_the_deferred_window_read_fails() { + let directory = std::env::temp_dir().join(format!( + "dim-scenario-eval-window-after-timeout-{}", + std::process::id() + )); + let (socket, reads) = + scripted_peer(&directory, 8_000, PeerScript::DeferredUsageFails).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + // The run is past its wall clock as soon as it submits: the timeout + // needs no clock of its own. + scenario.budget.seconds = 0.; + let workspace = std::env::temp_dir(); + let model = peer_model(); + let producer = ProducerState::default(); + let driven = drive(&mut client, &scenario, &workspace, &model, &producer, None).await; + let _ = std::fs::remove_dir_all(directory); + assert_eq!(driven.stop, "seconds", "{:?}", driven.error); + assert!(driven.timed_out, "the run stopped on its wall clock"); + assert_eq!( + reads.usages.load(Ordering::SeqCst), + 2, + "the deferred read ran once after the timeout" + ); + assert!( + driven.error.is_none(), + "the deferred read's failure is not the timeout's error: {:?}", + driven.error + ); + } + /// A busy line does not multiply the declines: the peer refuses the first /// decline and streams a burst of unrelated notices at once, and the /// runner answers the decline again only once the quiet period has From b2e13c61f50775237636e90bc5f5375c63b53471 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 17:10:50 +0800 Subject: [PATCH 17/32] fix(xtask): skip judging a timed-out run whose close did not settle A run that stopped on its wall clock bounds its Session close, but drive_once discarded the result and went on to export the Timeline and wait on the judge. A close that did not settle leaves a Session still settling the move the run stopped on: its export is not a settled record, and the judge call sits outside the cleanup grace, holding the child and the worker that runs it before the bounded server join. Keep the timeout when the close does not settle, omit the export, and read no judge. The child then returns its record, prints it, and exits, so the next scheduled run can use the same --jobs slot. Add a regression through the child and supervisor boundary: a timed-out scenario whose close and server shutdown never settle still returns a record for both arms, leaves no export, and lets the next scenario run and be judged on the same slot. The stall hook shortens the cleanup grace so the test reaches the bound without a real wait. --- xtask/src/app_server.rs | 6 ++ xtask/src/scenario_eval.rs | 175 ++++++++++++++++++++++++++++++++++++- 2 files changed, 178 insertions(+), 3 deletions(-) diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index 9f86787b54..21b2514061 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -89,6 +89,11 @@ pub struct RunSettings { /// run turns it off, so the tools the process registers are the ceiling /// its Sessions can declare. pub plugin_tools: bool, + /// A test hook: a timed-out run's Session close and its server's shutdown + /// never settle, to check that its child still returns the outcome and + /// frees the worker that runs it. The product and the evaluations set it + /// off. + pub stall_cleanup: bool, } impl Default for RunSettings { @@ -102,6 +107,7 @@ impl Default for RunSettings { js_runtime: None, boundary: None, plugin_tools: true, + stall_cleanup: false, } } } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 5d7c494fd9..8e85e24768 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -325,6 +325,20 @@ const IDLE_WAIT: Duration = Duration::from_secs(1); /// and how long a run that stopped on its wall clock waits for its cleanup /// before it keeps the outcome it reached. const SETTLE_BOUND: Duration = Duration::from_secs(30); +/// The cleanup grace a run with the `stall_cleanup` test hook gives its +/// close and its server's shutdown: short enough for a test to reach the +/// bound without a real wait, and unsignalled by the product. +const STALLED_CLEANUP_GRACE: Duration = Duration::from_millis(200); + +/// The cleanup grace of a run's close and its server's shutdown: [`SETTLE_BOUND`], +/// or the test hook's shorter grace. +fn settle_bound(settings: &RunSettings) -> Duration { + if settings.stall_cleanup { + STALLED_CLEANUP_GRACE + } else { + SETTLE_BOUND + } +} const JUDGE_SYSTEM: &str = "You check statements against the exported Timeline of a coding session. The Timeline is JSONL: a header line, one branch line per line of the Session, one event line per event, and an end line. A context/prepare or model/call event carries its request: addedMessages are the messages added since that line's previous request, with messageCount the whole request's count, and messages is the whole list when the history changed; every other field of the request appears in full only when it changed, and otherwise reads {\"unchanged\": true}. For each statement answer \"present\" when the run shows it and \"absent\" when it does not. Add the Timeline events that support the verdict as a short quote. Answer with a JSON array only, one object per statement: {\"id\": \"\", \"verdict\": \"present|absent\", \"quote\": \"\"}."; @@ -1296,6 +1310,10 @@ struct Options { /// child's standard output instead of detaching it, so only killing the /// child's group lets the parent's read reach EOF. fail_child_holds_stdout: bool, + /// A test hook: a timed-out run's Session close and its server's + /// shutdown never settle, to exercise a child that must still return its + /// outcome and free the worker that runs it. + stall_cleanup: bool, /// The default plugin configuration file both arms load; `None` serves /// the assembly without the product's plugins. defaults: Option, @@ -1461,6 +1479,7 @@ impl Options { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + stall_cleanup: false, rejudge, select, pool, @@ -2342,6 +2361,11 @@ struct ChildParams { /// child's group lets the parent's read reach EOF. #[serde(default)] fail_child_holds_stdout: bool, + /// A test hook: a timed-out run's Session close and its server's + /// shutdown never settle, to exercise a child that must still return its + /// outcome and free the worker that runs it. + #[serde(default)] + stall_cleanup: bool, /// The native probe's declared set: the assembly served without the /// plugin defaults. Each run's `tools-product` check reads its own /// declared set against it. @@ -2552,6 +2576,7 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child js_runtime: params.js_runtime.clone(), boundary: params.boundary.clone(), plugin_tools: false, + stall_cleanup: params.stall_cleanup, }; // The scenario's event producers run in the child, whose process // publishes what the run's Session subscribes to (EventHub design A.1). @@ -2592,8 +2617,17 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child // same bounded grace as its close: the tree close waits for the move the // run stopped waiting on, and the child must print its outcome and exit // so the parent's worker is released (model-prompts §8.1). - if timed_out { - let _ = tokio::time::timeout(SETTLE_BOUND, server.join()).await; + let bound = settle_bound(&settings); + if timed_out && settings.stall_cleanup { + // The hook's stand-in for a server that never finishes shutting down: + // the real join runs, and the wait after it does not return. + let stalled = async move { + let _ = server.join().await; + std::future::pending::<()>().await; + }; + let _ = tokio::time::timeout(bound, stalled).await; + } else if timed_out { + let _ = tokio::time::timeout(bound, server.join()).await; } else { let _ = server.join().await; } @@ -2624,6 +2658,7 @@ fn native_probe_settings( js_runtime: None, boundary, plugin_tools: false, + stall_cleanup: false, } } @@ -3771,6 +3806,7 @@ async fn isolate_run( .filter(|(arm_name, _)| arm_name == arm) .map(|(_, marker)| marker.clone()), fail_child_holds_stdout: options.fail_child_holds_stdout, + stall_cleanup: options.stall_cleanup, native_tools: native.to_vec(), probe_only: false, }; @@ -3877,6 +3913,7 @@ async fn native_probe( extra_tool: options.extra_tool, fail_child: None, fail_child_holds_stdout: false, + stall_cleanup: false, native_tools: Vec::new(), probe_only: true, }; @@ -4522,7 +4559,38 @@ async fn drive_once( // outcome the run reached or hold the worker that runs it // (model-prompts §8.1). if driven.timed_out { - let _ = tokio::time::timeout(SETTLE_BOUND, close).await; + let bound = settle_bound(settings); + let closed = if settings.stall_cleanup { + // The hook's stand-in for cleanup that never settles: the real + // close runs, and the wait after it does not return. + let stalled = async move { + let _ = close.await; + std::future::pending::<()>().await; + }; + let _ = tokio::time::timeout(bound, stalled).await; + false + } else { + matches!(tokio::time::timeout(bound, close).await, Ok(Ok(_))) + }; + if !closed { + // The Session may still be settling the move the run stopped on, + // so its export is not a settled record and the judge must not + // run on it: the run keeps the timeout it reached, and its + // child returns the record and exits (model-prompts §8.1). + return Ok(Finished { + driven, + export: None, + view: None, + judging: Judging::not_asked( + scenario, + Some( + "the Session did not close within the cleanup grace after the run \ + stopped on its wall clock" + .to_owned(), + ), + ), + }); + } } else { let _ = close.await; } @@ -10709,6 +10777,7 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + stall_cleanup: false, defaults: None, node: None, js_runtime: None, @@ -12292,6 +12361,7 @@ mod tests { js_runtime: None, boundary: None, plugin_tools: false, + stall_cleanup: false, }; let mut scenario = scenario(Vec::new()); scenario.budget.seconds = 0.5; @@ -13862,6 +13932,7 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + stall_cleanup: false, defaults: None, node: None, js_runtime: None, @@ -14160,6 +14231,7 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + stall_cleanup: false, native_tools: native .iter() .map(|name| ((*name).to_owned(), ToolSource::Builtin)) @@ -14355,6 +14427,103 @@ mod tests { ); } + /// A run that stopped on its wall clock and whose Session's close and + /// server shutdown never settle keeps its timeout, is not judged, and + /// frees the worker that ran it: its child returns the record and exits, + /// and the next scenario runs on the same slot (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_timed_out_run_whose_cleanup_stalls_frees_its_worker() { + /// Holds the stalled scenario's run answer and every judge answer + /// but the next scenario's: a run that entered the judge after an + /// unsettled close would wait on it instead of returning its record. + fn hold_the_stalled_case(text: &str) -> Option { + (text.contains("Run the stalled probes.") + || (text.contains("You check statements") + && !text.contains("Finish the next scenario."))) + .then(|| Duration::from_secs(60)) + } + let fixture = Fixture::holding( + "stalled-cleanup", + reads_the_workspace_file, + hold_the_stalled_case, + json!({ + "message": "Run the stalled probes.", + "budget": {"turns": 4, "seconds": 0.2, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + }), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + // The second scenario is the same run with time to finish: it must + // run on the slot the stalled run frees. + let next = fixture.scenarios.join("next"); + std::fs::create_dir_all(next.join("workspace")).unwrap(); + std::fs::write(next.join("workspace").join("notes.txt"), FILE_TEXT).unwrap(); + std::fs::write( + next.join("scenario.json"), + serde_json::to_string_pretty(&json!({ + "message": "Finish the next scenario.", + "budget": {"turns": 4, "seconds": 60, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + })) + .unwrap(), + ) + .unwrap(); + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + options.stall_cleanup = true; + let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + .await + .expect("the evaluation returns although the first scenario's cleanup never settles") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in records.iter().filter(|record| record["scenario"] == "case") { + assert_eq!(record["stop"], "seconds", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "not_asked", "{record}"); + assert_eq!(record["error"], Value::Null, "{record}"); + let error = record["judgeError"].as_str().unwrap_or_default(); + assert!( + error.contains("did not close within the cleanup grace"), + "the run says why it was not judged: {record}" + ); + } + for record in records.iter().filter(|record| record["scenario"] == "next") { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + for arm in ["current", "candidate"] { + assert!( + !out.join("outputs") + .join(arm) + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "a Session that did not close leaves no export to judge ({arm})" + ); + assert!( + out.join("outputs") + .join(arm) + .join("next") + .join("run-0.timeline.jsonl") + .exists(), + "the next scenario exports its Timeline ({arm})" + ); + } + assert_eq!( + fixture.judge().len(), + 2, + "only the next scenario's runs are judged" + ); + } + /// A child that fails after it started a member of its group does not /// leave it behind: the group the child leads is killed on the non-zero /// exit, so the member is gone when `evaluate` returns. The failing From 2c7b46a661f4ed8e907fcec1894a11a7a5169fde Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 18:17:40 +0800 Subject: [PATCH 18/32] fix(xtask): bound the parent's read of an exited child's output A serve child that exits successfully can leave a member of its process group holding the write end of its stdout, and the parent's read of the outcome then waited for an EOF that never came, holding the job slot and the evaluation. The read now runs under the cleanup grace and the evaluation's cancel; when the grace runs out the group is killed and the outcome is parsed from what the child printed, so a child that printed none reports the existing no-outcome failure. The group is killed after the read on a successful exit too, so no member outlives the harness. A timed-out run whose close settles still exports and is judged; a test pins that half of the timeout path, and changing the close result to a constant false fails it. Two tests cover the read: an exit with a stdout holder returns at the bound and frees its job slot, and a successful exit leaves no member of its group behind. Without the bound the first test waits out its guard. --- xtask/src/scenario_eval.rs | 304 ++++++++++++++++++++++++++++++++----- 1 file changed, 267 insertions(+), 37 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 8e85e24768..9102843232 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -326,14 +326,16 @@ const IDLE_WAIT: Duration = Duration::from_secs(1); /// before it keeps the outcome it reached. const SETTLE_BOUND: Duration = Duration::from_secs(30); /// The cleanup grace a run with the `stall_cleanup` test hook gives its -/// close and its server's shutdown: short enough for a test to reach the -/// bound without a real wait, and unsignalled by the product. +/// close, its server's shutdown and the parent's read of its child's output: +/// short enough for a test to reach the bound without a real wait, and +/// unsignalled by the product. const STALLED_CLEANUP_GRACE: Duration = Duration::from_millis(200); -/// The cleanup grace of a run's close and its server's shutdown: [`SETTLE_BOUND`], -/// or the test hook's shorter grace. -fn settle_bound(settings: &RunSettings) -> Duration { - if settings.stall_cleanup { +/// The cleanup grace of a run's close, its server's shutdown and the parent's +/// read of its child's output: [`SETTLE_BOUND`], or the test hook's shorter +/// grace. +fn settle_bound(stall_cleanup: bool) -> Duration { + if stall_cleanup { STALLED_CLEANUP_GRACE } else { SETTLE_BOUND @@ -1310,6 +1312,11 @@ struct Options { /// child's standard output instead of detaching it, so only killing the /// child's group lets the parent's read reach EOF. fail_child_holds_stdout: bool, + /// A test hook: the run's child leaves a member of its group behind after + /// it exits; the bool makes that member inherit the child's standard + /// output, so only killing the group lets the parent's read reach EOF. + /// The member's pid goes beside the marker. + leave_member: Option<(bool, PathBuf)>, /// A test hook: a timed-out run's Session close and its server's /// shutdown never settle, to exercise a child that must still return its /// outcome and free the worker that runs it. @@ -1479,6 +1486,7 @@ impl Options { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, stall_cleanup: false, rejudge, select, @@ -2361,6 +2369,12 @@ struct ChildParams { /// child's group lets the parent's read reach EOF. #[serde(default)] fail_child_holds_stdout: bool, + /// A test hook: this child leaves a member of its group behind after it + /// exits; the bool makes that member inherit this child's standard + /// output, so only killing the group lets the parent's read reach EOF. + /// The member's pid goes beside the marker. + #[serde(default)] + leave_member: Option<(bool, PathBuf)>, /// A test hook: a timed-out run's Session close and its server's /// shutdown never settle, to exercise a child that must still return its /// outcome and free the worker that runs it. @@ -2538,6 +2552,36 @@ pub(crate) async fn serve_entry(params_path: Option) -> Result<()> { ); return Ok(()); } + if let Some((holds_stdout, marker)) = ¶ms.leave_member { + // A test hook: a member of this child's group outlives it; with + // `holds_stdout` it keeps the child's standard output open, so the + // parent's read of the outcome can only end at its bound. Its pid is + // appended beside the marker for the test to check the group is gone. + let mut member = std::process::Command::new("sleep"); + member + .arg("30") + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .stdout(if *holds_stdout { + Stdio::inherit() + } else { + Stdio::null() + }); + let member = member.spawn().map_err(|error| { + format!("the leaving-member test hook cannot start its member: {error}") + })?; + use std::io::Write as _; + let mut recorded = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(marker.with_extension("member")) + .map_err(|error| { + format!("the leaving-member test hook cannot record its member: {error}") + })?; + writeln!(recorded, "{}", member.id()).map_err(|error| { + format!("the leaving-member test hook cannot record its member: {error}") + })?; + } println!( "{}", serde_json::to_string(&child_outcome(¶ms, &provider).await)? @@ -2617,7 +2661,7 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child // same bounded grace as its close: the tree close waits for the move the // run stopped waiting on, and the child must print its outcome and exit // so the parent's worker is released (model-prompts §8.1). - let bound = settle_bound(&settings); + let bound = settle_bound(settings.stall_cleanup); if timed_out && settings.stall_cleanup { // The hook's stand-in for a server that never finishes shutting down: // the real join runs, and the wait after it does not return. @@ -3806,6 +3850,7 @@ async fn isolate_run( .filter(|(arm_name, _)| arm_name == arm) .map(|(_, marker)| marker.clone()), fail_child_holds_stdout: options.fail_child_holds_stdout, + leave_member: options.leave_member.clone(), stall_cleanup: options.stall_cleanup, native_tools: native.to_vec(), probe_only: false, @@ -3913,6 +3958,7 @@ async fn native_probe( extra_tool: options.extra_tool, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, stall_cleanup: false, native_tools: Vec::new(), probe_only: true, @@ -4237,28 +4283,35 @@ async fn spawn_child_json( // Drain the pipe while the child runs: the child may print more than a // pipe holds (the run's logged output rides the same stream), and a full // pipe would block the child's last print forever, so waiting and then - // reading would deadlock. + // reading would deadlock. The reader appends what it has read as it goes, + // so a read that outlives its bound still yields the output the child + // printed before it exited. + let collected = Arc::new(Mutex::new(Vec::new())); let reading = child.stdout.take().map(|mut stdout| { + let collected = Arc::clone(&collected); tokio::spawn(async move { - let mut output = Vec::new(); - tokio::io::AsyncReadExt::read_to_end(&mut stdout, &mut output) - .await - .map_err(|error| format!("cannot read the serve child's outcome: {error}"))?; - Ok::, String>(output) + let mut buffer = [0u8; 8192]; + loop { + let read = tokio::io::AsyncReadExt::read(&mut stdout, &mut buffer) + .await + .map_err(|error| format!("cannot read the serve child's outcome: {error}"))?; + if read == 0 { + return Ok::<(), String>(()); + } + collected.lock().unwrap().extend_from_slice(&buffer[..read]); + } }) }); let status = tokio::select! { result = child.wait() => { let status = result?; - // The group is killed before the output is read: a member the - // failed child left behind may hold the write end of its stdout, - // and the reader would wait for an EOF that never comes. A - // successful child left no member behind, so its group is - // disarmed instead. + // A failed child may have left a member holding the write end of + // its stdout, and the reader would wait for an EOF that never + // comes: the group is killed before the output is read. A + // successful child's group is killed once its output is in hand, + // below. #[cfg(unix)] - if status.success() { - group.disarm(); - } else { + if !status.success() { group.kill(); } status @@ -4272,11 +4325,48 @@ async fn spawn_child_json( } }; let output = match reading { - Some(reading) => reading - .await - .map_err(|error| format!("the outcome reader failed: {error}"))??, + Some(mut reading) => { + // The child has exited, but a member it left behind may hold the + // write end of its stdout: the read gets the cleanup grace, and + // the evaluation's cancel ends it at once. When the grace runs + // out the group is killed and the reader is dropped; what it + // collected is still the child's output, so a missing outcome + // line is reported as one. + let grace = settle_bound(params.stall_cleanup); + let read = tokio::select! { + _ = cancel.cancelled() => { + #[cfg(unix)] + group.kill(); + reading.abort(); + let _ = reading.await; + return Err("the evaluation was cancelled".into()); + } + read = tokio::time::timeout(grace, &mut reading) => read, + }; + match read { + Ok(joined) => { + joined.map_err(|error| format!("the outcome reader failed: {error}"))??; + } + Err(_) => { + // The child exited, but a member it left behind still + // holds the write end of its stdout: the read's grace ran + // out. The group is killed so no member outlives the + // harness, and the output the reader collected is what + // the outcome line is looked for in. + #[cfg(unix)] + group.kill(); + reading.abort(); + let _ = reading.await; + } + } + std::mem::take(&mut *collected.lock().unwrap()) + } None => Vec::new(), }; + // The output is in hand: whatever member the child left in its group goes + // with it, so none outlives the harness. + #[cfg(unix)] + group.kill(); let text = String::from_utf8_lossy(&output); if !status.success() { // The group was killed as soon as the exit status was known: a @@ -4316,30 +4406,25 @@ async fn spawn_child_json( } /// The serve child's process group: the child leads it (`process_group(0)`), -/// so signalling it takes the members left in it. Armed until the child -/// exits on its own; dropping the guard kills whatever the group still -/// holds. +/// so signalling it takes the members left in it. Killed once, before the +/// output is read after a failed exit and after it is read otherwise; +/// dropping the guard kills whatever the group still holds. #[cfg(unix)] struct ChildGroup { pid: u32, - armed: bool, + killed: bool, } #[cfg(unix)] impl ChildGroup { fn new(pid: u32) -> Self { - Self { pid, armed: true } - } - - /// The child exited on its own: its group is not the harness's to kill. - fn disarm(&mut self) { - self.armed = false; + Self { pid, killed: false } } /// Kills every process in the group, once. fn kill(&mut self) { - if self.armed { - self.armed = false; + if !self.killed { + self.killed = true; if self.pid != 0 { // SAFETY: the child leads the group its own `process_group // (0)` created, so the negated id signals only the group the @@ -4559,7 +4644,7 @@ async fn drive_once( // outcome the run reached or hold the worker that runs it // (model-prompts §8.1). if driven.timed_out { - let bound = settle_bound(settings); + let bound = settle_bound(settings.stall_cleanup); let closed = if settings.stall_cleanup { // The hook's stand-in for cleanup that never settles: the real // close runs, and the wait after it does not return. @@ -10777,6 +10862,7 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, stall_cleanup: false, defaults: None, node: None, @@ -13932,6 +14018,7 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, stall_cleanup: false, defaults: None, node: None, @@ -14231,6 +14318,7 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, stall_cleanup: false, native_tools: native .iter() @@ -14524,6 +14612,56 @@ mod tests { ); } + /// A run that stopped on its wall clock and whose Session closes within + /// the grace still exports its Timeline and is judged: the timeout is the + /// run's outcome, not a reason to skip the judge. The run stays open on a + /// steer that is not due, reaches its wall clock with an idle Session, + /// and the close settles. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_timed_out_run_that_closes_is_judged() { + let fixture = Fixture::with_window( + "timed-out-judged", + reads_the_workspace_file, + json!({ + "description": "Timed out", + "message": "Run the quick probe.", + "steers": [{"afterSeconds": 120, "text": "This steer is not due."}], + "budget": {"turns": 12, "seconds": 1.0, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + }), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + let out = fixture.directory.join("out"); + let options = fixture.options(out.clone()); + let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + .await + .expect("the evaluation returns") + .expect("the evaluation records both arms"); + let records = fixture.records(&out); + assert_eq!(records.len(), 2, "{report}"); + for record in &records { + assert_eq!(record["stop"], "seconds", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + assert_eq!(record["error"], Value::Null, "{record}"); + } + for arm in ["current", "candidate"] { + assert!( + out.join("outputs") + .join(arm) + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "the closed run exports its Timeline ({arm})" + ); + } + assert_eq!(fixture.judge().len(), 2, "both runs reach the judge"); + } + /// A child that fails after it started a member of its group does not /// leave it behind: the group the child leads is killed on the non-zero /// exit, so the member is gone when `evaluate` returns. The failing @@ -14610,6 +14748,98 @@ mod tests { ); } + /// A child whose group keeps the write end of its standard output open + /// after the child exits must not hold the evaluation: the parent's read + /// of the outcome is bounded and the group is killed when the bound runs + /// out, so the run still returns its record. The second scenario runs on + /// the slot the first frees. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_child_that_leaves_a_stdout_holder_stops_at_the_read_bound() { + let fixture = Fixture::start( + "stdout-holder", + reads_the_workspace_file, + isolated_scenario(), + &[("notes.txt", FILE_TEXT)], + ) + .await; + let next = fixture.scenarios.join("next"); + std::fs::create_dir_all(next.join("workspace")).unwrap(); + std::fs::write(next.join("workspace").join("notes.txt"), FILE_TEXT).unwrap(); + std::fs::write( + next.join("scenario.json"), + serde_json::to_string_pretty(&isolated_scenario()).unwrap(), + ) + .unwrap(); + let out = fixture.directory.join("out"); + let mut options = fixture.judge_options(out.clone()); + options.jobs = 1; + options.stall_cleanup = true; + let marker = fixture.directory.join("leave.marker"); + options.leave_member = Some((true, marker.clone())); + let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + .await + .expect("the evaluation returns though a child left its stdout open") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in &records { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + let members = left_members(&marker); + assert_eq!(members.len(), 4, "each run's child left its member"); + for pid in members { + assert!( + child_tree_gone(pid).await, + "the stdout holder and its group are gone (pid {pid})" + ); + } + } + + /// A child that exits successfully and leaves a member that does not + /// hold its standard output still leaves no member behind: the group is + /// killed once the output is read. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_successful_child_leaves_no_group_member() { + let fixture = Fixture::start( + "successful-member", + reads_the_workspace_file, + isolated_scenario(), + &[("notes.txt", FILE_TEXT)], + ) + .await; + let out = fixture.directory.join("out"); + let mut options = fixture.judge_options(out.clone()); + let marker = fixture.directory.join("leave.marker"); + options.leave_member = Some((false, marker.clone())); + let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + .await + .expect("the evaluation returns") + .expect("the evaluation records both arms"); + let records = fixture.records(&out); + assert_eq!(records.len(), 2, "{report}"); + let members = left_members(&marker); + assert_eq!(members.len(), 2, "each arm's child left its member"); + for pid in members { + assert!( + child_tree_gone(pid).await, + "the successful child's member and its group are gone (pid {pid})" + ); + } + } + + /// The pids a `leave_member` child recorded, in the order it left them. + #[cfg(unix)] + fn left_members(marker: &Path) -> Vec { + std::fs::read_to_string(marker.with_extension("member")) + .expect("the leaving child recorded its member") + .lines() + .map(|line| line.trim().parse().expect("a member's pid")) + .collect() + } + /// Whether a serve child and the process group it leads have no member /// left, probed for up to five seconds: the harness kills the group, and /// the kill and the reaping of its leader settle a moment later. From 20ae9442f96107a8cbcab87983bd747c456a0bcc Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 18:34:18 +0800 Subject: [PATCH 19/32] test(xtask): give the stdout-holder test a wider hang guard The test runs four real child processes at one job; under a loaded machine one run took most of the old thirty-second guard, so the guard could fail a bounded read. It only turns a hang into a failed assertion, and the bound under test is the test hook's 200 ms read grace. --- xtask/src/scenario_eval.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 9102843232..085a00d6db 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -14777,7 +14777,11 @@ mod tests { options.stall_cleanup = true; let marker = fixture.directory.join("leave.marker"); options.leave_member = Some((true, marker.clone())); - let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + // Four runs, each starting its own child and served Session: the + // guard only turns a hang into a failed assertion, so it is wide + // enough for a loaded machine. The bound under test is the test + // hook's 200 ms read grace. + let report = tokio::time::timeout(Duration::from_secs(120), fixture.evaluate(&options)) .await .expect("the evaluation returns though a child left its stdout open") .expect("the evaluation records both scenarios"); From e3dbd7523eca01ceddfcad000c01671fe5f44534 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 18:48:35 +0800 Subject: [PATCH 20/32] test(xtask): hold the stdout-holder member past its guard A 30-second member only outlasted the test by its overhead, so a slower machine could have let the pre-fix read reach EOF and pass. The member now holds its standard output for 90 seconds, and the test runs one scenario's two arms at one job: the first arm's read cannot reach EOF before the guard, and the second arm still proves the first freed the slot. The guard is 60 seconds, twice the slowest loaded run. --- xtask/src/scenario_eval.rs | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 085a00d6db..8f242d6b29 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -2559,7 +2559,7 @@ pub(crate) async fn serve_entry(params_path: Option) -> Result<()> { // appended beside the marker for the test to check the group is gone. let mut member = std::process::Command::new("sleep"); member - .arg("30") + .arg("90") .stdin(Stdio::null()) .stderr(Stdio::null()) .stdout(if *holds_stdout { @@ -14751,8 +14751,8 @@ mod tests { /// A child whose group keeps the write end of its standard output open /// after the child exits must not hold the evaluation: the parent's read /// of the outcome is bounded and the group is killed when the bound runs - /// out, so the run still returns its record. The second scenario runs on - /// the slot the first frees. + /// out, so the run still returns its record. The second arm runs on the + /// slot the first frees. #[cfg(unix)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_child_that_leaves_a_stdout_holder_stops_at_the_read_bound() { @@ -14763,36 +14763,28 @@ mod tests { &[("notes.txt", FILE_TEXT)], ) .await; - let next = fixture.scenarios.join("next"); - std::fs::create_dir_all(next.join("workspace")).unwrap(); - std::fs::write(next.join("workspace").join("notes.txt"), FILE_TEXT).unwrap(); - std::fs::write( - next.join("scenario.json"), - serde_json::to_string_pretty(&isolated_scenario()).unwrap(), - ) - .unwrap(); let out = fixture.directory.join("out"); let mut options = fixture.judge_options(out.clone()); options.jobs = 1; options.stall_cleanup = true; let marker = fixture.directory.join("leave.marker"); options.leave_member = Some((true, marker.clone())); - // Four runs, each starting its own child and served Session: the - // guard only turns a hang into a failed assertion, so it is wide - // enough for a loaded machine. The bound under test is the test + // Two runs, each starting its own child and served Session: the + // guard only turns a hang into a failed assertion, and the member + // holds its stdout for 90 seconds. The bound under test is the test // hook's 200 ms read grace. - let report = tokio::time::timeout(Duration::from_secs(120), fixture.evaluate(&options)) + let report = tokio::time::timeout(Duration::from_secs(60), fixture.evaluate(&options)) .await .expect("the evaluation returns though a child left its stdout open") - .expect("the evaluation records both scenarios"); + .expect("the evaluation records both arms"); let records = fixture.records(&out); - assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + assert_eq!(records.len(), 2, "both arms: {report}"); for record in &records { assert_eq!(record["stop"], "idle", "{record}"); assert_eq!(record["judgeOutcome"], "judged", "{record}"); } let members = left_members(&marker); - assert_eq!(members.len(), 4, "each run's child left its member"); + assert_eq!(members.len(), 2, "each arm's child left its member"); for pid in members { assert!( child_tree_gone(pid).await, From 4a5851ba74350b97c1d7e6f4717f4510882dc3a8 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 19:35:55 +0800 Subject: [PATCH 21/32] fix(xtask): bound a timed-out run's judge A run that stopped on its wall clock gives its cleanup a bounded grace: its close, its server's shutdown and the parent's read of its output. The judge that follows a settled close had no such bound, so a provider that never answers held the run child open, and with it the worker that runs it, until the whole evaluation was cancelled. The judge of a timed-out run now gets the same SETTLE_BOUND. A judge that has not finished by then is recorded as a failed call, the run keeps its timeout and its error, and the child prints its record and exits. The verdicts of a failed run enter no probe rate, so the bound costs no measurement; a run that did not stop on its wall clock judges as before. A test hook sets the deadline shorter for the regression test, which runs two scenarios at one job through the real child and supervisor: the first scenario's two runs time out, close, export and meet a held judge, and the second scenario's runs still finish and are judged on the slot they free. --- xtask/src/app_server.rs | 5 ++ xtask/src/scenario_eval.rs | 152 +++++++++++++++++++++++++++++++++++-- 2 files changed, 152 insertions(+), 5 deletions(-) diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index 21b2514061..dbe833b898 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -94,6 +94,10 @@ pub struct RunSettings { /// frees the worker that runs it. The product and the evaluations set it /// off. pub stall_cleanup: bool, + /// A test hook: the deadline a timed-out run gives its judge, in + /// milliseconds, in place of the cleanup grace. The product and the + /// evaluations set it off. + pub judge_grace_ms: Option, } impl Default for RunSettings { @@ -108,6 +112,7 @@ impl Default for RunSettings { boundary: None, plugin_tools: true, stall_cleanup: false, + judge_grace_ms: None, } } } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 8f242d6b29..3d7a306d74 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -322,8 +322,9 @@ const QUIET: Duration = Duration::from_secs(1); const IDLE_WAIT: Duration = Duration::from_secs(1); /// How long a failed run waits for its cancelled siblings to settle before /// their futures are dropped (and their children's groups killed with them), -/// and how long a run that stopped on its wall clock waits for its cleanup -/// before it keeps the outcome it reached. +/// and how long a run that stopped on its wall clock waits for its cleanup — +/// its close, its server's shutdown and its judge — before it keeps the +/// outcome it reached. const SETTLE_BOUND: Duration = Duration::from_secs(30); /// The cleanup grace a run with the `stall_cleanup` test hook gives its /// close, its server's shutdown and the parent's read of its child's output: @@ -1321,6 +1322,9 @@ struct Options { /// shutdown never settle, to exercise a child that must still return its /// outcome and free the worker that runs it. stall_cleanup: bool, + /// A test hook: the deadline a timed-out run gives its judge, in + /// milliseconds, in place of the cleanup grace. + judge_grace_ms: Option, /// The default plugin configuration file both arms load; `None` serves /// the assembly without the product's plugins. defaults: Option, @@ -1488,6 +1492,7 @@ impl Options { fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, + judge_grace_ms: None, rejudge, select, pool, @@ -2236,8 +2241,9 @@ enum JudgeOutcome { /// The judge answered every call, and its verdicts are usable. Judged, /// A judge call failed: a window overflow, a transport or an HTTP error, - /// or a reply cut off at its output cap, on the first call, on its retry, - /// or on a re-ask. + /// a reply cut off at its output cap, or a call that did not finish + /// within the cleanup grace after a timed-out run, on the first call, on + /// its retry, or on a re-ask. CallFailed, /// The judge was never asked: the run left no export, the profile has no /// model host for the judge, or the run failed before the judge ran. @@ -2380,6 +2386,10 @@ struct ChildParams { /// outcome and free the worker that runs it. #[serde(default)] stall_cleanup: bool, + /// A test hook: the deadline a timed-out run gives its judge, in + /// milliseconds, in place of the cleanup grace. + #[serde(default)] + judge_grace_ms: Option, /// The native probe's declared set: the assembly served without the /// plugin defaults. Each run's `tools-product` check reads its own /// declared set against it. @@ -2621,6 +2631,7 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child boundary: params.boundary.clone(), plugin_tools: false, stall_cleanup: params.stall_cleanup, + judge_grace_ms: params.judge_grace_ms, }; // The scenario's event producers run in the child, whose process // publishes what the run's Session subscribes to (EventHub design A.1). @@ -2703,6 +2714,7 @@ fn native_probe_settings( boundary, plugin_tools: false, stall_cleanup: false, + judge_grace_ms: None, } } @@ -3852,6 +3864,7 @@ async fn isolate_run( fail_child_holds_stdout: options.fail_child_holds_stdout, leave_member: options.leave_member.clone(), stall_cleanup: options.stall_cleanup, + judge_grace_ms: options.judge_grace_ms, native_tools: native.to_vec(), probe_only: false, }; @@ -3960,6 +3973,7 @@ async fn native_probe( fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, + judge_grace_ms: None, native_tools: Vec::new(), probe_only: true, }; @@ -4589,6 +4603,18 @@ impl Judging { temperature_dropped: false, } } + /// A timed-out run whose judge did not answer within its cleanup grace: + /// the call is recorded as failed, and every probe stays unparsed. + fn unfinished(scenario: &Scenario, error: String) -> Self { + Self { + outcome: JudgeOutcome::CallFailed, + probes: unparsed(scenario), + error: Some(error), + reasks: 0, + calls: Vec::new(), + temperature_dropped: false, + } + } } #[expect( @@ -4725,7 +4751,34 @@ async fn drive_once( }); }; let view = judge_view(&export); - let judging = judge_export(&host, &resolver, judge, scenario, &view, limits, cancel).await; + // A run that stopped on its wall clock gives its judge the same bounded + // grace as the rest of its cleanup. The judge then reads the view of a + // failed run, which enters no probe rate (model-prompts §8.1), so a judge + // that has not answered inside the grace leaves the run's judgment + // unfinished instead of holding the child — and the worker that runs it — + // open. A run that did not stop on its wall clock judges as before. + let judging = if driven.timed_out { + let grace = settings + .judge_grace_ms + .map(Duration::from_millis) + .unwrap_or(SETTLE_BOUND); + match tokio::time::timeout( + grace, + judge_export(&host, &resolver, judge, scenario, &view, limits, cancel), + ) + .await + { + Ok(judging) => judging, + Err(_) => Judging::unfinished( + scenario, + "the judge did not finish within the cleanup grace after the run stopped on \ + its wall clock" + .to_owned(), + ), + } + } else { + judge_export(&host, &resolver, judge, scenario, &view, limits, cancel).await + }; Ok(Finished { driven, export: Some(export), @@ -10864,6 +10917,7 @@ mod tests { fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, + judge_grace_ms: None, defaults: None, node: None, js_runtime: None, @@ -12448,6 +12502,7 @@ mod tests { boundary: None, plugin_tools: false, stall_cleanup: false, + judge_grace_ms: None, }; let mut scenario = scenario(Vec::new()); scenario.budget.seconds = 0.5; @@ -14020,6 +14075,7 @@ mod tests { fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, + judge_grace_ms: None, defaults: None, node: None, js_runtime: None, @@ -14320,6 +14376,7 @@ mod tests { fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, + judge_grace_ms: None, native_tools: native .iter() .map(|name| ((*name).to_owned(), ToolSource::Builtin)) @@ -14662,6 +14719,91 @@ mod tests { assert_eq!(fixture.judge().len(), 2, "both runs reach the judge"); } + /// A timed-out run whose Session closes still gets a bounded judge: a + /// judge whose provider never answers leaves the record a failed judge + /// call naming the grace and keeps the timeout, and the child prints its + /// record and exits, so the worker runs the next scenario. The judge's + /// deadline is the test hook's one second; the held answer is a minute. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_timed_out_run_whose_judge_never_answers_frees_its_worker() { + fn hold_the_first_judge(text: &str) -> Option { + (text.contains("You check statements") && text.contains("Run the quick probe.")) + .then(|| Duration::from_secs(60)) + } + let fixture = Fixture::holding( + "timed-out-judge", + reads_the_workspace_file, + hold_the_first_judge, + json!({ + "description": "Timed out", + "message": "Run the quick probe.", + "steers": [{"afterSeconds": 120, "text": "This steer is not due."}], + "budget": {"turns": 12, "seconds": 1.0, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + }), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + // The second scenario must run on the slot the first frees; its + // judge is answered at once. + let next = fixture.scenarios.join("next"); + std::fs::create_dir_all(next.join("workspace")).unwrap(); + std::fs::write(next.join("workspace").join("notes.txt"), FILE_TEXT).unwrap(); + std::fs::write( + next.join("scenario.json"), + serde_json::to_string_pretty(&json!({ + "message": "Finish the next scenario.", + "budget": {"turns": 4, "seconds": 60, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + })) + .unwrap(), + ) + .unwrap(); + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + options.judge_grace_ms = Some(1_000); + let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + .await + .expect("the evaluation returns though the first scenario's judge never answers") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in records.iter().filter(|record| record["scenario"] == "case") { + assert_eq!(record["stop"], "seconds", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "call_failed", "{record}"); + assert_eq!(record["error"], Value::Null, "{record}"); + let error = record["judgeError"].as_str().unwrap_or_default(); + assert!( + error.contains("did not finish within the cleanup grace"), + "the run says why its judge is unfinished: {record}" + ); + assert!( + out.join("outputs") + .join(record["arm"].as_str().unwrap()) + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "the closed run still exports its Timeline: {record}" + ); + } + for record in records.iter().filter(|record| record["scenario"] == "next") { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + assert_eq!( + fixture.judge().len(), + 4, + "the first scenario's judge was asked and held; the second's was answered" + ); + } + /// A child that fails after it started a member of its group does not /// leave it behind: the group the child leads is killed on the non-zero /// exit, so the member is gone when `evaluate` returns. The failing From 615f2b8c8c084ccb879d290d102830f1d2a68909 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 19:48:56 +0800 Subject: [PATCH 22/32] test(xtask): give the judge-bound test a wider hang guard The test runs four real child processes at one job; under a loaded machine one run took about twenty of the old thirty-second guard, so the guard could fail a bounded judge. It only turns a hang into a failed assertion, and the deadline under test is the test hook's one second. --- xtask/src/scenario_eval.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 3d7a306d74..5531b9dc99 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -14723,7 +14723,8 @@ mod tests { /// judge whose provider never answers leaves the record a failed judge /// call naming the grace and keeps the timeout, and the child prints its /// record and exits, so the worker runs the next scenario. The judge's - /// deadline is the test hook's one second; the held answer is a minute. + /// deadline is the test hook's one second; the held answer is a minute, + /// and the guard only turns a hang into a failed assertion. #[cfg(unix)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_timed_out_run_whose_judge_never_answers_frees_its_worker() { @@ -14767,7 +14768,7 @@ mod tests { let mut options = fixture.options(out.clone()); options.jobs = 1; options.judge_grace_ms = Some(1_000); - let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + let report = tokio::time::timeout(Duration::from_secs(60), fixture.evaluate(&options)) .await .expect("the evaluation returns though the first scenario's judge never answers") .expect("the evaluation records both scenarios"); From 7747f4f9a5f8bf286905364870f24b69b1cfc5e8 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 21:00:19 +0800 Subject: [PATCH 23/32] fix(xtask): bound a timed-out run's whole cleanup A run that stops on its wall clock now fixes one cleanup deadline at that moment, and every step after it runs under that deadline: the remaining session.stop calls, the deferred window read, the close, the Timeline export, the judge, and the child's server shutdown and join. An export that misses the deadline leaves no partial export, keeps the stop and the error it reached, and the run records no judgment. The parent now gives each serve child a hard bound: the run's wall clock, the startup before it, the cleanup budget after it, and the grace to read its output. A child stuck in blocking work may never reach its own cleanup, so the bound kills its process group and the run keeps the wall-clock stop without an export or a judgment. The tests use controlled timing: on one worker, a run whose close settles and whose export stalls frees the slot for the next scenario, and a child that blocks after its wall clock is killed at the parent's bound with no process left behind. --- xtask/src/app_server.rs | 20 +- xtask/src/scenario_eval.rs | 648 +++++++++++++++++++++++++++++++------ 2 files changed, 571 insertions(+), 97 deletions(-) diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index dbe833b898..5e698aade1 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -94,10 +94,18 @@ pub struct RunSettings { /// frees the worker that runs it. The product and the evaluations set it /// off. pub stall_cleanup: bool, - /// A test hook: the deadline a timed-out run gives its judge, in - /// milliseconds, in place of the cleanup grace. The product and the - /// evaluations set it off. - pub judge_grace_ms: Option, + /// A test hook: a timed-out run's whole cleanup budget in milliseconds, in + /// place of the run's cleanup budget. The product and the evaluations set + /// it off. + pub cleanup_budget_ms: Option, + /// A test hook: this scenario's Timeline export never completes, to check + /// that a timed-out run keeps its outcome without an export. The product + /// and the evaluations set it off. + pub stall_export: Option, + /// A test hook: this child blocks the thread after its run stopped on its + /// wall clock, so only the parent's hard bound ends it. The product and + /// the evaluations set it off. + pub block_after_wall_clock: bool, } impl Default for RunSettings { @@ -112,7 +120,9 @@ impl Default for RunSettings { boundary: None, plugin_tools: true, stall_cleanup: false, - judge_grace_ms: None, + cleanup_budget_ms: None, + stall_export: None, + block_after_wall_clock: false, } } } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 5531b9dc99..b1caec4f79 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -322,10 +322,22 @@ const QUIET: Duration = Duration::from_secs(1); const IDLE_WAIT: Duration = Duration::from_secs(1); /// How long a failed run waits for its cancelled siblings to settle before /// their futures are dropped (and their children's groups killed with them), -/// and how long a run that stopped on its wall clock waits for its cleanup — -/// its close, its server's shutdown and its judge — before it keeps the -/// outcome it reached. +/// and how long the parent gives its read of a child's output after the child +/// exited. const SETTLE_BOUND: Duration = Duration::from_secs(30); +/// How long a run that stopped on its wall clock has for everything after that +/// moment: the remaining `session.stop` calls, the deferred window read, the +/// close, the Timeline export, the judge, and the child's server shutdown and +/// join. The moment the wall clock stops fixes one deadline; every step runs +/// under it, so the cleanup is bounded as a whole rather than step by step +/// (model-prompts §8.1). +const CLEANUP_BUDGET: Duration = Duration::from_secs(30); +/// How long a run's serve child may take before the parent kills its process +/// group: the child's startup before its wall clock starts — its server, its +/// connect, the plugin wait (60 s), the model and judge selections, the +/// preflight and `session.create` — is twice the longest of those waits, so a +/// child that never reaches its own cleanup has an end as well. +const STARTUP_BOUND: Duration = Duration::from_secs(120); /// The cleanup grace a run with the `stall_cleanup` test hook gives its /// close, its server's shutdown and the parent's read of its child's output: /// short enough for a test to reach the bound without a real wait, and @@ -343,6 +355,17 @@ fn settle_bound(stall_cleanup: bool) -> Duration { } } +/// The whole budget a run that stopped on its wall clock has for everything +/// after that moment: [`CLEANUP_BUDGET`], the test hook's shorter grace, or +/// the hook's given milliseconds. +fn cleanup_budget(stall_cleanup: bool, given_ms: Option) -> Duration { + if stall_cleanup { + STALLED_CLEANUP_GRACE + } else { + given_ms.map_or(CLEANUP_BUDGET, Duration::from_millis) + } +} + const JUDGE_SYSTEM: &str = "You check statements against the exported Timeline of a coding session. The Timeline is JSONL: a header line, one branch line per line of the Session, one event line per event, and an end line. A context/prepare or model/call event carries its request: addedMessages are the messages added since that line's previous request, with messageCount the whole request's count, and messages is the whole list when the history changed; every other field of the request appears in full only when it changed, and otherwise reads {\"unchanged\": true}. For each statement answer \"present\" when the run shows it and \"absent\" when it does not. Add the Timeline events that support the verdict as a short quote. Answer with a JSON array only, one object per statement: {\"id\": \"\", \"verdict\": \"present|absent\", \"quote\": \"\"}."; /// The message that asks the judge again, `{what}` saying why its last answer @@ -1322,9 +1345,19 @@ struct Options { /// shutdown never settle, to exercise a child that must still return its /// outcome and free the worker that runs it. stall_cleanup: bool, - /// A test hook: the deadline a timed-out run gives its judge, in - /// milliseconds, in place of the cleanup grace. - judge_grace_ms: Option, + /// A test hook: a timed-out run's whole cleanup budget, in milliseconds, + /// in place of [`CLEANUP_BUDGET`]. + cleanup_budget_ms: Option, + /// A test hook: this scenario's Timeline export never completes, to + /// exercise a run that keeps its wall-clock stop without an export. + stall_export: Option, + /// A test hook: a run's child blocks its thread after the run stopped on + /// its wall clock, so only the parent's hard bound ends it. + block_after_wall_clock: bool, + /// A test hook: the parent's hard bound on one run's child, in + /// milliseconds, in place of the bound its wall clock, startup, cleanup + /// and output grace add up to. + hard_bound_ms: Option, /// The default plugin configuration file both arms load; `None` serves /// the assembly without the product's plugins. defaults: Option, @@ -1492,7 +1525,10 @@ impl Options { fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, - judge_grace_ms: None, + cleanup_budget_ms: None, + stall_export: None, + block_after_wall_clock: false, + hard_bound_ms: None, rejudge, select, pool, @@ -2386,10 +2422,18 @@ struct ChildParams { /// outcome and free the worker that runs it. #[serde(default)] stall_cleanup: bool, - /// A test hook: the deadline a timed-out run gives its judge, in - /// milliseconds, in place of the cleanup grace. + /// A test hook: a timed-out run's whole cleanup budget in milliseconds, in + /// place of [`CLEANUP_BUDGET`]. + #[serde(default)] + cleanup_budget_ms: Option, + /// A test hook: this scenario's Timeline export never completes, to + /// exercise a run that keeps its wall-clock stop without an export. + #[serde(default)] + stall_export: Option, + /// A test hook: this child blocks its thread after the run stopped on its + /// wall clock, so only the parent's hard bound ends it. #[serde(default)] - judge_grace_ms: Option, + block_after_wall_clock: bool, /// The native probe's declared set: the assembly served without the /// plugin defaults. Each run's `tools-product` check reads its own /// declared set against it. @@ -2450,6 +2494,8 @@ struct ChildOutcome { /// The reasoning effort and service tier the run's requests carried. model_configuration: Option<(Option, Option)>, judge_configuration: Option<(Option, Option)>, + /// The judge's declared window and output cap: `(0, 0)` when the child + /// never resolved them, as a run the parent killed has not. judge_window: (u64, u64), } @@ -2631,7 +2677,9 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child boundary: params.boundary.clone(), plugin_tools: false, stall_cleanup: params.stall_cleanup, - judge_grace_ms: params.judge_grace_ms, + cleanup_budget_ms: params.cleanup_budget_ms, + stall_export: params.stall_export.clone(), + block_after_wall_clock: params.block_after_wall_clock, }; // The scenario's event producers run in the child, whose process // publishes what the run's Session subscribes to (EventHub design A.1). @@ -2661,28 +2709,37 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child } }; let started = Instant::now(); + let mut cleanup_deadline = None; let outcome = child_drive( - &server, &settings, params, &scenario, &unparsed, &producer, preflight, + &server, + &settings, + params, + &scenario, + &unparsed, + &producer, + preflight, + &mut cleanup_deadline, ) .await; let duration_ms = started.elapsed().as_secs_f64() * 1000.; - let timed_out = matches!(&outcome, Ok(outcome) if outcome.timed_out); server.shutdown(); - // A run that stopped on its wall clock gives its served App Server the - // same bounded grace as its close: the tree close waits for the move the - // run stopped waiting on, and the child must print its outcome and exit - // so the parent's worker is released (model-prompts §8.1). - let bound = settle_bound(settings.stall_cleanup); - if timed_out && settings.stall_cleanup { - // The hook's stand-in for a server that never finishes shutting down: - // the real join runs, and the wait after it does not return. - let stalled = async move { - let _ = server.join().await; - std::future::pending::<()>().await; - }; - let _ = tokio::time::timeout(bound, stalled).await; - } else if timed_out { - let _ = tokio::time::timeout(bound, server.join()).await; + // A run that stopped on its wall clock runs its served App Server's join + // under the one deadline the wall-clock stop fixed: the tree close waits + // for the move the run stopped waiting on, and the child must print its + // outcome and exit so the parent's worker is released (model-prompts + // §8.1). + if let Some(deadline) = cleanup_deadline { + if settings.stall_cleanup { + // The hook's stand-in for a server that never finishes shutting + // down: the real join runs, and the wait after it does not return. + let stalled = async move { + let _ = server.join().await; + std::future::pending::<()>().await; + }; + let _ = tokio::time::timeout_at(deadline, stalled).await; + } else { + let _ = tokio::time::timeout_at(deadline, server.join()).await; + } } else { let _ = server.join().await; } @@ -2714,7 +2771,9 @@ fn native_probe_settings( boundary, plugin_tools: false, stall_cleanup: false, - judge_grace_ms: None, + cleanup_budget_ms: None, + stall_export: None, + block_after_wall_clock: false, } } @@ -2768,6 +2827,10 @@ async fn native_probe_child(params: &ChildParams) -> Result, + cleanup_deadline: &mut Option, ) -> std::result::Result> { let cancel = CancellationToken::new(); let socket = settings @@ -2900,6 +2964,7 @@ async fn child_drive( } }; let driven = finished.driven; + *cleanup_deadline = driven.cleanup_deadline; let judging = finished.judging; Ok(ChildOutcome { preflight: checks, @@ -3864,7 +3929,9 @@ async fn isolate_run( fail_child_holds_stdout: options.fail_child_holds_stdout, leave_member: options.leave_member.clone(), stall_cleanup: options.stall_cleanup, - judge_grace_ms: options.judge_grace_ms, + cleanup_budget_ms: options.cleanup_budget_ms, + stall_export: options.stall_export.clone(), + block_after_wall_clock: options.block_after_wall_clock, native_tools: native.to_vec(), probe_only: false, }; @@ -3876,7 +3943,14 @@ async fn isolate_run( .join(format!("run-{run}.json")); private_directory(params_path.parent().expect("a params file has a parent"))?; std::fs::write(¶ms_path, serde_json::to_string_pretty(¶ms)?)?; - let outcome = spawn_child(options, ¶ms_path, ¶ms, cancel).await?; + let outcome = spawn_child( + options, + ¶ms_path, + ¶ms, + cancel, + Duration::from_secs_f64(scenario.budget.seconds), + ) + .await?; let record = child_record(arm, scenario, run, &outcome, instrument)?; Ok((record, outcome)) } @@ -3973,13 +4047,24 @@ async fn native_probe( fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, - judge_grace_ms: None, + cleanup_budget_ms: None, + stall_export: None, + block_after_wall_clock: false, native_tools: Vec::new(), probe_only: true, }; let params_path = root.join("params.json"); std::fs::write(¶ms_path, serde_json::to_string_pretty(¶ms)?)?; - let outcome = spawn_child_json(options, ¶ms_path, ¶ms, cancel, "nativeTools").await?; + let outcome = spawn_child_json( + options, + ¶ms_path, + ¶ms, + cancel, + "nativeTools", + Some(STARTUP_BOUND), + ) + .await? + .ok_or("the native probe's serve child did not exit within its bound")?; serde_json::from_value(outcome["nativeTools"].clone()) .map_err(|error| format!("the native probe printed no tool set: {error}").into()) } @@ -4234,15 +4319,102 @@ fn child_environment( Ok(env) } -/// Spawns the run's serve child and reads its outcome line. +/// Spawns the run's serve child and reads its outcome line. The child runs +/// under the parent's hard bound on one run: one that is still alive when the +/// bound expires is killed with its process group and recorded as a run that +/// stopped on its wall clock without an export or a judgment (model-prompts +/// §8.1). async fn spawn_child( options: &Options, params_path: &Path, params: &ChildParams, cancel: &CancellationToken, + wall_clock: Duration, ) -> Result { - let outcome = spawn_child_json(options, params_path, params, cancel, "judgeOutcome").await?; - Ok(serde_json::from_value(outcome)?) + let bound = child_hard_bound(options, params, wall_clock); + let started = Instant::now(); + match spawn_child_json( + options, + params_path, + params, + cancel, + "judgeOutcome", + Some(bound), + ) + .await? + { + Some(outcome) => Ok(serde_json::from_value(outcome)?), + None => Ok(bound_outcome(params, bound, started.elapsed())), + } +} + +/// The parent's hard bound on one run's serve child: the run's wall clock, the +/// startup before it ([`STARTUP_BOUND`]), the cleanup budget after it and the +/// grace to read the output the child may print. A child stuck in blocking +/// work may never reach its own cleanup, so this bound is what ends it. +fn child_hard_bound(options: &Options, params: &ChildParams, wall_clock: Duration) -> Duration { + options + .hard_bound_ms + .map(Duration::from_millis) + .unwrap_or_else(|| { + wall_clock + + STARTUP_BOUND + + cleanup_budget(params.stall_cleanup, params.cleanup_budget_ms) + + settle_bound(params.stall_cleanup) + }) +} + +/// The record of a run whose serve child the parent killed at its hard bound: +/// the child printed no outcome, so the run takes the wall-clock stop the +/// supervisor vouches for, with no export and no judgment (model-prompts +/// §8.1). +fn bound_outcome(params: &ChildParams, bound: Duration, elapsed: Duration) -> ChildOutcome { + let scenario: Option = serde_json::from_value(params.scenario.clone()).ok(); + let probes = scenario + .as_ref() + .map(unparsed) + .unwrap_or_default() + .into_iter() + .map(|probe| SavedProbe { + id: probe.id, + kind: Some(probe.kind.to_owned()), + verdict: probe.verdict, + quote: probe.quote, + }) + .collect(); + ChildOutcome { + preflight: Vec::new(), + harness: None, + export: None, + view: None, + session: None, + stop: "seconds".into(), + timed_out: true, + turns: 0, + window: None, + duration_ms: elapsed.as_secs_f64() * 1000., + decline_retries: 0, + switch_retries: 0, + error: Some(format!( + "the run's serve child did not exit within the parent's bound of {}s", + bound.as_secs_f64() + )), + judge_outcome: JudgeOutcome::NotAsked, + judge_error: Some( + "the run's Timeline was not exported: its serve child did not exit within the \ + parent's bound" + .to_owned(), + ), + judge_reasks: 0, + judge_calls: Vec::new(), + temperature_dropped: false, + events: Vec::new(), + reply_calls: Vec::new(), + probes, + model_configuration: None, + judge_configuration: None, + judge_window: (0, 0), + } } /// The serve children this test binary started, by their params path: a @@ -4252,14 +4424,17 @@ static SPAWNED: Mutex> = Mutex::new(Vec::new()); /// Spawns a child and reads the JSON object of the output line that names /// `marker`: a run's child prints its outcome under `judgeOutcome`, the -/// native probe's child its declared tool set under `nativeTools`. +/// native probe's child its declared tool set under `nativeTools`. `hard_bound` +/// is the parent's limit on the child's whole life; the answer is `None` when +/// that bound expired first, and the child's group was killed. async fn spawn_child_json( options: &Options, params_path: &Path, params: &ChildParams, cancel: &CancellationToken, marker: &str, -) -> Result { + hard_bound: Option, +) -> Result> { let (executable, args, test_binary) = child_command(params_path); let env = child_environment(options, params, params_path, test_binary)?; let mut command = tokio::process::Command::new(&executable); @@ -4294,6 +4469,9 @@ async fn spawn_child_json( .push((params_path.to_owned(), child.id().unwrap_or_default())); #[cfg(unix)] let mut group = ChildGroup::new(child.id().unwrap_or_default()); + // The parent's hard bound runs from the spawn, so a child that never + // reaches its own cleanup is still ended. + let deadline = hard_bound.map(|bound| tokio::time::Instant::now() + bound); // Drain the pipe while the child runs: the child may print more than a // pipe holds (the run's logged output rides the same stream), and a full // pipe would block the child's last print forever, so waiting and then @@ -4337,16 +4515,40 @@ async fn spawn_child_json( let _ = child.wait().await; return Err("the evaluation was cancelled".into()); } + _ = async { + match deadline { + Some(deadline) => tokio::time::sleep_until(deadline).await, + None => std::future::pending().await, + } + } => { + // The child is still alive at the parent's hard bound: it may be + // stuck in blocking work and never reach its own cleanup. Its + // group is killed so no member outlives the run, and the run gets + // the outcome the supervisor can vouch for. + #[cfg(unix)] + group.kill(); + let _ = child.kill().await; + let _ = child.wait().await; + if let Some(reading) = reading { + reading.abort(); + let _ = reading.await; + } + return Ok(None); + } }; let output = match reading { Some(mut reading) => { // The child has exited, but a member it left behind may hold the // write end of its stdout: the read gets the cleanup grace, and // the evaluation's cancel ends it at once. When the grace runs - // out the group is killed and the reader is dropped; what it - // collected is still the child's output, so a missing outcome - // line is reported as one. + // out — or the parent's hard bound does — the group is killed and + // the reader is dropped; what it collected is still the child's + // output, so a missing outcome line is reported as one. let grace = settle_bound(params.stall_cleanup); + let until = deadline.map_or_else( + || tokio::time::Instant::now() + grace, + |deadline| deadline.min(tokio::time::Instant::now() + grace), + ); let read = tokio::select! { _ = cancel.cancelled() => { #[cfg(unix)] @@ -4355,7 +4557,7 @@ async fn spawn_child_json( let _ = reading.await; return Err("the evaluation was cancelled".into()); } - read = tokio::time::timeout(grace, &mut reading) => read, + read = tokio::time::timeout_at(until, &mut reading) => read, }; match read { Ok(joined) => { @@ -4416,7 +4618,7 @@ async fn spawn_child_json( let json = &line[line .find('{') .ok_or("the child's outcome line carries no JSON")?..]; - Ok(serde_json::from_str(json)?) + Ok(Some(serde_json::from_str(json)?)) } /// The serve child's process group: the child leads it (`process_group(0)`), @@ -4535,7 +4737,7 @@ fn child_record( .clone() .map(|(effort, tier)| Configuration { effort, tier }) }); - if instrument.judge_window.is_none() { + if instrument.judge_window.is_none() && outcome.judge_window != (0, 0) { instrument.judge_window = Some(JudgeWindow { window: outcome.judge_window.0, max_output: outcome.judge_window.1, @@ -4559,6 +4761,7 @@ impl Finished { session: String::new(), stop: "error", timed_out: false, + cleanup_deadline: None, turns: 0, window: None, decline_retries: 0, @@ -4654,7 +4857,16 @@ async fn drive_once( if settings.defaults.is_some() { wait_for_plugins(&mut client).await?; } - let mut driven = drive(&mut client, scenario, workspace, model, producer, tools).await; + let mut driven = drive( + &mut client, + settings, + scenario, + workspace, + model, + producer, + tools, + ) + .await; if driven.session.is_empty() { return Ok(Finished { driven, @@ -4663,14 +4875,19 @@ async fn drive_once( judging: Judging::not_asked(scenario, None), }); } + if driven.timed_out && settings.block_after_wall_clock { + // The hook's stand-in for a child stuck in blocking work after its + // wall clock: no timer of the child's can end it, so only the + // parent's hard bound does. + std::thread::sleep(Duration::from_secs(600)); + } let close = client.rpc("session.close", json!({"sessionId": driven.session})); - // A run that stopped on its wall clock gives the close a bounded grace: a - // move the run stopped waiting on keeps settling on the server, and the - // close waits behind it. Cleanup that cannot settle must not replace the - // outcome the run reached or hold the worker that runs it - // (model-prompts §8.1). - if driven.timed_out { - let bound = settle_bound(settings.stall_cleanup); + // A run that stopped on its wall clock runs its close under the one + // deadline the wall-clock stop fixed: a move the run stopped waiting on + // keeps settling on the server, and the close waits behind it. Cleanup + // that cannot settle must not replace the outcome the run reached or hold + // the worker that runs it (model-prompts §8.1). + if let Some(deadline) = driven.cleanup_deadline { let closed = if settings.stall_cleanup { // The hook's stand-in for cleanup that never settles: the real // close runs, and the wait after it does not return. @@ -4678,10 +4895,10 @@ async fn drive_once( let _ = close.await; std::future::pending::<()>().await; }; - let _ = tokio::time::timeout(bound, stalled).await; + let _ = tokio::time::timeout_at(deadline, stalled).await; false } else { - matches!(tokio::time::timeout(bound, close).await, Ok(Ok(_))) + matches!(tokio::time::timeout_at(deadline, close).await, Ok(Ok(_))) }; if !closed { // The Session may still be settling the move the run stopped on, @@ -4706,14 +4923,47 @@ async fn drive_once( let _ = close.await; } drop(client); - let mut export = Vec::new(); - let export = match dim_app_server::storage::export_timeline( - settings.database(run_home), - &driven.session, - &mut export, - ) - .await - { + let export = { + let session = driven.session.clone(); + let database = settings.database(run_home); + let stalled = driven.cleanup_deadline.is_some() + && settings.stall_export.as_deref() == Some(scenario.id.as_str()); + async move { + if stalled { + std::future::pending::<()>().await; + } + let mut export = Vec::new(); + let exported = + dim_app_server::storage::export_timeline(database, &session, &mut export).await; + (export, exported) + } + }; + let (export, exported) = match driven.cleanup_deadline { + Some(deadline) => match tokio::time::timeout_at(deadline, export).await { + Ok(exported) => exported, + Err(_) => { + // A run that stopped on its wall clock keeps the timeout it + // reached: no partial export is written, and the judge is not + // asked about a Timeline that was not exported + // (model-prompts §8.1). + return Ok(Finished { + driven, + export: None, + view: None, + judging: Judging::not_asked( + scenario, + Some( + "the Timeline export did not finish within the cleanup grace after \ + the run stopped on its wall clock" + .to_owned(), + ), + ), + }); + } + }, + None => export.await, + }; + let export = match exported { Ok(()) => { let export = String::from_utf8_lossy_owned(export); let (turns, failed_turn) = turns_in_export(&export); @@ -4751,19 +5001,15 @@ async fn drive_once( }); }; let view = judge_view(&export); - // A run that stopped on its wall clock gives its judge the same bounded - // grace as the rest of its cleanup. The judge then reads the view of a - // failed run, which enters no probe rate (model-prompts §8.1), so a judge - // that has not answered inside the grace leaves the run's judgment - // unfinished instead of holding the child — and the worker that runs it — - // open. A run that did not stop on its wall clock judges as before. - let judging = if driven.timed_out { - let grace = settings - .judge_grace_ms - .map(Duration::from_millis) - .unwrap_or(SETTLE_BOUND); - match tokio::time::timeout( - grace, + // A run that stopped on its wall clock gives its judge the time left of + // the one cleanup deadline: the judge reads the view of a failed run, + // which enters no probe rate (model-prompts §8.1), so a judge that has not + // answered by the deadline leaves the run's judgment unfinished instead of + // holding the child — and the worker that runs it — open. A run that did + // not stop on its wall clock judges as before. + let judging = if let Some(deadline) = driven.cleanup_deadline { + match tokio::time::timeout_at( + deadline, judge_export(&host, &resolver, judge, scenario, &view, limits, cancel), ) .await @@ -4911,6 +5157,10 @@ struct Driven { /// renamed afterwards (a pending switch makes its own outcome), so the /// cleanup paths read this rather than the stop's spelling. timed_out: bool, + /// The one deadline every step after the wall-clock stop runs under, + /// [`CLEANUP_BUDGET`] after that moment; `Some` exactly when + /// [`timed_out`](Self::timed_out) is true. + cleanup_deadline: Option, turns: u32, window: Option, /// How many declines the runner sent again after `question_not_pending`. @@ -4938,6 +5188,7 @@ fn window_mismatch(window: Option, declared: u64) -> Option { /// `plugin` tool. async fn drive( client: &mut Client, + settings: &RunSettings, scenario: &Scenario, workspace: &Path, model: &ModelSelection, @@ -4951,6 +5202,7 @@ async fn drive( session: String::new(), stop: "error", timed_out: false, + cleanup_deadline: None, turns: 0, window: None, decline_retries: 0, @@ -4975,6 +5227,7 @@ async fn drive( session: String::new(), stop: "error", timed_out: false, + cleanup_deadline: None, turns: 0, window: None, decline_retries: 0, @@ -4987,6 +5240,7 @@ async fn drive( session: session.clone(), stop: "idle", timed_out: false, + cleanup_deadline: None, turns: 0, window: None, decline_retries: 0, @@ -5153,6 +5407,10 @@ async fn drive( 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(match line { Some(line) => format!( "the switch to line {line} did not answer before the run's {}s budget ran out", @@ -5206,6 +5464,10 @@ async fn drive( if started.elapsed().as_secs_f64() >= scenario.budget.seconds { driven.stop = "seconds"; driven.timed_out = true; + driven.cleanup_deadline = Some( + tokio::time::Instant::now() + + cleanup_budget(settings.stall_cleanup, settings.cleanup_budget_ms), + ); break; } if driven.turns >= scenario.budget.turns { @@ -5340,12 +5602,12 @@ async fn drive( .await; } }; - // A run that already spent its wall clock gives its cleanup a bounded - // grace: a server that keeps settling the operation the run stopped - // waiting on must not hold the run past the outcome it reached - // (model-prompts §8.1). - if driven.timed_out { - let _ = tokio::time::timeout(SETTLE_BOUND, stop).await; + // A run that already spent its wall clock runs its cleanup under the + // one deadline the wall-clock stop fixed: a server that keeps settling + // the operation the run stopped waiting on must not hold the run past + // the outcome it reached (model-prompts §8.1). + if let Some(deadline) = driven.cleanup_deadline { + let _ = tokio::time::timeout_at(deadline, stop).await; } else { stop.await; } @@ -5359,8 +5621,8 @@ async fn drive( ) .await }; - let usage = if driven.timed_out { - tokio::time::timeout(SETTLE_BOUND, usage).await.ok() + let usage = if let Some(deadline) = driven.cleanup_deadline { + tokio::time::timeout_at(deadline, usage).await.ok() } else { Some(usage.await) }; @@ -10917,7 +11179,10 @@ mod tests { fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, - judge_grace_ms: None, + cleanup_budget_ms: None, + stall_export: None, + block_after_wall_clock: false, + hard_bound_ms: None, defaults: None, node: None, js_runtime: None, @@ -12298,6 +12563,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12339,6 +12605,7 @@ mod tests { }); let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12386,6 +12653,7 @@ mod tests { }); let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12449,6 +12717,7 @@ mod tests { GUARD, drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12502,7 +12771,9 @@ mod tests { boundary: None, plugin_tools: false, stall_cleanup: false, - judge_grace_ms: None, + cleanup_budget_ms: None, + stall_export: None, + block_after_wall_clock: false, }; let mut scenario = scenario(Vec::new()); scenario.budget.seconds = 0.5; @@ -12622,7 +12893,16 @@ mod tests { let workspace = std::env::temp_dir(); let model = peer_model(); let producer = ProducerState::default(); - let driven = drive(&mut client, &scenario, &workspace, &model, &producer, None).await; + let driven = drive( + &mut client, + &RunSettings::default(), + &scenario, + &workspace, + &model, + &producer, + None, + ) + .await; let _ = std::fs::remove_dir_all(directory); assert_eq!(driven.stop, "seconds", "{:?}", driven.error); assert!(driven.timed_out, "the run stopped on its wall clock"); @@ -12654,6 +12934,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12690,6 +12971,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12730,6 +13012,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12770,6 +13053,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12809,6 +13093,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12843,6 +13128,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12881,6 +13167,7 @@ mod tests { let started = Instant::now(); let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -14075,7 +14362,10 @@ mod tests { fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, - judge_grace_ms: None, + cleanup_budget_ms: None, + stall_export: None, + block_after_wall_clock: false, + hard_bound_ms: None, defaults: None, node: None, js_runtime: None, @@ -14376,7 +14666,9 @@ mod tests { fail_child_holds_stdout: false, leave_member: None, stall_cleanup: false, - judge_grace_ms: None, + cleanup_budget_ms: None, + stall_export: None, + block_after_wall_clock: false, native_tools: native .iter() .map(|name| ((*name).to_owned(), ToolSource::Builtin)) @@ -14722,9 +15014,9 @@ mod tests { /// A timed-out run whose Session closes still gets a bounded judge: a /// judge whose provider never answers leaves the record a failed judge /// call naming the grace and keeps the timeout, and the child prints its - /// record and exits, so the worker runs the next scenario. The judge's - /// deadline is the test hook's one second; the held answer is a minute, - /// and the guard only turns a hang into a failed assertion. + /// record and exits, so the worker runs the next scenario. The run's whole + /// cleanup deadline is the test hook's one second; the held answer is a + /// minute, and the guard only turns a hang into a failed assertion. #[cfg(unix)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_timed_out_run_whose_judge_never_answers_frees_its_worker() { @@ -14767,7 +15059,7 @@ mod tests { let out = fixture.directory.join("out"); let mut options = fixture.options(out.clone()); options.jobs = 1; - options.judge_grace_ms = Some(1_000); + options.cleanup_budget_ms = Some(1_000); let report = tokio::time::timeout(Duration::from_secs(60), fixture.evaluate(&options)) .await .expect("the evaluation returns though the first scenario's judge never answers") @@ -14805,6 +15097,178 @@ mod tests { ); } + /// A timed-out run whose Session closes but whose Timeline export never + /// finishes keeps its wall-clock stop, leaves no export and no judgment, + /// and frees the worker: the export runs under the same cleanup deadline + /// as the rest of the cleanup, and the next scenario runs on the slot + /// (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_timed_out_run_whose_export_stalls_frees_its_worker() { + let fixture = Fixture::with_window( + "stalled-export", + reads_the_workspace_file, + json!({ + "description": "Timed out", + "message": "Run the quick probe.", + "steers": [{"afterSeconds": 120, "text": "This steer is not due."}], + "budget": {"turns": 12, "seconds": 1.0, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + }), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + // The second scenario is the same run with time to finish: it must + // run on the slot the stalled run frees, and be judged. + let next = fixture.scenarios.join("next"); + std::fs::create_dir_all(next.join("workspace")).unwrap(); + std::fs::write(next.join("workspace").join("notes.txt"), FILE_TEXT).unwrap(); + std::fs::write( + next.join("scenario.json"), + serde_json::to_string_pretty(&json!({ + "message": "Finish the next scenario.", + "budget": {"turns": 4, "seconds": 60, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + })) + .unwrap(), + ) + .unwrap(); + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + options.stall_export = Some("case".into()); + // Long enough for the close to settle on a loaded host; the export is + // the step that never finishes. + options.cleanup_budget_ms = Some(2_000); + let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + .await + .expect("the evaluation returns though the first scenario's export never finishes") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in records.iter().filter(|record| record["scenario"] == "case") { + assert_eq!(record["stop"], "seconds", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "not_asked", "{record}"); + assert_eq!(record["error"], Value::Null, "{record}"); + let error = record["judgeError"].as_str().unwrap_or_default(); + assert!( + error.contains("export did not finish within the cleanup grace"), + "the run says why its Timeline was not exported: {record}" + ); + } + for record in records.iter().filter(|record| record["scenario"] == "next") { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + for arm in ["current", "candidate"] { + assert!( + !out.join("outputs") + .join(arm) + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "a run whose export did not finish leaves no export ({arm})" + ); + assert!( + out.join("outputs") + .join(arm) + .join("next") + .join("run-0.timeline.jsonl") + .exists(), + "the next scenario exports its Timeline ({arm})" + ); + } + assert_eq!( + fixture.judge().len(), + 2, + "only the next scenario's runs are judged" + ); + } + + /// A child that blocks after its run stopped on its wall clock never + /// reaches its own cleanup: the parent's hard bound kills its process + /// group, records the run as a wall-clock stop with no export and no + /// judgment, and frees the worker for the next arm, and no process of the + /// child's outlives the evaluation (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_child_stuck_after_its_wall_clock_stops_at_the_parent_bound() { + let fixture = Fixture::with_window( + "stuck-child", + reads_the_workspace_file, + json!({ + "description": "Timed out", + "message": "Run the quick probe.", + "steers": [{"afterSeconds": 120, "text": "This steer is not due."}], + "budget": {"turns": 12, "seconds": 0.2, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + }), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + options.block_after_wall_clock = true; + // The bound under test is the parent's two seconds per child; the + // guard only turns a hang into a failed assertion. + options.hard_bound_ms = Some(2_000); + let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + .await + .expect("the evaluation returns though each child blocks after its wall clock") + .expect("the evaluation records both arms"); + let records = fixture.records(&out); + assert_eq!(records.len(), 2, "both arms: {report}"); + for record in &records { + assert_eq!(record["stop"], "seconds", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "not_asked", "{record}"); + let error = record["error"].as_str().unwrap_or_default(); + assert!( + error.contains("did not exit within the parent's bound"), + "the run says why it has no outcome: {record}" + ); + let judge_error = record["judgeError"].as_str().unwrap_or_default(); + assert!( + judge_error.contains("was not exported"), + "the run says why it was not judged: {record}" + ); + assert!( + !out.join("outputs") + .join(record["arm"].as_str().unwrap()) + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "a killed child leaves no export: {record}" + ); + } + for arm in ["current", "candidate"] { + let params = out + .join("children") + .join(arm) + .join("case") + .join("run-0.json"); + let pid = SPAWNED + .lock() + .unwrap() + .iter() + .find(|(path, _)| path == ¶ms) + .map(|(_, pid)| *pid) + .expect("the run's serve child was spawned"); + assert!( + child_tree_gone(pid).await, + "the killed child and its group are gone ({arm}, pid {pid})" + ); + } + } + /// A child that fails after it started a member of its group does not /// leave it behind: the group the child leads is killed on the non-zero /// exit, so the member is gone when `evaluate` returns. The failing From 72d13a57a8500cd85f79a6689223ae8c52ef7aaa Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 21:06:16 +0800 Subject: [PATCH 24/32] fix(xtask): cover the judge's own wait budget in the parent bound A run that does not stop on its wall clock is not under the cleanup budget: its judge may legitimately spend the failure policy's five minute wait budget on retries. The parent's hard bound on its child now takes the larger of the cleanup budget and that wait budget, so a slow but legitimate judge is not killed and recorded as a wall-clock stop. --- xtask/src/scenario_eval.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index b1caec4f79..3b2c464693 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -332,6 +332,12 @@ const SETTLE_BOUND: Duration = Duration::from_secs(30); /// under it, so the cleanup is bounded as a whole rather than step by step /// (model-prompts §8.1). const CLEANUP_BUDGET: Duration = Duration::from_secs(30); +/// The longest a judge's own retries may wait before its call fails: one +/// request's wait budget in the product's failure policy. A run that did not +/// stop on its wall clock is not under [`CLEANUP_BUDGET`], so the parent's hard +/// bound on its child covers the judge's own budget instead when that is +/// longer. +const JUDGE_BUDGET: Duration = dim_agent_capabilities::model_provider::WAIT_BUDGET; /// How long a run's serve child may take before the parent kills its process /// group: the child's startup before its wall clock starts — its server, its /// connect, the plugin wait (60 s), the model and judge selections, the @@ -4349,9 +4355,10 @@ async fn spawn_child( } /// The parent's hard bound on one run's serve child: the run's wall clock, the -/// startup before it ([`STARTUP_BOUND`]), the cleanup budget after it and the -/// grace to read the output the child may print. A child stuck in blocking -/// work may never reach its own cleanup, so this bound is what ends it. +/// startup before it ([`STARTUP_BOUND`]), the cleanup budget after it — or the +/// judge's own retry budget when that is longer — and the grace to read the +/// output the child may print. A child stuck in blocking work may never reach +/// its own cleanup, so this bound is what ends it. fn child_hard_bound(options: &Options, params: &ChildParams, wall_clock: Duration) -> Duration { options .hard_bound_ms @@ -4359,7 +4366,7 @@ fn child_hard_bound(options: &Options, params: &ChildParams, wall_clock: Duratio .unwrap_or_else(|| { wall_clock + STARTUP_BOUND - + cleanup_budget(params.stall_cleanup, params.cleanup_budget_ms) + + cleanup_budget(params.stall_cleanup, params.cleanup_budget_ms).max(JUDGE_BUDGET) + settle_bound(params.stall_cleanup) }) } From 4129e21e1f7783d7e7570a36b5d55f4aa4d69d12 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 21:20:48 +0800 Subject: [PATCH 25/32] test(xtask): shorten the stalled-export case's own setup The scenario stops on its wall clock after half a second instead of a second, and its cleanup budget is one second instead of two, so the test spends less of its hang guard on waits it does not need. The shared guards and the other tests' bounds are unchanged. --- xtask/src/scenario_eval.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 3b2c464693..58589e3319 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -15119,7 +15119,7 @@ mod tests { "description": "Timed out", "message": "Run the quick probe.", "steers": [{"afterSeconds": 120, "text": "This steer is not due."}], - "budget": {"turns": 12, "seconds": 1.0, "window": 131072}, + "budget": {"turns": 12, "seconds": 0.5, "window": 131072}, "probes": [{"id": "ran", "kind": "must_show", "text": "the run has a transcript"}] }), @@ -15149,7 +15149,7 @@ mod tests { options.stall_export = Some("case".into()); // Long enough for the close to settle on a loaded host; the export is // the step that never finishes. - options.cleanup_budget_ms = Some(2_000); + options.cleanup_budget_ms = Some(1_000); let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) .await .expect("the evaluation returns though the first scenario's export never finishes") From 8e61cffe134ccaa58b8754f23492d632ca6bb36f Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 21:40:28 +0800 Subject: [PATCH 26/32] test(xtask): give the subprocess flows one hang guard The flows that run a real serve child through the supervisor take one outer guard, `SUBPROCESS_EVAL_GUARD` (60 seconds), and the answers and the stdout member they must outwait take `HELD_PAST_GUARD` (90 seconds), with a compile-time assertion that the second is longer. The failed-run sibling flow gains the same guard. The stalled-close, stalled-export and unanswered-judge flows also assert that their stalled case's record ends under 20 seconds, so an implementation whose bound is merely too long fails instead of passing. The 10-second guard of the failed stdout holder is left as it is. --- xtask/src/scenario_eval.rs | 46 ++++++++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 58589e3319..3df646358b 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -349,6 +349,15 @@ const STARTUP_BOUND: Duration = Duration::from_secs(120); /// short enough for a test to reach the bound without a real wait, and /// unsignalled by the product. const STALLED_CLEANUP_GRACE: Duration = Duration::from_millis(200); +/// The outer hang guard of the tests that run a real serve child through the +/// supervisor: a wait that never ends fails the guard instead of holding the +/// suite. +const SUBPROCESS_EVAL_GUARD: Duration = Duration::from_secs(60); +/// How long a test hook's provider holds an answer, and how long the +/// stdout-holder member keeps the write end open: past the guard, so a flow +/// that waits on either fails its guard instead of passing. +const HELD_PAST_GUARD: Duration = Duration::from_secs(90); +const _: () = assert!(HELD_PAST_GUARD.as_secs() > SUBPROCESS_EVAL_GUARD.as_secs()); /// The cleanup grace of a run's close, its server's shutdown and the parent's /// read of its child's output: [`SETTLE_BOUND`], or the test hook's shorter @@ -2621,7 +2630,7 @@ pub(crate) async fn serve_entry(params_path: Option) -> Result<()> { // appended beside the marker for the test to check the group is gone. let mut member = std::process::Command::new("sleep"); member - .arg("90") + .arg(HELD_PAST_GUARD.as_secs().to_string()) .stdin(Stdio::null()) .stderr(Stdio::null()) .stdout(if *holds_stdout { @@ -14805,8 +14814,7 @@ mod tests { /// Holds the candidate arm's model calls until the failure cancels /// it; the current arm's child never reaches a model call. fn hold_the_candidate(text: &str) -> Option { - text.contains("/candidate/") - .then(|| Duration::from_secs(60)) + text.contains("/candidate/").then_some(HELD_PAST_GUARD) } let fixture = Fixture::holding( "failed-sibling", @@ -14845,7 +14853,9 @@ mod tests { }) }; options.fail_child = Some(("current".into(), marker)); - let settled = fixture.evaluate(&options).await; + let settled = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) + .await + .expect("the evaluation returns after its failed run settles the sibling"); let error = settled .expect_err("the failing run fails the evaluation") .to_string(); @@ -14885,7 +14895,7 @@ mod tests { (text.contains("Run the stalled probes.") || (text.contains("You check statements") && !text.contains("Finish the next scenario."))) - .then(|| Duration::from_secs(60)) + .then_some(HELD_PAST_GUARD) } let fixture = Fixture::holding( "stalled-cleanup", @@ -14921,7 +14931,7 @@ mod tests { let mut options = fixture.options(out.clone()); options.jobs = 1; options.stall_cleanup = true; - let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await .expect("the evaluation returns although the first scenario's cleanup never settles") .expect("the evaluation records both scenarios"); @@ -14932,6 +14942,10 @@ mod tests { assert_eq!(record["failed"], true, "{record}"); assert_eq!(record["judgeOutcome"], "not_asked", "{record}"); assert_eq!(record["error"], Value::Null, "{record}"); + assert!( + record["durationMs"].as_f64().unwrap_or_default() < 20_000.0, + "the run ends within its cleanup bound, not at a longer one: {record}" + ); let error = record["judgeError"].as_str().unwrap_or_default(); assert!( error.contains("did not close within the cleanup grace"), @@ -15029,7 +15043,7 @@ mod tests { async fn a_timed_out_run_whose_judge_never_answers_frees_its_worker() { fn hold_the_first_judge(text: &str) -> Option { (text.contains("You check statements") && text.contains("Run the quick probe.")) - .then(|| Duration::from_secs(60)) + .then_some(HELD_PAST_GUARD) } let fixture = Fixture::holding( "timed-out-judge", @@ -15067,7 +15081,7 @@ mod tests { let mut options = fixture.options(out.clone()); options.jobs = 1; options.cleanup_budget_ms = Some(1_000); - let report = tokio::time::timeout(Duration::from_secs(60), fixture.evaluate(&options)) + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await .expect("the evaluation returns though the first scenario's judge never answers") .expect("the evaluation records both scenarios"); @@ -15078,6 +15092,10 @@ mod tests { assert_eq!(record["failed"], true, "{record}"); assert_eq!(record["judgeOutcome"], "call_failed", "{record}"); assert_eq!(record["error"], Value::Null, "{record}"); + assert!( + record["durationMs"].as_f64().unwrap_or_default() < 20_000.0, + "the run ends within its cleanup bound, not at a longer one: {record}" + ); let error = record["judgeError"].as_str().unwrap_or_default(); assert!( error.contains("did not finish within the cleanup grace"), @@ -15150,7 +15168,7 @@ mod tests { // Long enough for the close to settle on a loaded host; the export is // the step that never finishes. options.cleanup_budget_ms = Some(1_000); - let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await .expect("the evaluation returns though the first scenario's export never finishes") .expect("the evaluation records both scenarios"); @@ -15161,6 +15179,10 @@ mod tests { assert_eq!(record["failed"], true, "{record}"); assert_eq!(record["judgeOutcome"], "not_asked", "{record}"); assert_eq!(record["error"], Value::Null, "{record}"); + assert!( + record["durationMs"].as_f64().unwrap_or_default() < 20_000.0, + "the run ends within its cleanup bound, not at a longer one: {record}" + ); let error = record["judgeError"].as_str().unwrap_or_default(); assert!( error.contains("export did not finish within the cleanup grace"), @@ -15227,7 +15249,7 @@ mod tests { // The bound under test is the parent's two seconds per child; the // guard only turns a hang into a failed assertion. options.hard_bound_ms = Some(2_000); - let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await .expect("the evaluation returns though each child blocks after its wall clock") .expect("the evaluation records both arms"); @@ -15387,7 +15409,7 @@ mod tests { // guard only turns a hang into a failed assertion, and the member // holds its stdout for 90 seconds. The bound under test is the test // hook's 200 ms read grace. - let report = tokio::time::timeout(Duration::from_secs(60), fixture.evaluate(&options)) + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await .expect("the evaluation returns though a child left its stdout open") .expect("the evaluation records both arms"); @@ -15424,7 +15446,7 @@ mod tests { let mut options = fixture.judge_options(out.clone()); let marker = fixture.directory.join("leave.marker"); options.leave_member = Some((false, marker.clone())); - let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await .expect("the evaluation returns") .expect("the evaluation records both arms"); From 4560a5d6704f2781fcb263caba3062488c935d50 Mon Sep 17 00:00:00 2001 From: huihui Date: Sun, 22 Nov 2026 22:56:29 +0800 Subject: [PATCH 27/32] test(xtask): give the judged flow the shared guard and bound The timed-out run that closes and is judged runs a real serve child through the supervisor like the other subprocess flows, so it takes `SUBPROCESS_EVAL_GUARD` instead of a 30-second guard of its own, and its records assert that the stop, close, export and judge finish under 20 seconds. The record is taken before the served App Server's join, so the join is not part of that bound. --- xtask/src/scenario_eval.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 3df646358b..b6c360f6e2 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -15007,7 +15007,7 @@ mod tests { .await; let out = fixture.directory.join("out"); let options = fixture.options(out.clone()); - let report = tokio::time::timeout(Duration::from_secs(30), fixture.evaluate(&options)) + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await .expect("the evaluation returns") .expect("the evaluation records both arms"); @@ -15018,6 +15018,10 @@ mod tests { assert_eq!(record["failed"], true, "{record}"); assert_eq!(record["judgeOutcome"], "judged", "{record}"); assert_eq!(record["error"], Value::Null, "{record}"); + assert!( + record["durationMs"].as_f64().unwrap_or_default() < 20_000.0, + "the stop, close, export and judge do not sit at a longer bound: {record}" + ); } for arm in ["current", "candidate"] { assert!( From fad1ece40a79e7d03dcabb0c16a8d73d854dbb1b Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 01:07:25 +0800 Subject: [PATCH 28/32] fix(xtask): record the supervisor's endings apart from the run's own The parent now tracks whether its read of a serve child's output reached EOF or was cut at its deadline, so an exit-first race records a supervisor timeout for that run and leaves the next scheduled run intact, while a malformed completed line still fails the evaluation. A complete outcome printed before the parent's hard bound stands: the teardown failure is attached as an error instead of replacing the run's stop, export and judgment. A child the bound ends before its outcome is a supervisor failure with no export and no judgment, unless the child reported the scenario's own wall-clock stop, which is kept. The non-wall-clock judge phase gets its own 600-second budget for up to four legitimate calls, the parent's hard bound covers it, and every server join is bounded so a finished outcome is printed and its slot released. A failed turn in the export no longer replaces a run's wall-clock stop, and the stall hooks write a marker the parent's bound counts from, so a slow start cannot spend the bound under test. --- xtask/src/app_server.rs | 9 +- xtask/src/scenario_eval.rs | 1019 +++++++++++++++++++++++++++++++----- 2 files changed, 906 insertions(+), 122 deletions(-) diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index 5e698aade1..94131524b2 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -102,10 +102,9 @@ pub struct RunSettings { /// that a timed-out run keeps its outcome without an export. The product /// and the evaluations set it off. pub stall_export: Option, - /// A test hook: this child blocks the thread after its run stopped on its - /// wall clock, so only the parent's hard bound ends it. The product and - /// the evaluations set it off. - pub block_after_wall_clock: bool, + /// A test hook: the judge phase's budget in milliseconds, in place of the + /// runner's own phase budget. The product and the evaluations set it off. + pub judge_budget_ms: Option, } impl Default for RunSettings { @@ -122,7 +121,7 @@ impl Default for RunSettings { stall_cleanup: false, cleanup_budget_ms: None, stall_export: None, - block_after_wall_clock: false, + judge_budget_ms: None, } } } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index b6c360f6e2..d214efa57e 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -332,12 +332,12 @@ const SETTLE_BOUND: Duration = Duration::from_secs(30); /// under it, so the cleanup is bounded as a whole rather than step by step /// (model-prompts §8.1). const CLEANUP_BUDGET: Duration = Duration::from_secs(30); -/// The longest a judge's own retries may wait before its call fails: one -/// request's wait budget in the product's failure policy. A run that did not -/// stop on its wall clock is not under [`CLEANUP_BUDGET`], so the parent's hard -/// bound on its child covers the judge's own budget instead when that is -/// longer. -const JUDGE_BUDGET: Duration = dim_agent_capabilities::model_provider::WAIT_BUDGET; +/// The budget of one run's judge phase: its first call, the retry without a +/// temperature, and two re-asks, each under the product's own retry policy. A +/// run that did not stop on its wall clock is not under [`CLEANUP_BUDGET`], so +/// its judge phase has this budget instead, and the parent's hard bound on its +/// child covers it. +const JUDGE_PHASE_BUDGET: Duration = Duration::from_secs(600); /// How long a run's serve child may take before the parent kills its process /// group: the child's startup before its wall clock starts — its server, its /// connect, the plugin wait (60 s), the model and judge selections, the @@ -349,6 +349,10 @@ const STARTUP_BOUND: Duration = Duration::from_secs(120); /// short enough for a test to reach the bound without a real wait, and /// unsignalled by the product. const STALLED_CLEANUP_GRACE: Duration = Duration::from_millis(200); +/// How long the parent waits for its read of a killed child's output to reach +/// EOF: every writer in the child's group is dead, so the read ends at once; +/// the grace only turns a stuck reader into a dropped one. +const KILLED_READ_GRACE: Duration = Duration::from_secs(1); /// The outer hang guard of the tests that run a real serve child through the /// supervisor: a wait that never ends fails the guard instead of holding the /// suite. @@ -381,6 +385,12 @@ fn cleanup_budget(stall_cleanup: bool, given_ms: Option) -> Duration { } } +/// The budget of one run's judge phase: [`JUDGE_PHASE_BUDGET`], or the test +/// hook's given milliseconds. +fn judge_phase_budget(given_ms: Option) -> Duration { + given_ms.map_or(JUDGE_PHASE_BUDGET, Duration::from_millis) +} + const JUDGE_SYSTEM: &str = "You check statements against the exported Timeline of a coding session. The Timeline is JSONL: a header line, one branch line per line of the Session, one event line per event, and an end line. A context/prepare or model/call event carries its request: addedMessages are the messages added since that line's previous request, with messageCount the whole request's count, and messages is the whole list when the history changed; every other field of the request appears in full only when it changed, and otherwise reads {\"unchanged\": true}. For each statement answer \"present\" when the run shows it and \"absent\" when it does not. Add the Timeline events that support the verdict as a short quote. Answer with a JSON array only, one object per statement: {\"id\": \"\", \"verdict\": \"present|absent\", \"quote\": \"\"}."; /// The message that asks the judge again, `{what}` saying why its last answer @@ -1316,6 +1326,56 @@ fn schedule(runs: usize, scenarios: usize) -> Vec<(&'static str, usize, usize)> schedule } +/// A test hook: a run's child stalls after writing its marker, and the +/// parent's hard bound counts from that marker. The product and the ordinary +/// tests leave it unset. +struct Stall { + /// The arm and scenario whose child stalls; `None` stalls every run. + run: Option<(String, String)>, + point: StallPoint, + /// The parent's hard bound after the marker, in milliseconds. + bound_ms: u64, +} +impl Stall { + /// Where this run's child stalls, when the hook names it. + fn point_for(&self, arm: &str, scenario: &str) -> Option { + match &self.run { + Some((arm_name, scenario_name)) => { + (arm_name == arm && scenario_name == scenario).then_some(self.point) + } + None => Some(self.point), + } + } +} + +/// Where a stalled child stops: before it prints anything (a startup stall), +/// after it printed its outcome (a child that cannot exit), or after its run +/// stopped on its wall clock (a cleanup that never settles). +#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +enum StallPoint { + BeforeOutcome, + AfterOutcome, + AfterWallClock, +} + +/// A test hook: how a run's child ends before its outcome line. +#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +enum BrokenOutcome { + /// It exits without printing a line. + Silent, + /// It prints a line that names the outcome but is not JSON. + Garbled, +} + +/// A test hook: the run whose child ends before its outcome line. +struct BrokenRun { + /// The arm and scenario of the run. + run: (String, String), + outcome: BrokenOutcome, +} + struct Options { scenarios: PathBuf, /// The `--text ID --candidate FILE` pairs, in the order given. @@ -1366,13 +1426,16 @@ struct Options { /// A test hook: this scenario's Timeline export never completes, to /// exercise a run that keeps its wall-clock stop without an export. stall_export: Option, - /// A test hook: a run's child blocks its thread after the run stopped on - /// its wall clock, so only the parent's hard bound ends it. - block_after_wall_clock: bool, - /// A test hook: the parent's hard bound on one run's child, in - /// milliseconds, in place of the bound its wall clock, startup, cleanup - /// and output grace add up to. - hard_bound_ms: Option, + /// A test hook: a run's child stalls at `point` after writing its marker, + /// and the parent's hard bound counts from that marker, so a slow start + /// does not spend the bound under test. + stall: Option, + /// A test hook: the run whose child ends before its outcome line, + /// silently or with a garbled one. + broken: Option, + /// A test hook: the judge phase's budget in milliseconds, in place of + /// [`JUDGE_PHASE_BUDGET`]. + judge_budget_ms: Option, /// The default plugin configuration file both arms load; `None` serves /// the assembly without the product's plugins. defaults: Option, @@ -1542,8 +1605,9 @@ impl Options { stall_cleanup: false, cleanup_budget_ms: None, stall_export: None, - block_after_wall_clock: false, - hard_bound_ms: None, + stall: None, + broken: None, + judge_budget_ms: None, rejudge, select, pool, @@ -2355,6 +2419,14 @@ impl JudgeCall { } } +/// A stalled child's marker and where it stalls. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct ChildStall { + point: StallPoint, + marker: PathBuf, +} + /// One run's serve child: the App Server of the run, served in its own /// process with a disposable environment (isolation decision 1). The parent /// starts its own binary with `scenario-eval-serve `; the offline @@ -2445,10 +2517,18 @@ struct ChildParams { /// exercise a run that keeps its wall-clock stop without an export. #[serde(default)] stall_export: Option, - /// A test hook: this child blocks its thread after the run stopped on its - /// wall clock, so only the parent's hard bound ends it. + /// A test hook: where this child stalls, the marker it writes, and the + /// parent's hard bound after that marker. + #[serde(default)] + stall: Option, + /// A test hook: this child ends before its outcome line, silently or with + /// a line that is not JSON. #[serde(default)] - block_after_wall_clock: bool, + broken: Option, + /// A test hook: the judge phase's budget in milliseconds, in place of + /// [`JUDGE_PHASE_BUDGET`]. + #[serde(default)] + judge_budget_ms: Option, /// The native probe's declared set: the assembly served without the /// plugin defaults. Each run's `tools-product` check reads its own /// declared set against it. @@ -2562,6 +2642,11 @@ pub(crate) async fn serve_entry(params_path: Option) -> Result<()> { augment_model_config(¶ms.model_config, &preflight_url, &config_path)?; let mut params = params; params.model_config = config_path; + if let Some(stall) = ¶ms.stall + && stall.point == StallPoint::BeforeOutcome + { + stall_here(stall, "before its outcome")?; + } // A test hook: the test writes `marker` once the sibling arm's model // call is held; this child waits for that event, bounded, then exits // non-zero. The wait's outcome is printed on a line of its own, so the @@ -2653,10 +2738,32 @@ pub(crate) async fn serve_entry(params_path: Option) -> Result<()> { format!("the leaving-member test hook cannot record its member: {error}") })?; } + if let Some(broken) = params.broken { + // A test hook: the child ends before its outcome line, with the + // leaving member — if any — still holding its standard output. + match broken { + BrokenOutcome::Silent => {} + BrokenOutcome::Garbled => println!("{{\"judgeOutcome\": "), + } + return Ok(()); + } println!( "{}", serde_json::to_string(&child_outcome(¶ms, &provider).await)? ); + if let Some(stall) = ¶ms.stall + && stall.point == StallPoint::AfterOutcome + { + stall_here(stall, "after its outcome")?; + } + Ok(()) +} + +/// The test hook's stall: the marker the parent's hard bound counts from, +/// then a wait no timer of the child's ends. +fn stall_here(stall: &ChildStall, note: &str) -> Result<()> { + std::fs::write(&stall.marker, note)?; + std::thread::sleep(Duration::from_secs(600)); Ok(()) } @@ -2694,7 +2801,7 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child stall_cleanup: params.stall_cleanup, cleanup_budget_ms: params.cleanup_budget_ms, stall_export: params.stall_export.clone(), - block_after_wall_clock: params.block_after_wall_clock, + judge_budget_ms: params.judge_budget_ms, }; // The scenario's event producers run in the child, whose process // publishes what the run's Session subscribes to (EventHub design A.1). @@ -2742,25 +2849,50 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child // under the one deadline the wall-clock stop fixed: the tree close waits // for the move the run stopped waiting on, and the child must print its // outcome and exit so the parent's worker is released (model-prompts - // §8.1). - if let Some(deadline) = cleanup_deadline { - if settings.stall_cleanup { - // The hook's stand-in for a server that never finishes shutting - // down: the real join runs, and the wait after it does not return. - let stalled = async move { - let _ = server.join().await; - std::future::pending::<()>().await; - }; - let _ = tokio::time::timeout_at(deadline, stalled).await; - } else { - let _ = tokio::time::timeout_at(deadline, server.join()).await; - } - } else { - let _ = server.join().await; - } + // §8.1). Every other run's join gets the settle grace, and a join that + // outlives it is attached to the outcome as a teardown failure instead + // of holding the child before it prints. + let teardown = match cleanup_deadline { + Some(deadline) => { + if settings.stall_cleanup { + // The hook's stand-in for a server that never finishes + // shutting down: the real join runs, and the wait after it + // does not return. + let stalled = async move { + let _ = server.join().await; + std::future::pending::<()>().await; + }; + let _ = tokio::time::timeout_at(deadline, stalled).await; + } else { + let _ = tokio::time::timeout_at(deadline, server.join()).await; + } + None + } + None => match tokio::time::timeout(SETTLE_BOUND, server.join()).await { + Ok(Ok(_)) => None, + Ok(Err(error)) => Some(format!("the run's serve server did not shut down: {error}")), + Err(_) => Some(format!( + "the run's serve server did not finish shutting down within {}s", + SETTLE_BOUND.as_secs_f64() + )), + }, + }; let mut outcome = outcome.unwrap_or_else(|error| { harness_outcome(format!("the run failed to finish: {error}"), Vec::new()) }); + if let Some(teardown) = teardown { + // The run's own ending stands; the teardown failure marks the run + // failed (model-prompts §8.1). + if let Some(harness) = outcome.harness.as_mut() { + harness.push_str("; "); + harness.push_str(&teardown); + } else if let Some(error) = outcome.error.as_mut() { + error.push_str("; "); + error.push_str(&teardown); + } else { + outcome.error = Some(teardown); + } + } if outcome.duration_ms == 0. { outcome.duration_ms = duration_ms; } @@ -2788,7 +2920,7 @@ fn native_probe_settings( stall_cleanup: false, cleanup_budget_ms: None, stall_export: None, - block_after_wall_clock: false, + judge_budget_ms: None, } } @@ -2837,7 +2969,10 @@ async fn native_probe_child(params: &ChildParams) -> Result .join(format!("{arm}-{}-run-{run}.sock", scenario.id)) } +/// The marker a stalled child writes, beside its params: one per run, so a +/// bound counts from this child's stall and no other's. +fn run_stall_marker(options: &Options, arm: &str, scenario: &Scenario, run: usize) -> PathBuf { + options + .out + .join("children") + .join(arm) + .join(&scenario.id) + .join(format!("run-{run}.stall")) +} + /// The run's own account files, under the output root, never inside the run /// root: the export and the view the judge read. A re-judge reads them from /// here ([`read_saved_runs`]). @@ -3911,6 +4058,17 @@ async fn isolate_run( let operator_home = std::env::var_os("HOME").map(PathBuf::from); let boundary = run_boundary(options, workspace, env_home)?; let credentials = augmented_credentials(options); + let stall = options.stall.as_ref().and_then(|stall| { + stall.point_for(arm, &scenario.id).map(|point| ChildStall { + point, + marker: run_stall_marker(options, arm, scenario, run), + }) + }); + let broken = options + .broken + .as_ref() + .filter(|broken| broken.run.0 == arm && broken.run.1 == scenario.id) + .map(|broken| broken.outcome); let params = ChildParams { home: run_home.to_owned(), workspace: workspace.to_owned(), @@ -3946,7 +4104,9 @@ async fn isolate_run( stall_cleanup: options.stall_cleanup, cleanup_budget_ms: options.cleanup_budget_ms, stall_export: options.stall_export.clone(), - block_after_wall_clock: options.block_after_wall_clock, + stall, + broken, + judge_budget_ms: options.judge_budget_ms, native_tools: native.to_vec(), probe_only: false, }; @@ -4064,13 +4224,18 @@ async fn native_probe( stall_cleanup: false, cleanup_budget_ms: None, stall_export: None, - block_after_wall_clock: false, + stall: None, + broken: None, + judge_budget_ms: None, native_tools: Vec::new(), probe_only: true, }; let params_path = root.join("params.json"); std::fs::write(¶ms_path, serde_json::to_string_pretty(¶ms)?)?; - let outcome = spawn_child_json( + // The probe's set is all the parent needs: any ending without it fails + // the evaluation before its runs, as a startup probe that never finished + // always did. + let ChildOutput::Read(outcome) = spawn_child_json( options, ¶ms_path, ¶ms, @@ -4079,7 +4244,9 @@ async fn native_probe( Some(STARTUP_BOUND), ) .await? - .ok_or("the native probe's serve child did not exit within its bound")?; + else { + return Err("the native probe's serve child did not exit within its bound".into()); + }; serde_json::from_value(outcome["nativeTools"].clone()) .map_err(|error| format!("the native probe printed no tool set: {error}").into()) } @@ -4334,11 +4501,68 @@ fn child_environment( Ok(env) } +/// How the parent's read of a serve child's output ended. +#[derive(Clone, Copy, PartialEq, Eq)] +enum ReadEnd { + /// The reader saw the write end close: the child's output is complete. + Eof, + /// The read's deadline passed with the write end still open: the output + /// the reader collected is the child's, but the read was cut short. + Deadline, +} + +/// The run's own ending, as the child reported it before its outcome line: a +/// parent that ends the child before the outcome keeps the stop the run +/// reached and records the supervisor failure beside it (model-prompts +/// §8.1). +#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct RunProgress { + stop: String, + timed_out: bool, +} + +/// What one serve child's life left the parent: the eight endings of +/// [`spawn_child_json`] group into these four records. +enum ChildOutput { + /// The output holds the marker's JSON line, and the read reached EOF (or + /// the line was complete when the read's deadline cut it). + Read(Value), + /// The hard bound ended a child that had already printed its complete + /// line: the line stands, and the teardown did not settle. + Unsettled { value: Value, error: String }, + /// The child exited, but the read was cut at its deadline before the + /// marker's line arrived. + CutShort { progress: Option }, + /// The hard bound ended the child before it printed the marker's line. + Killed { progress: Option }, +} + +/// The JSON object of the first line that names `marker`, or `None` when the +/// output holds no such line; a line that does not parse is an error. +fn marker_value(text: &str, marker: &str) -> std::result::Result, serde_json::Error> { + match text.lines().find(|line| line.contains(marker)) { + Some(line) => { + let json = &line[line.find('{').unwrap_or(line.len())..]; + serde_json::from_str(json).map(Some) + } + None => Ok(None), + } +} + +/// The run's own ending, if the child reported it before its outcome line. +fn progress_value(text: &str) -> Option { + let line = text + .lines() + .find(|line| line.starts_with("{\"runProgress\""))?; + let value: Value = serde_json::from_str(line).ok()?; + serde_json::from_value(value["runProgress"].clone()).ok() +} + /// Spawns the run's serve child and reads its outcome line. The child runs /// under the parent's hard bound on one run: one that is still alive when the -/// bound expires is killed with its process group and recorded as a run that -/// stopped on its wall clock without an export or a judgment (model-prompts -/// §8.1). +/// bound expires is killed with its process group, and what the child had +/// already printed decides the record (model-prompts §8.1). async fn spawn_child( options: &Options, params_path: &Path, @@ -4358,33 +4582,106 @@ async fn spawn_child( ) .await? { - Some(outcome) => Ok(serde_json::from_value(outcome)?), - None => Ok(bound_outcome(params, bound, started.elapsed())), + ChildOutput::Read(value) => Ok(serde_json::from_value(value)?), + ChildOutput::Unsettled { value, error } => unsettled_outcome(value, error), + ChildOutput::Killed { progress } => { + Ok(bound_outcome(params, bound, started.elapsed(), progress)) + } + ChildOutput::CutShort { progress } => { + Ok(cut_short_outcome(params, started.elapsed(), progress)) + } } } /// The parent's hard bound on one run's serve child: the run's wall clock, the /// startup before it ([`STARTUP_BOUND`]), the cleanup budget after it — or the -/// judge's own retry budget when that is longer — and the grace to read the +/// judge phase's budget when that is longer — and the grace to read the /// output the child may print. A child stuck in blocking work may never reach -/// its own cleanup, so this bound is what ends it. +/// its own cleanup, so this bound is what ends it. A test stall hook replaces +/// it with its own bound and counts that from the child's stall marker. fn child_hard_bound(options: &Options, params: &ChildParams, wall_clock: Duration) -> Duration { - options - .hard_bound_ms - .map(Duration::from_millis) - .unwrap_or_else(|| { + match (¶ms.stall, &options.stall) { + (Some(_), Some(stall)) => Duration::from_millis(stall.bound_ms), + _ => { wall_clock + STARTUP_BOUND - + cleanup_budget(params.stall_cleanup, params.cleanup_budget_ms).max(JUDGE_BUDGET) + + cleanup_budget(params.stall_cleanup, params.cleanup_budget_ms) + .max(judge_phase_budget(params.judge_budget_ms)) + settle_bound(params.stall_cleanup) - }) + } + } } -/// The record of a run whose serve child the parent killed at its hard bound: -/// the child printed no outcome, so the run takes the wall-clock stop the -/// supervisor vouches for, with no export and no judgment (model-prompts -/// §8.1). -fn bound_outcome(params: &ChildParams, bound: Duration, elapsed: Duration) -> ChildOutcome { +/// The instant a stalled child's bound falls: the bound counts from the +/// marker the child writes at its stall, so the bound under test is not spent +/// on the startup before it. A marker that never appears leaves the bound at +/// [`STARTUP_BOUND`], the cap a child that never reports its stall gets. +async fn bound_after_stall(marker: &Path, bound: Duration) -> tokio::time::Instant { + let startup = tokio::time::Instant::now() + STARTUP_BOUND; + loop { + if marker.exists() { + return tokio::time::Instant::now() + bound; + } + if tokio::time::Instant::now() >= startup { + return startup; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// The record of a run the parent ended before its child printed its outcome: +/// a supervisor failure, unless the child had reported the run's own +/// wall-clock stop, which the record keeps (model-prompts §8.1). +fn bound_outcome( + params: &ChildParams, + bound: Duration, + elapsed: Duration, + progress: Option, +) -> ChildOutcome { + supervisor_outcome( + params, + elapsed, + progress, + format!( + "the run's serve child did not exit within the parent's bound of {}s", + bound.as_secs_f64() + ), + "the run's Timeline was not exported: its serve child did not exit within the parent's \ + bound" + .to_owned(), + ) +} + +/// The record of a run whose child exited before its outcome was read: a +/// supervisor failure, unless the child had reported the run's own wall-clock +/// stop, which the record keeps (model-prompts §8.1). +fn cut_short_outcome( + params: &ChildParams, + elapsed: Duration, + progress: Option, +) -> ChildOutcome { + supervisor_outcome( + params, + elapsed, + progress, + "the run's serve child exited before its outcome was read within the parent's deadline" + .to_owned(), + "the run's Timeline was not exported: its serve child exited before its outcome was \ + read" + .to_owned(), + ) +} + +/// The record of a run the supervisor ended: a failure, with no export and no +/// judgment. A reported wall-clock stop is the run's own ending and is kept; +/// every other ending is the supervisor failure `error` names. +fn supervisor_outcome( + params: &ChildParams, + elapsed: Duration, + progress: Option, + error: String, + judge_error: String, +) -> ChildOutcome { let scenario: Option = serde_json::from_value(params.scenario.clone()).ok(); let probes = scenario .as_ref() @@ -4398,29 +4695,26 @@ fn bound_outcome(params: &ChildParams, bound: Duration, elapsed: Duration) -> Ch quote: probe.quote, }) .collect(); + let (stop, timed_out) = match progress { + Some(progress) if progress.timed_out => (progress.stop, true), + _ => ("error".to_owned(), false), + }; ChildOutcome { preflight: Vec::new(), harness: None, export: None, view: None, session: None, - stop: "seconds".into(), - timed_out: true, + stop, + timed_out, turns: 0, window: None, duration_ms: elapsed.as_secs_f64() * 1000., decline_retries: 0, switch_retries: 0, - error: Some(format!( - "the run's serve child did not exit within the parent's bound of {}s", - bound.as_secs_f64() - )), + error: Some(error), judge_outcome: JudgeOutcome::NotAsked, - judge_error: Some( - "the run's Timeline was not exported: its serve child did not exit within the \ - parent's bound" - .to_owned(), - ), + judge_error: Some(judge_error), judge_reasks: 0, judge_calls: Vec::new(), temperature_dropped: false, @@ -4433,6 +4727,23 @@ fn bound_outcome(params: &ChildParams, bound: Duration, elapsed: Duration) -> Ch } } +/// The record of a run whose child printed its complete outcome and then did +/// not exit: the outcome stands, and the teardown failure is attached so the +/// run is failed (model-prompts §8.1). +fn unsettled_outcome(value: Value, error: String) -> Result { + let mut outcome: ChildOutcome = serde_json::from_value(value)?; + if let Some(harness) = outcome.harness.as_mut() { + harness.push_str("; "); + harness.push_str(&error); + } else if let Some(existing) = outcome.error.as_mut() { + existing.push_str("; "); + existing.push_str(&error); + } else { + outcome.error = Some(error); + } + Ok(outcome) +} + /// The serve children this test binary started, by their params path: a /// test finds the child another run's failure must have taken down. #[cfg(test)] @@ -4440,9 +4751,11 @@ static SPAWNED: Mutex> = Mutex::new(Vec::new()); /// Spawns a child and reads the JSON object of the output line that names /// `marker`: a run's child prints its outcome under `judgeOutcome`, the -/// native probe's child its declared tool set under `nativeTools`. `hard_bound` -/// is the parent's limit on the child's whole life; the answer is `None` when -/// that bound expired first, and the child's group was killed. +/// native probe's child its declared tool set under `nativeTools`. +/// `hard_bound` is the parent's limit on the child's whole life. The answer +/// tells the four endings apart: a complete line, a complete line printed by +/// a child the bound had to end, a read cut at its deadline before the line, +/// and a child the bound ended before the line. async fn spawn_child_json( options: &Options, params_path: &Path, @@ -4450,7 +4763,7 @@ async fn spawn_child_json( cancel: &CancellationToken, marker: &str, hard_bound: Option, -) -> Result> { +) -> Result { let (executable, args, test_binary) = child_command(params_path); let env = child_environment(options, params, params_path, test_binary)?; let mut command = tokio::process::Command::new(&executable); @@ -4486,7 +4799,10 @@ async fn spawn_child_json( #[cfg(unix)] let mut group = ChildGroup::new(child.id().unwrap_or_default()); // The parent's hard bound runs from the spawn, so a child that never - // reaches its own cleanup is still ended. + // reaches its own cleanup is still ended. A test stall hook counts its + // bound from the child's marker instead: a slow start does not spend the + // bound, and the marker proves the child reached the stall under test. + let stall_marker = params.stall.as_ref().map(|stall| stall.marker.clone()); let deadline = hard_bound.map(|bound| tokio::time::Instant::now() + bound); // Drain the pipe while the child runs: the child may print more than a // pipe holds (the run's logged output rides the same stream), and a full @@ -4532,26 +4848,57 @@ async fn spawn_child_json( return Err("the evaluation was cancelled".into()); } _ = async { - match deadline { - Some(deadline) => tokio::time::sleep_until(deadline).await, - None => std::future::pending().await, - } + let Some(bound) = hard_bound else { + return std::future::pending::<()>().await; + }; + let until = match &stall_marker { + Some(marker) => bound_after_stall(marker, bound).await, + None => tokio::time::Instant::now() + bound, + }; + tokio::time::sleep_until(until).await } => { // The child is still alive at the parent's hard bound: it may be // stuck in blocking work and never reach its own cleanup. Its - // group is killed so no member outlives the run, and the run gets - // the outcome the supervisor can vouch for. + // group is killed so no member outlives the run; every writer is + // gone, so the reader reaches EOF, and what the child printed + // before the bound is in hand when the outcome is decided. #[cfg(unix)] group.kill(); let _ = child.kill().await; let _ = child.wait().await; - if let Some(reading) = reading { + if let Some(mut reading) = reading + && tokio::time::timeout(KILLED_READ_GRACE, &mut reading) + .await + .is_err() + { reading.abort(); let _ = reading.await; } - return Ok(None); + let output = std::mem::take(&mut *collected.lock().unwrap()); + let text = String::from_utf8_lossy(&output); + let bound = hard_bound.unwrap_or_default(); + return match marker_value(&text, marker).ok().flatten() { + // The child printed its complete line and only could not + // exit: the outcome stands, and the teardown failure is + // attached (model-prompts §8.1). + Some(value) => Ok(ChildOutput::Unsettled { + value, + error: format!( + "the run's serve child did not exit within the parent's bound of {}s", + bound.as_secs_f64() + ), + }), + // No complete line: a supervisor failure, unless the child + // reported the run's own wall-clock stop before the bound. + None => Ok(ChildOutput::Killed { + progress: progress_value(&text), + }), + }; } }; + // Whether the child's output was read to its end or the read was cut at + // its deadline: the same missing line means different things. + let mut read_end = ReadEnd::Eof; let output = match reading { Some(mut reading) => { // The child has exited, but a member it left behind may hold the @@ -4561,10 +4908,14 @@ async fn spawn_child_json( // the reader is dropped; what it collected is still the child's // output, so a missing outcome line is reported as one. let grace = settle_bound(params.stall_cleanup); - let until = deadline.map_or_else( - || tokio::time::Instant::now() + grace, - |deadline| deadline.min(tokio::time::Instant::now() + grace), - ); + let until = if stall_marker.is_some() { + tokio::time::Instant::now() + grace + } else { + deadline.map_or_else( + || tokio::time::Instant::now() + grace, + |deadline| deadline.min(tokio::time::Instant::now() + grace), + ) + }; let read = tokio::select! { _ = cancel.cancelled() => { #[cfg(unix)] @@ -4584,7 +4935,9 @@ async fn spawn_child_json( // holds the write end of its stdout: the read's grace ran // out. The group is killed so no member outlives the // harness, and the output the reader collected is what - // the outcome line is looked for in. + // the outcome line is looked for in. Whether the child's + // own line arrived is decided by that output. + read_end = ReadEnd::Deadline; #[cfg(unix)] group.kill(); reading.abort(); @@ -4619,22 +4972,34 @@ async fn spawn_child_json( } return Err(format!("the run's serve child exited with {status}").into()); } - let line = text - .lines() - .find(|line| line.contains(marker)) - .ok_or_else(|| { - format!( - "the run's serve child printed no {marker} line: {}", - text.trim() - ) - })?; // A test-binary child runs under the test harness, which opens its - // output line with the test's name; the outcome is the rest of the - // line. - let json = &line[line - .find('{') - .ok_or("the child's outcome line carries no JSON")?..]; - Ok(Some(serde_json::from_str(json)?)) + // output line with the test's name; the outcome is the rest of the line. + let value = match marker_value(&text, marker) { + Ok(value) => value, + // A read cut at its deadline may hold half a line: that is the + // supervisor's ending, decided below, not a malformed answer. + Err(_) if read_end == ReadEnd::Deadline => None, + // A read that reached EOF holds the child's whole output: a line + // that does not parse is a malformed answer and fails the evaluation + // as it always did. + Err(error) => return Err(error.into()), + }; + match (value, read_end) { + // A complete line stands whether the read reached EOF or was cut + // afterwards: a member of the child's group held the write end, and + // the line was already in hand. + (Some(value), _) => Ok(ChildOutput::Read(value)), + // The child exited before its line could be read: one run's + // supervisor failure, and the evaluation continues. + (None, ReadEnd::Deadline) => Ok(ChildOutput::CutShort { + progress: progress_value(&text), + }), + (None, ReadEnd::Eof) => Err(format!( + "the run's serve child printed no {marker} line: {}", + text.trim() + ) + .into()), + } } /// The serve child's process group: the child leads it (`process_group(0)`), @@ -4852,6 +5217,7 @@ async fn drive_once( cancel: &CancellationToken, producer: &ProducerState, tools: Option>, + stall: Option<&ChildStall>, ) -> Result { let socket = settings .unix_path @@ -4891,11 +5257,21 @@ async fn drive_once( judging: Judging::not_asked(scenario, None), }); } - if driven.timed_out && settings.block_after_wall_clock { + // The ending the run reached, printed before any cleanup: a parent that + // ends the child before its outcome line keeps the run's own stop and + // records the supervisor failure beside it (model-prompts §8.1). + println!( + "{}", + json!({"runProgress": {"stop": driven.stop, "timedOut": driven.timed_out}}) + ); + if let Some(stall) = stall + && stall.point == StallPoint::AfterWallClock + && driven.timed_out + { // The hook's stand-in for a child stuck in blocking work after its // wall clock: no timer of the child's can end it, so only the - // parent's hard bound does. - std::thread::sleep(Duration::from_secs(600)); + // parent's hard bound does. The marker is what the bound counts from. + stall_here(stall, "after its run's wall clock")?; } let close = client.rpc("session.close", json!({"sessionId": driven.session})); // A run that stopped on its wall clock runs its close under the one @@ -4984,8 +5360,13 @@ async fn drive_once( let export = String::from_utf8_lossy_owned(export); let (turns, failed_turn) = turns_in_export(&export); driven.turns = turns; + // The export is read after the run's own ending is fixed: a + // failed turn it records cannot replace the wall-clock stop the + // run reached, as the deferred window read below cannot either + // (model-prompts §8.1). if let Some(error) = failed_turn && driven.error.is_none() + && !driven.timed_out { driven.stop = "error"; driven.error = Some(error); @@ -5039,7 +5420,27 @@ async fn drive_once( ), } } else { - judge_export(&host, &resolver, judge, scenario, &view, limits, cancel).await + // A run that did not stop on its wall clock gives its judge phase + // its own budget: the judge may legitimately make several calls, and + // one that never answers must not hold the child — and the worker + // that runs it — open. The run keeps the stop it reached, its export + // and every call recorded so far (model-prompts §8.1). + let budget = judge_phase_budget(settings.judge_budget_ms); + match tokio::time::timeout( + budget, + judge_export(&host, &resolver, judge, scenario, &view, limits, cancel), + ) + .await + { + Ok(judging) => judging, + Err(_) => Judging::unfinished( + scenario, + format!( + "the judge did not finish within its phase budget of {}s", + budget.as_secs_f64() + ), + ), + } }; Ok(Finished { driven, @@ -11197,8 +11598,9 @@ mod tests { stall_cleanup: false, cleanup_budget_ms: None, stall_export: None, - block_after_wall_clock: false, - hard_bound_ms: None, + stall: None, + broken: None, + judge_budget_ms: None, defaults: None, node: None, js_runtime: None, @@ -12789,7 +13191,7 @@ mod tests { stall_cleanup: false, cleanup_budget_ms: None, stall_export: None, - block_after_wall_clock: false, + judge_budget_ms: None, }; let mut scenario = scenario(Vec::new()); scenario.budget.seconds = 0.5; @@ -12818,6 +13220,7 @@ mod tests { &cancel, &producer, None, + None, ); tokio::pin!(run); // The client connects and the Session attaches with real I/O; @@ -14380,8 +14783,9 @@ mod tests { stall_cleanup: false, cleanup_budget_ms: None, stall_export: None, - block_after_wall_clock: false, - hard_bound_ms: None, + stall: None, + broken: None, + judge_budget_ms: None, defaults: None, node: None, js_runtime: None, @@ -14684,7 +15088,9 @@ mod tests { stall_cleanup: false, cleanup_budget_ms: None, stall_export: None, - block_after_wall_clock: false, + stall: None, + broken: None, + judge_budget_ms: None, native_tools: native .iter() .map(|name| ((*name).to_owned(), ToolSource::Builtin)) @@ -15249,10 +15655,14 @@ mod tests { let out = fixture.directory.join("out"); let mut options = fixture.options(out.clone()); options.jobs = 1; - options.block_after_wall_clock = true; - // The bound under test is the parent's two seconds per child; the - // guard only turns a hang into a failed assertion. - options.hard_bound_ms = Some(2_000); + options.stall = Some(Stall { + run: None, + point: StallPoint::AfterWallClock, + // The bound under test is the parent's two seconds after the + // child reaches its stall; the guard only turns a hang into a + // failed assertion. + bound_ms: 2_000, + }); let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await .expect("the evaluation returns though each child blocks after its wall clock") @@ -15288,6 +15698,14 @@ mod tests { .join(arm) .join("case") .join("run-0.json"); + assert!( + out.join("children") + .join(arm) + .join("case") + .join("run-0.stall") + .exists(), + "the child reached its stall before the bound ({arm})" + ); let pid = SPAWNED .lock() .unwrap() @@ -15302,6 +15720,373 @@ mod tests { } } + /// The fixture's basic scenario at a window the judge's view fits: one + /// message, a plain answer, and the workspace file's read. + fn judged_scenario() -> Value { + json!({ + "description": "A quick probe", + "message": "Run the quick probe.", + "budget": {"turns": 4, "seconds": 60, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + }) + } + + /// A second scenario beside the fixture's own: it must run on the slot a + /// stalled or failed first scenario frees, and its judge answers at once. + fn next_scenario(fixture: &Fixture, window: u64) { + let next = fixture.scenarios.join("next"); + std::fs::create_dir_all(next.join("workspace")).unwrap(); + std::fs::write(next.join("workspace").join("notes.txt"), FILE_TEXT).unwrap(); + std::fs::write( + next.join("scenario.json"), + serde_json::to_string_pretty(&json!({ + "message": "Finish the next scenario.", + "budget": {"turns": 4, "seconds": 60, "window": window}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + })) + .unwrap(), + ) + .unwrap(); + } + + /// A child that exits before it prints its outcome, with a member of its + /// group still holding its standard output, is one run's supervisor + /// failure: the evaluation keeps its next scheduled run and judges it + /// (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_child_that_exits_before_its_outcome_leaves_the_next_run_intact() { + let fixture = Fixture::with_window( + "exit-before-outcome", + reads_the_workspace_file, + judged_scenario(), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + next_scenario(&fixture, 131_072); + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + // The read grace the member outlives is the test hook's 200ms. + options.stall_cleanup = true; + let marker = fixture.directory.join("leave.marker"); + options.leave_member = Some((true, marker.clone())); + options.broken = Some(BrokenRun { + run: ("current".into(), "case".into()), + outcome: BrokenOutcome::Silent, + }); + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) + .await + .expect("the evaluation returns after one run exits before its outcome") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in records + .iter() + .filter(|record| record["scenario"] == "case" && record["arm"] == "current") + { + assert_eq!(record["stop"], "error", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "not_asked", "{record}"); + let error = record["error"].as_str().unwrap_or_default(); + assert!( + error.contains("exited before its outcome was read"), + "the run says why it has no outcome: {record}" + ); + assert!( + !out.join("outputs") + .join("current") + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "an unread outcome leaves no export: {record}" + ); + } + for record in records.iter().filter(|record| record["scenario"] == "next") { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + let members = left_members(&marker); + assert_eq!(members.len(), 4, "each child left its member"); + for pid in members { + assert!( + child_tree_gone(pid).await, + "the member and its group are gone (pid {pid})" + ); + } + } + + /// A child that exits before its outcome line with nothing holding its + /// output is a malformed run: the evaluation fails it as it failed + /// before (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_child_that_exits_without_its_outcome_fails_the_evaluation() { + let fixture = Fixture::start( + "silent-child", + reads_the_workspace_file, + isolated_scenario(), + &[("notes.txt", FILE_TEXT)], + ) + .await; + let mut options = fixture.options(fixture.directory.join("out")); + options.broken = Some(BrokenRun { + run: ("current".into(), "case".into()), + outcome: BrokenOutcome::Silent, + }); + let error = fixture + .evaluate(&options) + .await + .expect_err("a run without an outcome fails the evaluation") + .to_string(); + assert!( + error.contains("printed no judgeOutcome line"), + "the error names the missing outcome: {error}" + ); + } + + /// A child whose completed output line is not JSON is still a malformed + /// run: the parse error is surfaced, not recorded as a timeout + /// (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_garbled_outcome_line_fails_the_evaluation() { + let fixture = Fixture::start( + "garbled-child", + reads_the_workspace_file, + isolated_scenario(), + &[("notes.txt", FILE_TEXT)], + ) + .await; + let mut options = fixture.options(fixture.directory.join("out")); + options.broken = Some(BrokenRun { + run: ("current".into(), "case".into()), + outcome: BrokenOutcome::Garbled, + }); + let error = fixture + .evaluate(&options) + .await + .expect_err("a garbled outcome fails the evaluation") + .to_string(); + assert!( + error.contains("EOF while parsing"), + "the error is the parse error of the completed line: {error}" + ); + } + + /// A child that never prints its outcome is a supervisor failure, not a + /// wall-clock stop the supervisor invents: the record names the parent's + /// bound, and the run that follows on the same worker is judged + /// (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_child_stuck_before_its_outcome_is_a_supervisor_failure() { + let fixture = Fixture::with_window( + "stuck-before-outcome", + reads_the_workspace_file, + judged_scenario(), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + next_scenario(&fixture, 131_072); + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + options.stall = Some(Stall { + run: Some(("current".into(), "case".into())), + point: StallPoint::BeforeOutcome, + bound_ms: 2_000, + }); + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) + .await + .expect("the evaluation returns though a child never prints its outcome") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in records + .iter() + .filter(|record| record["scenario"] == "case" && record["arm"] == "current") + { + assert_eq!(record["stop"], "error", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "not_asked", "{record}"); + let error = record["error"].as_str().unwrap_or_default(); + assert!( + error.contains("did not exit within the parent's bound"), + "the run names the supervisor's bound: {record}" + ); + assert!( + record["judgeError"] + .as_str() + .unwrap_or_default() + .contains("was not exported"), + "the run says why it was not judged: {record}" + ); + assert!( + out.join("children") + .join("current") + .join("case") + .join("run-0.stall") + .exists(), + "the child reached its stall before the bound: {record}" + ); + assert!( + !out.join("outputs") + .join("current") + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "a child with no outcome leaves no export: {record}" + ); + } + for record in records + .iter() + .filter(|record| !(record["scenario"] == "case" && record["arm"] == "current")) + { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + } + + /// A child that printed its complete outcome and then cannot exit keeps + /// its outcome: the run's stop, its export and its judgment stand, and + /// the teardown failure is attached as an error (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_child_that_printed_its_outcome_and_blocks_keeps_it() { + let fixture = Fixture::with_window( + "stuck-after-outcome", + reads_the_workspace_file, + judged_scenario(), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + next_scenario(&fixture, 131_072); + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + options.stall = Some(Stall { + run: Some(("current".into(), "case".into())), + point: StallPoint::AfterOutcome, + bound_ms: 2_000, + }); + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) + .await + .expect("the evaluation returns though a child cannot exit") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in records + .iter() + .filter(|record| record["scenario"] == "case" && record["arm"] == "current") + { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + let error = record["error"].as_str().unwrap_or_default(); + assert!( + error.contains("did not exit within the parent's bound"), + "the run names the teardown failure: {record}" + ); + assert!( + out.join("outputs") + .join("current") + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "the printed outcome keeps its export: {record}" + ); + } + for record in records + .iter() + .filter(|record| !(record["scenario"] == "case" && record["arm"] == "current")) + { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + } + + /// A run whose judge outlives the judge phase's budget keeps the stop it + /// reached and its export, records a failed judge call, and frees the + /// worker: the next scenario runs on the same slot (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_run_whose_judge_outlives_its_phase_budget_keeps_its_stop() { + fn hold_the_case_judge(text: &str) -> Option { + (text.contains("You check statements") && text.contains("Run the quick probe.")) + .then_some(HELD_PAST_GUARD) + } + let fixture = Fixture::holding( + "judge-phase-budget", + reads_the_workspace_file, + hold_the_case_judge, + json!({ + "description": "An idle run", + "message": "Run the quick probe.", + "budget": {"turns": 4, "seconds": 60, "window": 131072}, + "probes": [{"id": "ran", "kind": "must_show", + "text": "the run has a transcript"}] + }), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + next_scenario(&fixture, 131_072); + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + options.judge_budget_ms = Some(1_000); + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) + .await + .expect("the evaluation returns though a judge never answers") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in records.iter().filter(|record| record["scenario"] == "case") { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "call_failed", "{record}"); + assert_eq!(record["error"], Value::Null, "{record}"); + assert!( + record["judgeError"] + .as_str() + .unwrap_or_default() + .contains("did not finish within its phase budget"), + "the run says why its judge is unfinished: {record}" + ); + assert!( + out.join("outputs") + .join(record["arm"].as_str().unwrap()) + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "the closed run still exports its Timeline: {record}" + ); + assert!( + record["durationMs"].as_f64().unwrap_or_default() < 20_000.0, + "the run ends within its phase budget, not at a longer one: {record}" + ); + } + for record in records.iter().filter(|record| record["scenario"] == "next") { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + assert_eq!( + fixture.judge().len(), + 4, + "both case runs asked their held judge; both next runs were answered" + ); + } + /// A child that fails after it started a member of its group does not /// leave it behind: the group the child leads is killed on the non-zero /// exit, so the member is gone when `evaluate` returns. The failing From 0e1d2f0fac35cace2a4561a414a2b0955919a19a Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 01:19:03 +0800 Subject: [PATCH 29/32] fix(xtask): read the run's ending past the harness prefix The child's first output line carries the test harness's test-name prefix, so the run's reported ending is read from the first line that names it, and the JSON object is parsed from that line's first brace. The judge phase budget test runs both arms at once, so a loaded host cannot spend the guard on four sequential starts. --- xtask/src/scenario_eval.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index d214efa57e..353b9bfa67 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -4552,10 +4552,9 @@ fn marker_value(text: &str, marker: &str) -> std::result::Result, /// The run's own ending, if the child reported it before its outcome line. fn progress_value(text: &str) -> Option { - let line = text - .lines() - .find(|line| line.starts_with("{\"runProgress\""))?; - let value: Value = serde_json::from_str(line).ok()?; + let line = text.lines().find(|line| line.contains("\"runProgress\""))?; + let json = &line[line.find('{')?..]; + let value: Value = serde_json::from_str(json).ok()?; serde_json::from_value(value["runProgress"].clone()).ok() } @@ -16042,7 +16041,9 @@ mod tests { next_scenario(&fixture, 131_072); let out = fixture.directory.join("out"); let mut options = fixture.options(out.clone()); - options.jobs = 1; + // Both case runs hold a slot while their judges time out; the next + // scenarios run once those slots are free. + options.jobs = 2; options.judge_budget_ms = Some(1_000); let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await From e735629b40738b5101ca5fd3bf45b54271894d3b Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 02:09:50 +0800 Subject: [PATCH 30/32] test(xtask): pin the join bound and the export ending rule The non-wall-clock join is pinned by a_run_whose_server_never_settles_keeps_its_outcome: a new afterShutdown stall point writes the child's marker before the join and never lets the shutdown settle, the join runs under the settle grace, and the run keeps its stop, export and judgment with the teardown failure attached as an error, so the child prints its outcome and the next scenario runs on the same slot. The settle grace is the test hook's shorter grace when the hook is set; a run without the hook still waits the product's 30 seconds. The export's ending rule is a named function, settle_failed_turn, pinned by a_failed_turn_in_the_export_does_not_replace_a_wall_clock_stop: a failed turn in the export fails a run that did not stop on its wall clock, and a run that did keeps its seconds stop. --- xtask/src/scenario_eval.rs | 207 ++++++++++++++++++++++++++++++++----- 1 file changed, 183 insertions(+), 24 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 353b9bfa67..47a46bcf9d 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -1349,14 +1349,16 @@ impl Stall { } /// Where a stalled child stops: before it prints anything (a startup stall), -/// after it printed its outcome (a child that cannot exit), or after its run -/// stopped on its wall clock (a cleanup that never settles). +/// after it printed its outcome (a child that cannot exit), after its run +/// stopped on its wall clock (a cleanup that never settles), or before its +/// served App Server's join finishes (a shutdown that never settles). #[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] enum StallPoint { BeforeOutcome, AfterOutcome, AfterWallClock, + AfterShutdown, } /// A test hook: how a run's child ends before its outcome line. @@ -2849,9 +2851,9 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child // under the one deadline the wall-clock stop fixed: the tree close waits // for the move the run stopped waiting on, and the child must print its // outcome and exit so the parent's worker is released (model-prompts - // §8.1). Every other run's join gets the settle grace, and a join that - // outlives it is attached to the outcome as a teardown failure instead - // of holding the child before it prints. + // §8.1). Every other run's join gets the settle grace, or the test hook's + // shorter grace, and a join that outlives it is attached to the outcome + // as a teardown failure instead of holding the child before it prints. let teardown = match cleanup_deadline { Some(deadline) => { if settings.stall_cleanup { @@ -2868,14 +2870,38 @@ async fn child_outcome(params: &ChildParams, preflight: &Arc) -> Child } None } - None => match tokio::time::timeout(SETTLE_BOUND, server.join()).await { - Ok(Ok(_)) => None, - Ok(Err(error)) => Some(format!("the run's serve server did not shut down: {error}")), - Err(_) => Some(format!( - "the run's serve server did not finish shutting down within {}s", - SETTLE_BOUND.as_secs_f64() - )), - }, + None => { + let settle = settle_bound(settings.stall_cleanup); + let stalled = params + .stall + .as_ref() + .filter(|stall| stall.point == StallPoint::AfterShutdown); + if let Some(stall) = stalled { + // The hook's stand-in for a server that never finishes + // shutting down: the real join runs, and the wait after it + // does not return. The marker proves the child reached the + // shutdown under test. + let _ = std::fs::write(&stall.marker, "before its server's shutdown settles"); + } + let join = async move { + if stalled.is_some() { + let _ = server.join().await; + std::future::pending().await + } else { + server.join().await + } + }; + match tokio::time::timeout(settle, join).await { + Ok(Ok(_)) => None, + Ok(Err(error)) => { + Some(format!("the run's serve server did not shut down: {error}")) + } + Err(_) => Some(format!( + "the run's serve server did not finish shutting down within {}s", + settle.as_secs_f64() + )), + } + } }; let mut outcome = outcome.unwrap_or_else(|error| { harness_outcome(format!("the run failed to finish: {error}"), Vec::new()) @@ -5359,17 +5385,7 @@ async fn drive_once( let export = String::from_utf8_lossy_owned(export); let (turns, failed_turn) = turns_in_export(&export); driven.turns = turns; - // The export is read after the run's own ending is fixed: a - // failed turn it records cannot replace the wall-clock stop the - // run reached, as the deferred window read below cannot either - // (model-prompts §8.1). - if let Some(error) = failed_turn - && driven.error.is_none() - && !driven.timed_out - { - driven.stop = "error"; - driven.error = Some(error); - } + settle_failed_turn(&mut driven, failed_turn); export } Err(error) => { @@ -5512,6 +5528,20 @@ fn turns_in_export(export: &str) -> (u32, Option) { (turns, failed) } +/// Applies the export's turn account to a run's own ending: a failed turn it +/// records fails a run that did not stop on its wall clock, and cannot replace +/// the wall-clock stop the run reached, as the deferred window read cannot +/// either (model-prompts §8.1). +fn settle_failed_turn(driven: &mut Driven, failed_turn: Option) { + if let Some(error) = failed_turn + && driven.error.is_none() + && !driven.timed_out + { + driven.stop = "error"; + driven.error = Some(error); + } +} + pub(crate) async fn selection( server: &RunningServer, target: &ModelId, @@ -10017,6 +10047,48 @@ mod tests { assert_eq!(turns_in_export(""), (0, None)); } + /// The export's failed turn fails a run that did not stop on its wall + /// clock, but a run that did keeps that stop: a run can reach its wall + /// clock with a failed turn in its export that its notice stream did not + /// deliver before the stop, and the stop it reached stands + /// (model-prompts §8.1). Dedicated, because the flows that end on a + /// failed turn return before their export is read, so no flow brings the + /// two endings together. + #[test] + fn a_failed_turn_in_the_export_does_not_replace_a_wall_clock_stop() { + fn driven(stop: &'static str, timed_out: bool) -> Driven { + Driven { + session: String::new(), + stop, + timed_out, + cleanup_deadline: None, + turns: 0, + window: None, + decline_retries: 0, + switch_retries: 0, + error: None, + } + } + let failed_turn = || Some("main: the turn failed: provider error".to_owned()); + + let mut stopped = driven("seconds", true); + settle_failed_turn(&mut stopped, failed_turn()); + assert_eq!(stopped.stop, "seconds", "the wall-clock stop stands"); + assert_eq!( + stopped.error, None, + "the export's failed turn does not replace the stop's ending" + ); + + let mut idle = driven("idle", false); + settle_failed_turn(&mut idle, failed_turn()); + assert_eq!(idle.stop, "error", "a failed turn fails an idle run"); + assert_eq!( + idle.error.as_deref(), + Some("main: the turn failed: provider error"), + "the run records the failed turn's error" + ); + } + /// A declared tool without a source cannot come from the product: the /// request holds `ToolDefinition` values, whose `source` is a required /// field. The probe fails naming the tool instead of dropping it from @@ -15719,6 +15791,93 @@ mod tests { } } + /// A run that did not stop on its wall clock keeps the outcome it reached + /// when its served App Server's shutdown never settles: the join is + /// bounded by the settle grace, the teardown failure is attached as an + /// error, and the child prints its outcome and exits, so the next scenario + /// runs on the same slot (model-prompts §8.1). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_run_whose_server_never_settles_keeps_its_outcome() { + let fixture = Fixture::with_window( + "server-join-stall", + reads_the_workspace_file, + judged_scenario(), + &[("notes.txt", FILE_TEXT)], + 131_072, + ) + .await; + next_scenario(&fixture, 131_072); + let out = fixture.directory.join("out"); + let mut options = fixture.options(out.clone()); + options.jobs = 1; + // The shutdown under test never settles, and the settle grace is the + // test hook's 200ms, so the bound is reached without a real wait. The + // run itself does not stop on its wall clock. + options.stall_cleanup = true; + options.stall = Some(Stall { + run: Some(("current".into(), "case".into())), + point: StallPoint::AfterShutdown, + // The parent's own bound stays past the child's settle grace, so + // the child's ending is the teardown, not the supervisor's. + bound_ms: 5_000, + }); + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) + .await + .expect("the evaluation returns though a server never settles") + .expect("the evaluation records both scenarios"); + let records = fixture.records(&out); + assert_eq!(records.len(), 4, "two scenarios, both arms: {report}"); + for record in records + .iter() + .filter(|record| record["scenario"] == "case" && record["arm"] == "current") + { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], true, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + let error = record["error"].as_str().unwrap_or_default(); + assert!( + error.contains("did not finish shutting down within"), + "the run names the teardown failure: {record}" + ); + assert!( + record["durationMs"].as_f64().unwrap_or_default() < 20_000.0, + "the run ends within its settle grace, not at a longer one: {record}" + ); + assert!( + out.join("outputs") + .join("current") + .join("case") + .join("run-0.timeline.jsonl") + .exists(), + "the printed outcome keeps its export: {record}" + ); + } + let marker = out + .join("children") + .join("current") + .join("case") + .join("run-0.stall"); + assert_eq!( + std::fs::read_to_string(&marker).unwrap_or_default(), + "before its server's shutdown settles", + "the child reached its served server's shutdown" + ); + for record in records + .iter() + .filter(|record| !(record["scenario"] == "case" && record["arm"] == "current")) + { + assert_eq!(record["stop"], "idle", "{record}"); + assert_eq!(record["failed"], false, "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + assert_eq!( + fixture.judge().len(), + 4, + "both case runs reached the judge; the next scenario's runs were answered" + ); + } + /// The fixture's basic scenario at a window the judge's view fits: one /// message, a plain answer, and the workspace file's read. fn judged_scenario() -> Value { From 7450169e12fe3dac2f3ec391bfe56dcd0d0c1021 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 02:09:54 +0800 Subject: [PATCH 31/32] docs(xtask): state what an unfinished judge phase keeps The comment on the non-wall-clock judge phase said the run keeps every call recorded so far, but an unfinished phase records a failed call with no calls. The comment now states what the record holds: the run's stop and its export. --- xtask/src/scenario_eval.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 47a46bcf9d..5e567d8fee 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -5438,8 +5438,8 @@ async fn drive_once( // A run that did not stop on its wall clock gives its judge phase // its own budget: the judge may legitimately make several calls, and // one that never answers must not hold the child — and the worker - // that runs it — open. The run keeps the stop it reached, its export - // and every call recorded so far (model-prompts §8.1). + // that runs it — open. The run keeps the stop it reached and its + // export (model-prompts §8.1). let budget = judge_phase_budget(settings.judge_budget_ms); match tokio::time::timeout( budget, From e321f4a6dba2d18aa8820ee899ee328d3f6fc2c1 Mon Sep 17 00:00:00 2001 From: huihui Date: Mon, 23 Nov 2026 03:14:35 +0800 Subject: [PATCH 32/32] docs(xtask): say where the switch retry waits `SwitchFire::Retry` does not sleep at its match arm: the pass returns to the loop, which waits for the next notice (`wait_time`) before the move is tried again. The comment points a reader at that pacing so the retry is not changed into a sleep at the call site. --- xtask/src/scenario_eval.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 5e567d8fee..e8e1bb35c0 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -5871,6 +5871,8 @@ async fn drive( } }; match fired { + // The next attempt waits for the loop's next notice (`wait_time`), + // so the retry is paced there rather than by a sleep here. Ok(SwitchFire::Retry) => driven.switch_retries += 1, Ok(SwitchFire::Fired) => awaiting = true, Ok(SwitchFire::NotFired) => {}