diff --git a/docs/design/model-prompts.md b/docs/design/model-prompts.md index 1afe8f4a1d..6f56cd31d4 100644 --- a/docs/design/model-prompts.md +++ b/docs/design/model-prompts.md @@ -220,7 +220,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 @@ -253,6 +253,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` 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/design/timeline-branches.md b/docs/design/timeline-branches.md index 42685b4453..f636b2df77 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 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. +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 | @@ -530,6 +532,7 @@ The set lives in the repository, one directory per scenario, holding a `scenario | 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/model-prompts.md b/docs/zh/design/model-prompts.md index abd09eb54b..d1edbb431d 100644 --- a/docs/zh/design/model-prompts.md +++ b/docs/zh/design/model-prompts.md @@ -219,7 +219,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 @@ -252,6 +252,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/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/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 5a6727ed19..07d0c2711f 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/) 下,声明 29,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:这两对保持完全相同,改动其中一份而不同步另一份时,读取两个提交目录的无模型测试会失败。 | 场景 | 场景目录 | 关注什么 | @@ -487,7 +489,6 @@ WorkspaceTools 不变。 | 线把自己当成默认分支 | — | 不是默认分支的线把 Session 的对话当成自己的、无视自己可以开线,或者已经是默认分支的线不再向开它的那条线汇报 | | 线在不能开线的地方开线 | — | 既不是根也不是当前默认分支的线自己开线,而不是告诉其中一条 | | 上限与那条路径 | — | Session 已经超过上限时线仍拒绝开线,或者为腾位置关闭一条线 | -| 线把自己当成默认分支 | — | 不是默认分支的线把 Session 的对话当成自己的,或者已经是默认分支的线不再向开它的那条线汇报 | | 重复劳动 | `timeline-branches/redone-work` | `main` 重做一条线正在做的事,或者两条线做同一件事 | | 过时的认识 | — | 一条线依据切点之后已经改变的文件或决定行事,却没有重新读取 | | 父线动了 | `timeline-branches/main-moved-on` | 一条线在回答或结束前没有读取父线在切点之后提交的活动,或者逐页读遍了父线的全部活动 | @@ -496,6 +497,9 @@ WorkspaceTools 不变。 | 不结束 | `timeline-branches/never-ending` | 一条线已经做完,却不调用 `end` | | 兄弟中转 | `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/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/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/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..496ac79b48 --- /dev/null +++ b/xtask/scenario-eval/timeline-branches/switch-then-open-lines/scenario.json @@ -0,0 +1,15 @@ +{ + "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-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/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() diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index 9f86787b54..94131524b2 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -89,6 +89,22 @@ 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, + /// 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: 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 { @@ -102,6 +118,10 @@ impl Default for RunSettings { js_runtime: None, boundary: None, plugin_tools: true, + stall_cleanup: false, + cleanup_budget_ms: None, + stall_export: None, + judge_budget_ms: None, } } } diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 9e51755819..e8e1bb35c0 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. //! @@ -321,8 +321,75 @@ 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 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); +/// 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 +/// 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 +/// 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. +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 +/// grace. +fn settle_bound(stall_cleanup: bool) -> Duration { + if stall_cleanup { + STALLED_CLEANUP_GRACE + } else { + SETTLE_BOUND + } +} + +/// 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) + } +} + +/// 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\": \"\"}."; @@ -979,6 +1046,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, @@ -1076,6 +1144,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, @@ -1118,6 +1187,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)] @@ -1215,6 +1289,9 @@ 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"), + "switch_target_unknown" => Ok("switch_target_unknown"), "error" => Ok("error"), other => Err(format!("the saved run has an unknown stop {other}").into()), } @@ -1249,6 +1326,58 @@ 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), 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. +#[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. @@ -1284,6 +1413,31 @@ 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. + stall_cleanup: bool, + /// 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 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, @@ -1449,6 +1603,13 @@ impl Options { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, + stall_cleanup: false, + cleanup_budget_ms: None, + stall_export: None, + stall: None, + broken: None, + judge_budget_ms: None, rejudge, select, pool, @@ -1670,9 +1831,106 @@ 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: 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)] +#[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, +} + +/// 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 and that target has not started. +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 { + let line = match &switch.to { + SwitchTarget::Id(id) => Some(id.clone()), + SwitchTarget::Role(_) => None, + }; + 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/start` is when the move and the next input + /// 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, + SwitchTarget::Role(SwitchRole::LatestToolLine) + ) && event["data"]["source"]["kind"] == "tool" + && let Some(line) = event["data"]["branch"].as_str() + { + self.line = Some(line.to_owned()); + } + return; + } + if event["type"] == "turn" + && event["name"] == "start" + && self.line.as_deref() == Some(branch) + { + self.triggered = true; + } + } +} /// 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 @@ -1802,6 +2060,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, } @@ -1866,6 +2127,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()); @@ -1983,6 +2261,7 @@ fn into_scenario( sources: raw.sources, events: raw.events, steers: raw.steers, + switch: raw.switch, budget: raw.budget, probes: raw.probes, }) @@ -1996,7 +2275,8 @@ struct RunRecord { scenario: String, run: usize, session: Option, - /// `idle`, `turns`, `seconds` or `error`. + /// `idle`, `turns`, `seconds`, `switch_target_not_reached`, + /// `switch_target_ended`, `switch_target_unknown` or `error`. stop: &'static str, turns: u32, window: Option, @@ -2021,6 +2301,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. @@ -2074,8 +2358,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. @@ -2136,6 +2421,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 @@ -2207,6 +2500,37 @@ 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. + #[serde(default)] + stall_cleanup: bool, + /// 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: 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)] + 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. @@ -2244,10 +2568,13 @@ 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, decline_retries: u32, + switch_retries: u32, error: Option, judge_outcome: JudgeOutcome, judge_error: Option, @@ -2264,6 +2591,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), } @@ -2276,10 +2605,12 @@ 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., decline_retries: 0, + switch_retries: 0, error: None, judge_outcome: JudgeOutcome::NotAsked, judge_error: None, @@ -2313,6 +2644,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 @@ -2374,10 +2710,62 @@ 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(HELD_PAST_GUARD.as_secs().to_string()) + .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}") + })?; + } + 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(()) } @@ -2412,6 +2800,10 @@ 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, + cleanup_budget_ms: params.cleanup_budget_ms, + stall_export: params.stall_export.clone(), + 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). @@ -2441,16 +2833,92 @@ 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.; server.shutdown(); - let _ = 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). 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 { + // 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 => { + 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()) }); + 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; } @@ -2475,6 +2943,10 @@ fn native_probe_settings( js_runtime: None, boundary, plugin_tools: false, + stall_cleanup: false, + cleanup_budget_ms: None, + stall_export: None, + judge_budget_ms: None, } } @@ -2523,11 +2995,18 @@ async fn native_probe_child(params: &ChildParams) -> Result, + cleanup_deadline: &mut Option, ) -> std::result::Result> { let cancel = CancellationToken::new(); let socket = settings @@ -2649,6 +3129,7 @@ async fn child_drive( producer, (!params.offer_plugin) .then(|| ceiling.clone().unwrap_or_else(|| session_tools(scenario))), + params.stall.as_ref(), ) .await { @@ -2660,6 +3141,7 @@ async fn child_drive( } }; let driven = finished.driven; + *cleanup_deadline = driven.cleanup_deadline; let judging = finished.judging; Ok(ChildOutcome { preflight: checks, @@ -2668,10 +3150,12 @@ 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., decline_retries: driven.decline_retries, + switch_retries: driven.switch_retries, error: driven.error, judge_outcome: judging.outcome, judge_error: judging.error, @@ -2830,7 +3314,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 { @@ -2993,7 +3477,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 @@ -3534,6 +4018,17 @@ fn run_socket(options: &Options, arm: &str, scenario: &Scenario, run: usize) -> .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`]). @@ -3589,6 +4084,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(), @@ -3620,6 +4126,13 @@ 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, + cleanup_budget_ms: options.cleanup_budget_ms, + stall_export: options.stall_export.clone(), + stall, + broken, + judge_budget_ms: options.judge_budget_ms, native_tools: native.to_vec(), probe_only: false, }; @@ -3631,7 +4144,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)) } @@ -3726,12 +4246,33 @@ async fn native_probe( extra_tool: options.extra_tool, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, + stall_cleanup: false, + cleanup_budget_ms: None, + stall_export: None, + 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(options, ¶ms_path, ¶ms, cancel, "nativeTools").await?; + // 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, + cancel, + "nativeTools", + Some(STARTUP_BOUND), + ) + .await? + 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()) } @@ -3986,15 +4527,246 @@ fn child_environment( Ok(env) } -/// Spawns the run's serve child and reads its outcome line. +/// 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.contains("\"runProgress\""))?; + let json = &line[line.find('{')?..]; + let value: Value = serde_json::from_str(json).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 what the child had +/// already printed decides the record (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? + { + 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 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. 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 { + 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_phase_budget(params.judge_budget_ms)) + + settle_bound(params.stall_cleanup) + } + } +} + +/// 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() + .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(); + 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, + timed_out, + turns: 0, + window: None, + duration_ms: elapsed.as_secs_f64() * 1000., + decline_retries: 0, + switch_retries: 0, + error: Some(error), + judge_outcome: JudgeOutcome::NotAsked, + judge_error: Some(judge_error), + 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 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 @@ -4005,13 +4777,18 @@ 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 +/// 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, 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); @@ -4046,31 +4823,44 @@ 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. 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 // 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 @@ -4082,13 +4872,111 @@ async fn spawn_child_json( let _ = child.wait().await; return Err("the evaluation was cancelled".into()); } + _ = async { + 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; 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(mut reading) = reading + && tokio::time::timeout(KILLED_READ_GRACE, &mut reading) + .await + .is_err() + { + reading.abort(); + let _ = reading.await; + } + 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(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 — 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 = 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)] + group.kill(); + reading.abort(); + let _ = reading.await; + return Err("the evaluation was cancelled".into()); + } + read = tokio::time::timeout_at(until, &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. Whether the child's + // own line arrived is decided by that output. + read_end = ReadEnd::Deadline; + #[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 @@ -4109,49 +4997,56 @@ 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(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)`), -/// 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 @@ -4182,6 +5077,9 @@ fn child_record( "idle" => "idle", "turns" => "turns", "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 { @@ -4206,6 +5104,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 @@ -4244,7 +5143,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, @@ -4267,9 +5166,12 @@ impl Finished { driven: Driven { session: String::new(), stop: "error", + timed_out: false, + cleanup_deadline: None, turns: 0, window: None, decline_retries: 0, + switch_retries: 0, error: Some(error), }, export: None, @@ -4310,11 +5212,23 @@ impl Judging { temperature_dropped: false, } } -} - -#[expect( - clippy::too_many_arguments, - reason = "one parameter per part of a driven run's state" + /// 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( + clippy::too_many_arguments, + reason = "one parameter per part of a driven run's state" )] async fn drive_once( server: &RunningServer, @@ -4328,6 +5242,7 @@ async fn drive_once( cancel: &CancellationToken, producer: &ProducerState, tools: Option>, + stall: Option<&ChildStall>, ) -> Result { let socket = settings .unix_path @@ -4349,7 +5264,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, @@ -4358,28 +5282,110 @@ async fn drive_once( judging: Judging::not_asked(scenario, None), }); } - let _ = client - .rpc("session.close", json!({"sessionId": driven.session})) - .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 + // 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. 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 + // 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. + let stalled = async move { + let _ = close.await; + std::future::pending::<()>().await; + }; + let _ = tokio::time::timeout_at(deadline, stalled).await; + false + } else { + matches!(tokio::time::timeout_at(deadline, 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; + } + drop(client); + 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); driven.turns = turns; - if let Some(error) = failed_turn - && driven.error.is_none() - { - driven.stop = "error"; - driven.error = Some(error); - } + settle_failed_turn(&mut driven, failed_turn); export } Err(error) => { @@ -4407,7 +5413,50 @@ 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 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 + { + 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 { + // 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 and its + // export (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, export: Some(export), @@ -4417,12 +5466,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" | "switch_target_unknown" + ) || error.is_some() || matches!( judge_outcome, JudgeOutcome::CallFailed | JudgeOutcome::NotAsked @@ -4477,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, @@ -4534,10 +5599,21 @@ 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, + /// 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`. decline_retries: u32, + /// How many times the runner moved again after the target line answered + /// `unknown_branch`. + switch_retries: u32, error: Option, } @@ -4558,6 +5634,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, @@ -4570,9 +5647,12 @@ async fn drive( return Driven { session: String::new(), stop: "error", + timed_out: false, + cleanup_deadline: None, turns: 0, window: None, decline_retries: 0, + switch_retries: 0, error: Some(error), }; } @@ -4592,9 +5672,12 @@ async fn drive( return Driven { session: String::new(), stop: "error", + timed_out: false, + cleanup_deadline: None, turns: 0, window: None, decline_retries: 0, + switch_retries: 0, error: Some(format!("session.create failed: {error}")), }; } @@ -4602,9 +5685,12 @@ async fn drive( let mut driven = Driven { session: session.clone(), stop: "idle", + timed_out: false, + cleanup_deadline: None, turns: 0, window: None, decline_retries: 0, + switch_retries: 0, error: None, }; if let Err(error) = client @@ -4681,7 +5767,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; @@ -4694,6 +5780,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 @@ -4752,6 +5839,63 @@ async fn drive( driven.error = Some(error); return driven; } + // 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.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", + 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 { + // 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) => {} + 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 @@ -4759,13 +5903,19 @@ 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()) }); 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 { @@ -4820,6 +5970,9 @@ async fn drive( 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, Err(error) => { @@ -4886,33 +6039,88 @@ 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 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; } } 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 let Some(deadline) = driven.cleanup_deadline { + tokio::time::timeout_at(deadline, usage).await.ok() + } else { + Some(usage.await) + }; + 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); } - Err(error) if dim_client::app_error(&error) == Some("context_usage_unavailable") => {} - 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"; + } } - if driven.error.is_some() { - driven.stop = "error"; + } + if let Some(pending) = &switch { + 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!( + "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 @@ -5738,11 +6946,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); } @@ -5750,18 +6969,120 @@ fn submit_params(session: &str, text: &str, mode: Option) -> Value { } async fn submit( - client: &mut Client, + client: &mut impl SwitchClient, 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}")) } +/// 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 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 }, +} + +/// 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, +) -> std::result::Result { + let Some(pending) = switch.as_mut() else { + return Ok(SwitchFire::NotFired); + }; + if !pending.triggered { + return Ok(SwitchFire::NotFired); + } + let line = pending + .line + .clone() + .expect("a triggered switch names its line"); + if let Err(error) = client + .rpc( + "session.branch_set_default", + json!({"sessionId": session, "branchId": line}), + ) + .await + { + 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); + } + 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, + &pending.switch.message, + None, + pending.switch.branch_id.as_deref(), + ) + .await?; + Ok(SwitchFire::Fired) +} + /// Sends the timed steers that are due, and whether it sent one. async fn fire_due( client: &mut Client, @@ -5776,7 +7097,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; } } @@ -5803,13 +7124,19 @@ 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; } } 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( @@ -6825,6 +8152,7 @@ mod tests { sources: Vec::new(), events: Vec::new(), steers: Vec::new(), + switch: None, budget: Budget { turns: 4, seconds: 60., @@ -6856,6 +8184,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 @@ -7011,103 +8340,566 @@ 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")); } - /// 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. + /// 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 at the target + /// line's first `turn/start` (model-prompts §9.8). #[test] - fn the_committed_scenario_set_parses_and_its_shared_premises_stay_equal() { - let root = repository().join("xtask").join("scenario-eval"); - let branches = read_scenarios(&root.join("timeline-branches")).unwrap(); - let compact = read_scenarios(&root.join("timeline-branches-compact")).unwrap(); - fn find<'a>(scenarios: &'a [Scenario], id: &str) -> &'a Scenario { - scenarios - .iter() - .find(|scenario| scenario.id == id) - .unwrap_or_else(|| panic!("{id} is in the committed set")) - } - let redone = find(&branches, "redone-work"); - let identity = find(&compact, "identity-after-compaction"); - assert_eq!( - identity.message, redone.message, - "identity-after-compaction runs redone-work's task" - ); - assert_eq!( - workspace_files(&identity.directory), - workspace_files(&redone.directory), - "identity-after-compaction starts from redone-work's workspace" + 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" ); - let flooding = find(&branches, "flooding"); - let never_ending = find(&branches, "never-ending"); - assert_eq!( - workspace_files(&flooding.directory), - workspace_files(&never_ending.directory), - "flooding and never-ending start from one workspace" + assert!( + parse(json!({"to": {"id": ""}, "message": "second"})).is_err(), + "a switch target id is not empty" ); + let _ = std::fs::remove_dir_all(&directory); } - /// The scheduler set parses through the runner's own reader (Scheduler - /// §5.1): three scenarios, each with a statement to see and a statement - /// not to see, and no EventHub source, since the subject is the `schedule` - /// tool. No model runs, so CI catches a schema or layout drift before a - /// manual run. + /// 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 the_scheduler_scenario_set_parses() { - let root = repository() - .join("xtask") - .join("scenario-eval") - .join("scheduler"); - let scenarios = read_scenarios(&root).unwrap(); - let ids: Vec<_> = scenarios + 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", + "data": {"branch": branch, "source": {"kind": kind}}}) + }; + let mut pending = PendingSwitch::new(Switch { + to: SwitchTarget::Role(SwitchRole::LatestToolLine), + message: "next".into(), + branch_id: None, + }); + 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")); + pending.notice("3", &turn_start); + assert!(!pending.triggered, "another line's turn starts no switch"); + pending.notice("main", &create("3", "user")); + pending.notice("3", &turn_start); + assert!( + !pending.triggered, + "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, + }); + pending.notice("4", &turn_start); + 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(|scenario| scenario.id.as_str()) + .map(|(method, _)| method.as_str()) .collect(); assert_eq!( - ids, + calls, [ - "a-target-the-tool-cannot-set", - "recurring-job-from-a-request", - "rename-an-existing-job", + "session.branch_set_default", + "session.branch_set_default", + "session.submit" ], - "the committed set is the three scenarios" + "the retry moves before it sends the next input" ); - for scenario in &scenarios { - assert!( - scenario.sources.is_empty() && scenario.events.is_empty(), - "{}: the schedule tool is the subject, not an EventHub source", - scenario.id - ); - assert!( - scenario - .probes - .iter() - .any(|probe| probe.kind == ProbeKind::MustShow), - "{}: a statement to see", - scenario.id - ); - assert!( - scenario - .probes - .iter() - .any(|probe| probe.kind == ProbeKind::MustNotShow), + 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. + #[derive(Default)] + struct SwitchRecorder { + calls: Vec<(String, Value)>, + 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)); + 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 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 = triggered_switch(); + 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.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).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 { + refusals: vec![dim_client::RpcError { + code: -32000, + message: "the tree is closing".into(), + data: Some(json!({"appError": "session_closed"})), + }], + ..SwitchRecorder::default() + }; + 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:?}"), + }; + 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 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 + /// §9.8). + #[tokio::test] + async fn a_target_that_ended_before_the_move_is_its_own_outcome() { + for (code, message) in [ + ("branch_ended", "branch 2 has ended"), + ("branch_target_protected", "line 2 is ending or ended"), + ] { + let mut client = SwitchRecorder { + refusals: vec![dim_client::RpcError { + code: -32000, + message: message.into(), + data: Some(json!({"appError": code})), + }], + ..SwitchRecorder::default() + }; + 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}"); + } + 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" + ); + } + } + + /// 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"); + let branches = read_scenarios(&root.join("timeline-branches")).unwrap(); + let compact = read_scenarios(&root.join("timeline-branches-compact")).unwrap(); + fn find<'a>(scenarios: &'a [Scenario], id: &str) -> &'a Scenario { + scenarios + .iter() + .find(|scenario| scenario.id == id) + .unwrap_or_else(|| panic!("{id} is in the committed set")) + } + 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, + 29_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, "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 + .as_ref() + .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!( + identity.message, redone.message, + "identity-after-compaction runs redone-work's task" + ); + assert_eq!( + workspace_files(&identity.directory), + workspace_files(&redone.directory), + "identity-after-compaction starts from redone-work's workspace" + ); + let flooding = find(&branches, "flooding"); + let never_ending = find(&branches, "never-ending"); + assert_eq!( + workspace_files(&flooding.directory), + workspace_files(&never_ending.directory), + "flooding and never-ending start from one workspace" + ); + } + + /// The scheduler set parses through the runner's own reader (Scheduler + /// §5.1): three scenarios, each with a statement to see and a statement + /// not to see, and no EventHub source, since the subject is the `schedule` + /// tool. No model runs, so CI catches a schema or layout drift before a + /// manual run. + #[test] + fn the_scheduler_scenario_set_parses() { + let root = repository() + .join("xtask") + .join("scenario-eval") + .join("scheduler"); + let scenarios = read_scenarios(&root).unwrap(); + let ids: Vec<_> = scenarios + .iter() + .map(|scenario| scenario.id.as_str()) + .collect(); + assert_eq!( + ids, + [ + "a-target-the-tool-cannot-set", + "recurring-job-from-a-request", + "rename-an-existing-job", + ], + "the committed set is the three scenarios" + ); + for scenario in &scenarios { + assert!( + scenario.sources.is_empty() && scenario.events.is_empty(), + "{}: the schedule tool is the subject, not an EventHub source", + scenario.id + ); + assert!( + scenario + .probes + .iter() + .any(|probe| probe.kind == ProbeKind::MustShow), + "{}: a statement to see", + scenario.id + ); + assert!( + scenario + .probes + .iter() + .any(|probe| probe.kind == ProbeKind::MustNotShow), "{}: a statement not to see", scenario.id ); @@ -8257,6 +10049,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 @@ -9833,6 +11667,13 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, + stall_cleanup: false, + cleanup_budget_ms: None, + stall_export: None, + stall: None, + broken: None, + judge_budget_ms: None, defaults: None, node: None, js_runtime: None, @@ -10732,17 +12573,44 @@ 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, + /// 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, + /// 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, + /// 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, + /// 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, /// 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, + usages: AtomicUsize, + attached: tokio::sync::Notify, + closes: AtomicUsize, } /// How long [`PeerScript::HeldIdle`] keeps the line busy: five quiet @@ -10777,13 +12645,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", @@ -10847,6 +12719,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 @@ -10878,6 +12753,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); @@ -10985,6 +12869,12 @@ mod tests { write.write_all(&frame(&request, body)).await.unwrap(); (declines == 3).then_some(("r1", 1)) } + PeerScript::SwitchNeverFires => None, + PeerScript::SwitchMoveRetries => None, + PeerScript::SwitchMoveStalls + | PeerScript::SwitchSubmitStalls + | PeerScript::SwitchMoveAndCloseStall => None, + PeerScript::DeferredUsageFails => None, }; if let Some((request, sequence)) = closed { if recorded.settled_at.load(Ordering::SeqCst) == 0 { @@ -10998,10 +12888,49 @@ 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 | PeerScript::SwitchMoveAndCloseStall + ) + { + continue; + } + if method == "session.submit" { + submits += 1; + if submits > 1 && matches!(script, PeerScript::SwitchSubmitStalls) { + continue; + } + } 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.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) => + { + json!({"error": {"code": -32000, "message": "unknown branch: 2", + "data": {"appError": "session_invalid_input"}}}) + } _ => json!({"result": {}}), }; write.write_all(&frame(&request, body)).await.unwrap(); @@ -11013,8 +12942,43 @@ 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 + | PeerScript::DeferredUsageFails + ) { + if matches!( + script, + PeerScript::SwitchNeverFires | PeerScript::DeferredUsageFails + ) { + write + .write_all(¬ice(json!({"type": "turn", "name": "end", + "sequence": 2, "data": {}}))) + .await + .unwrap(); + } + continue; + } + if matches!( + script, + PeerScript::SwitchMoveRetries + | PeerScript::SwitchMoveStalls + | PeerScript::SwitchSubmitStalls + | PeerScript::SwitchMoveAndCloseStall + ) { + 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 { @@ -11090,6 +13054,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -11108,22 +13073,30 @@ mod tests { ); } - /// 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 - /// passed. The peer reads exactly two declines, and the run ends idle - /// because the retry took the second one. + /// 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_busy_line_sends_the_decline_again_once() { - let directory = - std::env::temp_dir().join(format!("dim-scenario-eval-busy-{}", std::process::id())); - let (socket, reads) = scripted_peer(&directory, 8_000, PeerScript::Late).await; + 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, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -11132,16 +13105,346 @@ mod tests { ) .await; let _ = std::fs::remove_dir_all(directory); - // The budget writes `seconds`, so `idle` is the retry ending the run. - assert_eq!(driven.stop, "idle", "{:?}", driven.error); assert_eq!( - driven.decline_retries, 1, - "the retry the quiet period scheduled" + driven.stop, "switch_target_not_reached", + "{:?}", + driven.error ); - assert_eq!( - reads.declines.lock().unwrap().len(), - 2, - "one declined early and one the quiet period scheduled" + 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 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, + &RunSettings::default(), + &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 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, + &RunSettings::default(), + &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 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, + stall_cleanup: false, + cleanup_budget_ms: None, + stall_export: None, + judge_budget_ms: None, + }; + 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, + 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 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, + &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"); + 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 + /// passed. The peer reads exactly two declines, and the run ends idle + /// because the retry took the second one. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_busy_line_sends_the_decline_again_once() { + let directory = + std::env::temp_dir().join(format!("dim-scenario-eval-busy-{}", std::process::id())); + let (socket, reads) = scripted_peer(&directory, 8_000, PeerScript::Late).await; + let mut client = driver_client(socket).await; + let mut scenario = scenario(Vec::new()); + scenario.budget.seconds = 10.; + let driven = drive( + &mut client, + &RunSettings::default(), + &scenario, + &std::env::temp_dir(), + &peer_model(), + &ProducerState::default(), + None, + ) + .await; + let _ = std::fs::remove_dir_all(directory); + // The budget writes `seconds`, so `idle` is the retry ending the run. + assert_eq!(driven.stop, "idle", "{:?}", driven.error); + assert_eq!( + driven.decline_retries, 1, + "the retry the quiet period scheduled" + ); + assert_eq!( + reads.declines.lock().unwrap().len(), + 2, + "one declined early and one the quiet period scheduled" ); } @@ -11160,6 +13463,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -11200,6 +13504,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -11240,6 +13545,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -11279,6 +13585,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -11313,6 +13620,7 @@ mod tests { scenario.budget.seconds = 10.; let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -11351,6 +13659,7 @@ mod tests { let started = Instant::now(); let driven = drive( &mut client, + &RunSettings::default(), &scenario, &std::env::temp_dir(), &peer_model(), @@ -12543,6 +14852,13 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, + stall_cleanup: false, + cleanup_budget_ms: None, + stall_export: None, + stall: None, + broken: None, + judge_budget_ms: None, defaults: None, node: None, js_runtime: None, @@ -12841,6 +15157,13 @@ mod tests { extra_tool: false, fail_child: None, fail_child_holds_stdout: false, + leave_member: None, + stall_cleanup: false, + cleanup_budget_ms: None, + stall_export: None, + stall: None, + broken: None, + judge_budget_ms: None, native_tools: native .iter() .map(|name| ((*name).to_owned(), ToolSource::Builtin)) @@ -12970,8 +15293,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", @@ -13010,7 +15332,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(); @@ -13036,80 +15360,969 @@ mod tests { ); } - /// 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 - /// child records its descendant's pid beside the marker before it - /// exits; the descendant is a `sleep` that joins the child's group (it - /// starts no session of its own). + /// 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_failed_child_kills_the_group_it_leaves() { - let fixture = Fixture::start( - "failed-descendant", + 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_some(HELD_PAST_GUARD) + } + let fixture = Fixture::holding( + "stalled-cleanup", reads_the_workspace_file, - isolated_scenario(), + 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; - let directory = fixture.directory.join("out"); - let mut options = fixture.options(directory); - // The marker is already there: the failing child needs no held - // sibling, only its own non-zero exit path. - let marker = fixture.directory.join("fail.marker"); - std::fs::write(&marker, "go").unwrap(); - options.fail_child = Some(("current".into(), marker.clone())); - let settled = fixture.evaluate(&options).await; - let error = settled - .expect_err("the failing run fails the evaluation") - .to_string(); - assert!( - error.contains("the held sibling's model call was seen"), - "the failing child saw its marker: {error}" - ); - let pid: u32 = std::fs::read_to_string(marker.with_extension("descendant")) - .expect("the failing child recorded its descendant") - .trim() - .parse() - .expect("the descendant's pid"); - assert!( - child_tree_gone(pid).await, - "the failed child's descendant and its group are gone (pid {pid})" + // 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(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"); + 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}"); + 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"), + "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 failed child's descendant that inherits the child's standard - /// output must not keep `evaluate` from the run's error: the group is - /// killed as soon as the non-zero status is known, before the parent - /// reads the child's output, so the read reaches EOF. The bound makes - /// an ordering regression a failed assertion instead of a hang. + /// 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_failed_child_holding_stdout_returns_its_error() { - let fixture = Fixture::start( - "failed-stdout-holder", + async fn a_timed_out_run_that_closes_is_judged() { + let fixture = Fixture::with_window( + "timed-out-judged", reads_the_workspace_file, - isolated_scenario(), + 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 directory = fixture.directory.join("out"); - let mut options = fixture.options(directory); - // The marker is already there: the failing child needs no held - // sibling, and its descendant inherits its standard output. - let marker = fixture.directory.join("fail.marker"); - std::fs::write(&marker, "go").unwrap(); - options.fail_child = Some(("current".into(), marker.clone())); - options.fail_child_holds_stdout = true; - let settled = tokio::time::timeout(Duration::from_secs(10), fixture.evaluate(&options)) + let out = fixture.directory.join("out"); + let options = fixture.options(out.clone()); + let report = tokio::time::timeout(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) .await - .expect("the evaluation returns within the bound"); - let error = settled - .expect_err("the failing run fails the evaluation") - .to_string(); - assert!( - error.contains("the held sibling's model call was seen"), - "the failing child saw its marker: {error}" + .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}"); + 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!( + 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 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 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() { + fn hold_the_first_judge(text: &str) -> Option { + (text.contains("You check statements") && text.contains("Run the quick probe.")) + .then_some(HELD_PAST_GUARD) + } + 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.cleanup_budget_ms = Some(1_000); + 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"); + 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}"); + 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"), + "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 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": 0.5, "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(1_000); + 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"); + 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}"); + 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"), + "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.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") + .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"); + 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() + .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 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 { + 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()); + // 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 + .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 + /// child records its descendant's pid beside the marker before it + /// exits; the descendant is a `sleep` that joins the child's group (it + /// starts no session of its own). + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_failed_child_kills_the_group_it_leaves() { + let fixture = Fixture::start( + "failed-descendant", + reads_the_workspace_file, + isolated_scenario(), + &[("notes.txt", FILE_TEXT)], + ) + .await; + let directory = fixture.directory.join("out"); + let mut options = fixture.options(directory); + // The marker is already there: the failing child needs no held + // sibling, only its own non-zero exit path. + let marker = fixture.directory.join("fail.marker"); + std::fs::write(&marker, "go").unwrap(); + options.fail_child = Some(("current".into(), marker.clone())); + let settled = fixture.evaluate(&options).await; + let error = settled + .expect_err("the failing run fails the evaluation") + .to_string(); + assert!( + error.contains("the held sibling's model call was seen"), + "the failing child saw its marker: {error}" + ); + let pid: u32 = std::fs::read_to_string(marker.with_extension("descendant")) + .expect("the failing child recorded its descendant") + .trim() + .parse() + .expect("the descendant's pid"); + assert!( + child_tree_gone(pid).await, + "the failed child's descendant and its group are gone (pid {pid})" + ); + } + + /// A failed child's descendant that inherits the child's standard + /// output must not keep `evaluate` from the run's error: the group is + /// killed as soon as the non-zero status is known, before the parent + /// reads the child's output, so the read reaches EOF. The bound makes + /// an ordering regression a failed assertion instead of a hang. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_failed_child_holding_stdout_returns_its_error() { + let fixture = Fixture::start( + "failed-stdout-holder", + reads_the_workspace_file, + isolated_scenario(), + &[("notes.txt", FILE_TEXT)], + ) + .await; + let directory = fixture.directory.join("out"); + let mut options = fixture.options(directory); + // The marker is already there: the failing child needs no held + // sibling, and its descendant inherits its standard output. + let marker = fixture.directory.join("fail.marker"); + std::fs::write(&marker, "go").unwrap(); + options.fail_child = Some(("current".into(), marker.clone())); + options.fail_child_holds_stdout = true; + let settled = tokio::time::timeout(Duration::from_secs(10), fixture.evaluate(&options)) + .await + .expect("the evaluation returns within the bound"); + let error = settled + .expect_err("the failing run fails the evaluation") + .to_string(); + assert!( + error.contains("the held sibling's model call was seen"), + "the failing child saw its marker: {error}" ); let pid: u32 = std::fs::read_to_string(marker.with_extension("descendant")) .expect("the failing child recorded its descendant") @@ -13122,6 +16335,94 @@ 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 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() { + let fixture = Fixture::start( + "stdout-holder", + 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()); + options.jobs = 1; + options.stall_cleanup = true; + let marker = fixture.directory.join("leave.marker"); + options.leave_member = Some((true, marker.clone())); + // 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(SUBPROCESS_EVAL_GUARD, fixture.evaluate(&options)) + .await + .expect("the evaluation returns though a child left its stdout open") + .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"], "idle", "{record}"); + assert_eq!(record["judgeOutcome"], "judged", "{record}"); + } + 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 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(SUBPROCESS_EVAL_GUARD, 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.