Repository navigation
feat(shell): adaptive timeouts and a wait-for-condition primitive - #3402
Conversation
|
Verdict: Request changes This gives shell commands a timeout that matches what they are (test runs get 15 minutes, builds 30, network calls 5, everything else 30 seconds), makes a timed-out command actually die instead of hanging on a surviving grandchild, and adds a What needs fixing before merge:
Real-world evidenceThe automated evidence harness failed to run on this PR ( 🔍 Technical details🔴 Critical
🟡 ImportantCancel is not observed during a long The
The non-
Same gap in the docs: 🟢 Minor
Strengths
|
…it primitive A shell command was killed at 30 seconds no matter what it was, so a test suite, a build or an install never finished — and while `timeout` was already a parameter the model could raise, nothing told it how long the command it was about to run should take, so it almost never did. The timeout now comes from the command itself: test runners get 900s, builds and installs 1800s, VCS and network calls 300s, everything else the unchanged 30s. The applied value and its class come back in the result, and an explicit `timeout=` still wins. Out-of-range values are refused rather than clamped, so a command is never killed at a limit its caller did not choose. `wait_for_condition` replaces sleep-and-recheck: it polls a predicate against a monotonic deadline inside one call, so waiting for a server to answer or a build to land costs one agent step instead of one per check. It is bounded (600s ceiling, 5-60s poll interval), gated behind the same confirmation and guardrails as the command it polls with, charged once against the shell rate limit, and interrupted by the agent's cancel signal.
The tool registry takes a tool's description from its docstring — @tool's `description=` and `parameters=` kwargs are swallowed and ignored — and the non-native prompt path renders only the first line of it. The class defaults were in the ignored kwarg, so the model would never have seen them. They now lead the docstring, with a test that fails if a class default drifts out of that line. Also documents both tools in the mixin spec and the flagship's tool surface.
…eturns A 5-second timeout took over two minutes and never returned: `subprocess.run` kills only the process it launched, then re-enters `communicate()` with no timeout, so a surviving grandchild holding the pipes blocks the call for as long as it lives. With 30-minute build timeouts now reachable, that hang would have held the agent loop for an hour instead of three minutes. The executor now drives Popen itself and kills the whole tree on expiry — `taskkill /T` on Windows, the process group on POSIX — then reads the buffered output with a short grace. Verified live: the same command that hung returns in 5.1s with its partial output intact. That partial output is also truncated to 10K now, like the success path always was. A command killed at 30 minutes has printed far more than one killed at 30 seconds; the live run returned 806KB straight into the model's context.
The flagship shows the model a subset of its registry per turn, chosen by bundle. A tool in no bundle is registered but unreachable, so wait_for_condition joins the shell bundle in both the chat and full profiles. Also repoints the granted-CLI argv tests at Popen, which is what the executor drives now — the behaviour they pin (a granted binary never goes through cmd.exe) is unchanged.
CI caught three kinds of drift the new tool created: the `taskkill` nosec had no entry in .security-suppressions.json (which fails both the gate and a unit test), and every hand-maintained tool count — the flagship manifest and the chat agent's four profile literals — was one short. Also formats with the black CI actually runs; the local cache was a version behind and passed files CI rejects.
3d20326 to
3668ec5
Compare
|
🔴 The prior review's tools-count fix is incomplete —
Fix: bump 🔍 Technical details
The drift guard at def test_registration_tools_count_matches_manifest(manifest):
assert build_gaia().tools_count == manifest["tools_count"]…compares This file was not in the prior review's fix either (it stayed at 67 while the yaml moved to 68 in the previous partial fix, then 69 in this push). It has been one step behind throughout. |
build_gaia() carries a second hand-typed copy of the count, one the manifest test does not read. Both now say 69.
Closes the review's 🔴: `gaia-agent.yaml` and `gaia_agent/__init__.py` now agree at 74, which is main's 73 plus this branch's `wait_for_condition`. ChatAgent's "full" profile is 58 — 55, plus transcribe_media/refine_transcript from #3597 and wait_for_condition from here. The shell_tools conflict was not really a conflict. #3252 made `@tool` reject unknown keyword arguments and #3583 taught it to derive the tool's name, description and per-argument schema from the function and its docstring, so main deleted the hand-written `name=`, `description=` and `parameters=` blocks everywhere. This branch still passed them on `run_shell_command` and `wait_for_condition`, which is now a TypeError at import. Both functions already carry full docstrings with `Args:` covering every parameter, so the arguments are dropped rather than migrated — they had been silently ignored, and nothing the model sees changes. `timeout=` stays on both: it is a supported argument and it is what keeps the agent-level guard outliving the longest command class. `_shell_tools()` in the adaptive-timeout spec keyed its captured tools on the `name=` argument, so every lookup returned None once it was gone; it reads `fn.__name__` now, the same place the decorator does.
Import-only conflict: #3703 added the verification import beside this branch's command-timeout imports. Kept both.
Raising the per-tool guard so a 30-minute build is not abandoned mid-run left nothing watching the cancel signal: clicking Stop during a build waited for the build. The executor now waits on the process in short slices, kills the whole tree the moment either cancel channel fires, and refuses outright if Stop landed before the spawn. A wait between probes wakes on the same signals. Also from the review: - `wait_for_condition`'s dead `name=`/`description=`/`parameters=` kwargs are gone; `@tool` rejects them outright since the merge, so they were a hard error. - `normalize_binary` -> `command_basename`, so it no longer shares a name with the security-critical `gaia.skills.binaries.normalize_binary` that returns "" for path spellings on purpose. - One `split_pipeline`, used by both the validator and the classifier, and the classifier now tokenizes `|` as its own token so `ls|pytest` is a pipeline. - Pre-execution refusals declare `executed: False` (#3677), including the wait's — but only when no probe ever reached a process. - Tests: a granted binary reaching the `test` class through the real allowlist (every other classification test stands it down), the same command refused without the grant, and Stop landing before, during, and between commands. Deadline tests now drive a clock, so a 1800s budget is asserted, not waited on.
Main rebuilt the shell execution path around parsed steps, so the branch's adaptive-timeout and cancellation work had to be re-applied on top of it rather than merged textually. - Kept main's `_run_pipeline(segments, modes, envs, cwd, timeout)` and its step loop; the branch's cancel/timeout behaviour now rides on an optional `waiter` callback threaded through `_run_pipeline` and `_run_step`, so a Stop still lands mid-command without the branch reintroducing the older signature. - Replaced `subprocess.run` in `_run_step` with a Popen the waiter can poll, spawned with `start_new_session` on POSIX so `terminate_process_tree` kills the child's group and not the agent's own. - Dropped the branch's `split_pipeline` — main already defines `_split_pipeline` and re-adding it would have shadowed the newer parser. - Chat manifest tool counts follow the merged registry: doc 38 -> 39 (main's `read_tool_output` plus the branch's `wait_for_condition`).
|
Rebuilt this branch's merge with The interesting part wasn't textual. One thing a human should confirm: the doc profile's tool count moved 38 → 39, because 🔍 Technical detailsMerge commit Resolution shape:
Tests: No eval run — Lemonade is down locally. |
…uses The Windows compound-line guard recorded zero invocations after the merge, so its four security assertions were all passing vacuously — the exact shape that would let a real regression through unnoticed. main added this test hard-coding `subprocess.run` as the spawn point. This branch had already replaced that call site with `subprocess.Popen`, because a Stop mid-command needs a process you can poll — `run()` blocks for the whole deadline, so a Stop during a 30-minute build would land 30 minutes late. Git merged the file as a clean add and had nothing to flag. Only the observation point moves. `shell=use_shell` is still on the Popen call and every assertion is byte-for-byte unchanged: two separate spawns, each a string, neither containing `&&`, and exactly `["ls", "cat notes.txt"]`.
|
The three red unit-test lanes were a mocking seam that moved, not a lost guard — pushed a fix, and the guard itself is untouched.
🔍 Technical details
The fix repoints
Full shell suite on the merged branch: 725 passed, 127 skipped, 0 failed. Not a shared cause with #3808 — that one changes refusal into a prompt ( |
|
This merges cleanly into main today. A real merge with The part that matters more: this does not share #3400's structural problem, and the two should not be treated as one decision. #3402 was written on top of main's current multi-step shell engine and extends it. #3400 predates that engine entirely, which is why it needs an author rework decision about who owns connectors and 🔍 Technical detailsHead The branch's Tests against the merged tree, not the branch in isolation: One correction for future readers: the brief circulating for this batch names |
…#4136) ## Why this matters A Windows contributor running the four shell test suites sees `112 skipped`, which is visually indistinguishable from green. CI on ubuntu and macOS sees 112 real results. So the loop is: verify locally, see no red, push, watch CI fail — which is exactly how the confirm-gate defect in amd#3808 reached CI undetected. The skip reason is genuine for the tests that actually launch a process: Windows runs each pipeline through `cmd.exe`, and `os.killpg` / process groups are POSIX-only. It is *not* genuine for the refusal, parsing, grant and tool-description tests — those decide before anything reaches a shell, and a module-level skip was hiding them on the platform most GAIA contributors develop on. After this change Windows runs **70 passed / 42 skipped** instead of `112 skipped`, and every one of those 70 is a real assertion about the security-adjacent refusal path. POSIX is untouched: the per-test mark carries the same `sys.platform == "win32"` condition the module-level one did, so off Windows it is a no-op and all 112 still run. <details> <summary>🔍 Technical details</summary> **Membership was measured, not guessed.** A throwaway pytest plugin stripped the `cmd.exe` skipifs, wrapped `shell_tools.subprocess.Popen` / `.run`, and recorded which node IDs actually spawned a child. 42 did; 70 did not. The 70 were then run on Windows 11 and all passed; every one of the 10 failures fell inside the 42. So the split is empirical, not a reading of the test names. That measurement mattered, because *running the tests* would have given the wrong answer. This dev box has MSYS coreutils on `PATH`, so `ls`, `cat`, `sort` and `date` resolve and most execution tests pass here — they would not on a clean Windows machine or a `windows-latest` runner. Classifying on "does it pass on my box" is the hidden-state trap CLAUDE.md warns about; classifying on "does it spawn a process" is not. - `pytestmark = pytest.mark.skipif(...)` → `posix_only = pytest.mark.skipif(...)`, same reason string per module, applied as `@posix_only` to the 35 spawning tests across three files. - **No assertion was weakened, relaxed, or deleted.** The diff is 53 insertions / 3 deletions; the 3 deletions are the `pytestmark` name on each of the three lines. - Node IDs are unchanged (no reorganisation into classes), so other in-flight PRs that name these tests in their test plans still resolve. - `test_shell_env_assignment.py`'s two existing `shutil.which("pytest")` skipifs stack above `@posix_only`; pytest ORs them, so behaviour off Windows is identical. - `tests/unit/test_shell_pipelines.py` keeps its module-level mark — all seven of its tests genuinely run a pipeline, so there is nothing to promote. `test_shell_output_encoding.py` already used per-test marks and is untouched. - One pleasing side effect: `test_windows_never_hands_a_compound_line_to_cmd_exe_as_one_string` — a fully-mocked test *about* the Windows path — was itself skipped on Windows. It now runs there. **Merge-conflict note for reviewers:** amd#3721 and amd#3402 both touch `test_shell_compound_commands.py`, neither near the `pytestmark` line. Whichever lands second may need a trivial rebase. </details> ## Scope This does **not** close amd#4127. That issue asks for `windows-latest` in the `test_unit.yml` matrix, gated on amd#4115 and amd#4119 landing first so the lane starts green. This is a prerequisite for that lane being worth anything — without it, 112 of the tests the new lane would run are skipped by construction. ## Test plan - [x] `python -m pytest tests/unit/test_shell_compound_commands.py tests/unit/test_shell_env_assignment.py -q` on Windows 11 — was `77 skipped`, now `51 passed, 26 skipped` - [x] Same for all four modules — was `112 skipped`, now `70 passed, 42 skipped` - [x] `python -m pytest tests/unit/test_shell*.py tests/unit/test_powershell_command_injection.py -q` — `266 passed, 42 skipped` - [x] `python util/lint.py --all` — output byte-identical to a clean `origin/main` worktree (both exit 1 on the same pre-existing mypy findings in `src/gaia/`, none in files this PR touches) - [ ] CI on ubuntu/macOS — expect the same counts as before this PR; the mark is a no-op off Windows Towards amd#4127. Co-authored-by: Kalin Ovtcharov <[email protected]>
Conflicts were additive on both sides: main added `capture_skill` and the shell cancellation hook, this branch added `wait_for_condition` and the adaptive-timeout imports. Both kept. The tool count needed a real fix rather than a pick. Both sides read 81 for different reasons (main 59+8, branch 60+7), so git auto-merged the literal while only the comment conflicted. The merged agent registers 82; the generator and the build-the-agent drift test both confirm it. Updated the manifest, the registration literal and the test's expected total, and regenerated CAPABILITY_MATRIX.md (shell bundle 4 -> 5).
Skill audit
✅ All audited skills cleared the tier they claim. Per-finding detail is withheld here on purpose. Read it in the Security > Code scanning tab, or download the |
main's #3390 moved git out of ALLOWED_COMMANDS into the binary-policy table, and #3402 added the adaptive-timeout waiter. Five conflicts, four mechanical: _run_step gained both sides' kwargs (waiter, bypass), _validate_command keeps main's body with the bypass short-circuit ahead of it, run_shell_command resolves the timeout after reading the bypass flag, and the deleted SAFE_GIT_COMMANDS stays deleted. The fifth was behavioural. With git no longer in ALLOWED_COMMANDS and never in DEVELOPER_COMMANDS, bypass refused it outright — so `git status` ran by default but not under bypass, leaving the permissive mode stricter than the default one. git joins the developer set, which restores the pre-merge behaviour and the build/test/land loop this mode exists for. That means git's policy refusals (push, reset, rebase) do not survive bypass. They are a tripwire rather than a boundary here: python and make are in the same set and reach git by shelling out regardless — the same reasoning already recorded for excluding rm. Noted on the six surfaces that enumerate the set, including the TUI's /bypass warning, so the consent text matches what the mode actually grants.
…amd#4370) `main` has been red since 2026-09-25 18:29, so nothing can leave the merge queue. Three separate regressions landed within minutes of each other; this clears all three. The worst is a literal `SyntaxError` — `ChatAgentConfig(...)` was passed `device=` twice, so the Agent UI backend and everything importing it failed at module load, taking out the Linux, Windows and macOS unit-test jobs. Nobody wrote that duplicate: amd#3666 and amd#4275 each added the same kwarg a few lines apart, neither diff conflicted textually, and the merge queue merged both cleanly into a file that does not parse. The other two are one-liners: amd#3402 re-imported `tool_cancelled` over a name the module already imports (failing the pylint gate) and shipped `wait_for_condition` with no UI label, and amd#4271 landed an over-long assertion (failing the black gate). **Worth knowing:** the ~13 "new pylint errors" that appear in the failing job's log are not pylint errors. They are the first 20 lines of the **non-blocking MyPy** output (1224 warnings, truncated for display) and have never gated anything. Only one pylint hit was real. No dependency or tool-version drift was involved — pylint 4.0.9 and black 26.5.1 both predate the last green run. ## Test plan - [ ] `python util/lint.py --black` — clean (1180 files unchanged) - [ ] `uvx pylint src/gaia --rcfile .pylintrc --disable C0103,C0301,W0246,W0221,E1102,R0401,E0401,W0718,W0212` — clean on Linux - [ ] `python -m compileall -q src/gaia tests` — no syntax errors - [ ] `python -m pytest tests/unit/test_schedule_daemon.py -q` — 28 passed - [ ] `python -m pytest tests/unit/chat/ui -q` — 1040 passed (was 17 collection errors) <details> <summary>🔍 Technical details</summary> **`src/gaia/ui/agent_loop.py`** — the two `device=session.get("device")` lines were textually identical, so deleting the later one restores exactly the intended call. `git blame` attributes line 461 to `1caad2ade5` (amd#4275) and line 465 to `7a8fea58b1` (amd#3666); amd#3666 is an ancestor of the last green commit `69f76ab57`, so amd#4275 is the one that created the duplicate. **`src/gaia/agents/tools/shell_tools.py`** — `gaia.agents.base.tools.tool_cancelled` is a pure re-export of `gaia.tool_cancellation.tool_cancelled`, which the module already imports at line 31. Verified the bindings are the same object, so dropping the function-local import is a no-op rather than a behaviour change. **Follow-up worth a maintainer's eye, deliberately not bundled here:** `wait_for_condition` executes arbitrary commands against the same allowlist as `run_shell_command`, but unlike `run_shell_command` it is not in `_GAIA_MUTATING_TOOLS`. By that set's own stated criterion ("or execute code") it looks like it belongs there, and omitting it means the tool skips the confirmation gating its sibling gets. That is a behaviour change, not a CI fix, so it should be reviewed on its own rather than smuggled into an unblock PR. **Also noted:** `.pylintrc` uses `disable = all` plus an explicit `enable` list that does not include `syntax-error`, which is why the pylint gate walked past a file it could not parse. Enabling `E0001` would have caught this at PR time. </details>
wait_for_condition (#3402) ships in the same shell bundle as run_shell_command, so it now reaches the bare chat profile fast mode composes as. Pin and ceiling updated to the new, intentional baseline -- still under a quarter of the default profile's cost. Also drops a stray agent_type key from a scenario this branch owns: the eval runner no longer honors per-scenario pins.
Resolves the tool-count collision and hardens the wait mixin's host contract. main added `wait_for_condition` (amd#3402) while this branch added `sleep`, so both sides claimed a flagship tool count of 82. The real merged count is 83; CORE goes to 16 and `dynamic_tools_max` to 29, keeping the dynamic share at 13. `gaia_agent/__init__.py` auto-merged to a stale 82 without conflicting — the capability-matrix reconciler is what caught it. Also: composing `wait` from KNOWN_TOOLS onto a host that is not an `Agent` used to die with a bare `AttributeError` several lines into a wait, after the model had already spent a step on it. `_sleep` now names the missing stop channel and refuses before waiting a single second. Registration stays permissive, because the registry is also built by skeletons (`build_full_agent_skeleton`) that only count tools and never call one.
The agent could not run anything that takes minutes. A shell command was killed at 30 seconds no matter what it was, so a test suite, a build or an install never finished — and a timed-out command on Windows did not even stop: a verified 5-second timeout took over two minutes and never returned, because the kill missed the grandchild still holding the pipes. Waiting was just as bad: with no way to wait for a condition, the agent slept and re-checked, which is what a user sees as spinning and what burns the loop's step budget. Now the timeout comes from what the command is — 900s for test runners, 1800s for builds and installs, 300s for git/network calls, 30s for everything else — the kill actually fires, Stop still lands while a command is running, and
wait_for_conditionwaits for a server to answer or a file to appear in one step instead of one per check.Closes #3382.
🔍 Technical details
src/gaia/agents/tools/command_timeouts.py— four named classes, one default each, plus the classifier. Wrappers are transparent (python -m pytest,uv run pytest,npx jest), and a pipeline takes its longest segment.timeout=still wins; out of range is refused, not clamped, so a command is never killed at a limit its caller did not choose.__doc__, and the non-native prompt path renders only its first line. A test fails if a class default drifts out of that line.Popenand waits on it in short slices, so it kills the process tree both at the deadline (taskkill /T/ process group) and the moment Stop lands — the per-tool guard is now over an hour, so nothing else would end a 30-minute build early. Partial output is truncated to 10K like the success path.shell:execute:<binary>); the base allowlist is read-only and refusespytest/pip/npmoutright. The guide says so, and a test drives a granted binary through the real allowlist into thetestclass.wait_for_conditionis confirmation-gated, runs its predicate throughrun_shell_command(same allowlist, refused before the prompt), is charged once against the shell rate limit rather than once per probe, and wakes on both cancel channels immediately.executed: False, so the verification footer (fix(agent): verification footer counts rejected test commands as executed #3677) never calls a refused check one that ran.Test plan
python -m pytest tests/unit/test_shell_adaptive_timeouts.py tests/unit/test_shell_guardrails.py tests/unit/test_shell_output_encoding.py tests/unit/test_skill_binary_grants.py -q— 393 pass. Each timeout class is asserted as the budget the command is really killed at, plus the wait primitive's deadline, and Stop landing before, during, and between commands.python -m pytest tests/unit/agents/ -q— 783 pass; covers the verification-scope contract this touches.python util/lint.py --all— clean.test_a_blown_deadline_really_kills_the_processpins it with a real child process.gaia eval agent --category tool_selectionon Gemma-4-E4B — judged pass rate unchanged vs thegemma-4-e4b-d71cd914baseline (75% → 75%), avg score 8.4 → 8.7.known_path_readwent FAIL → PASS. Nothing prompt-visible has changed since that run: the tool docstrings are byte-identical.rag_quality + context_retention + tool_selectioncheck — Eval gate fails identically on main: tool_selection scenarios die in 3s and claude's stderr is swallowed #3341 tracks it failing identically on main.