Skip to content

fix(shell): the rate-limit wait stops when the agent cancels the call - #4168

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/pace-interruptible
Sep 25, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/pace-interruptible

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

A shell command held back by the rate limit now waits in short slices and gives up the moment the agent cancels the call. Before this, it slept straight through: a user who pressed Stop waited out the rest of the wait, and a call that overran its own timeout left a worker running a command nobody was waiting for any more — the stray-process problem #2600 exists to prevent.

The pacing behaviour itself (#4023) is unchanged; only its interruptibility is. The mixin's spec had also kept describing the pre-#4023 contract — a refused 4th command, a caller-side sleep-and-retry loop, and a result shape without waited_seconds — so anyone reading it got the opposite of what the code does.

Test plan

  • pytest tests/unit/test_shell_rate_pacing.py tests/unit/test_shell_guardrails.py tests/unit/test_skill_binary_grants.py — 409 passed, 1 skipped.
  • New test_a_stop_during_the_wait_ends_it_instead_of_sleeping_on fails on main (the wait sleeps on) and passes here.
  • The burst test now asserts the wait totals 9s and that no single slice exceeds the poll interval, rather than pinning one long sleep.

🤖 Generated with Claude Code

Pacing landed in amd#4023 but sleeps straight through cancellation. Every tool runs
inside `_call_tool_bounded`'s window, which sets a cancellation flag when the
call overruns and stops waiting for the worker — so a wait of up to a minute
that ignores the flag keeps a worker alive past its own timeout, running the
command nobody is waiting for any more (amd#2600), and delays a user's Stop by the
rest of the wait.

The wait now runs in 0.25s slices and returns as soon as the flag is set.

`docs/spec/shell-tools-mixin.mdx` still taught the pre-amd#4023 contract — a
rate-limited 4th command, a caller-side sleep-and-retry loop, and a result shape
with no `waited_seconds` — so it now matches what the code does.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The rate-limit wait now happens in short slices and bails out as soon as the agent gives up on the call, instead of sleeping straight through — that's the right fix, the cancellation check lands before the first sleep so an already-abandoned call never sleeps at all, and the new test pins both the total wait and the slice size. Nothing here blocks merge.

Two things worth a follow-up:

  • A cancelled wait is reported as if it were a rate-limit refusal, with a "please wait 8.8 seconds" message attached. Today nothing reads that result, so there's no user-visible damage — but elsewhere in the codebase an abandoned tool signals it by raising the cancellation error rather than returning a fake refusal, and matching that keeps the two cases from blurring. Related: the description says a user pressing Stop is what triggers this, but as the code stands the only thing that sets the flag is a tool overrunning its own timeout.
  • The spec is half-updated. The result shape, the examples, and the tests now describe pacing, but the class listing and implementation section in the same file still show only the refuse-immediately design — and the new examples use a setting that page never documents.

Also worth a cheap test: the new one only covers the case where the call is already cancelled before any waiting happens, so nothing proves the "stops partway through a long wait" behaviour the fix is actually for.

Real-world evidence

No evidence bundle was produced for this PR (evidence-bundle.md absent). N/A is the right call here — this changes the internal wait loop of a tool mixin and adds no CLI, HTTP, MCP, or Agent-UI surface, so there is nothing a user-facing run would show that the unit tests don't. The PR's own test plan reports the suite green; I could not re-run it in this reviewer environment (pytest isn't installed), so my verdict rests on static review plus the author's reported run.

🔍 Technical details

🟡 Cancellation is reported as a rate-limit refusal (src/gaia/agents/tools/shell_tools.py:1300)

return False, "Rate limit wait cancelled", remaining, waited flows into the refusal branch at shell_tools.py:1859-1872, which emits rate_limited: True and error: "Rate limit wait cancelled. Please wait 8.8 seconds.". That contradicts the contract this same PR writes into the spec — "rate_limited": bool, # If refused rather than paced — and hands a model an instruction to wait when the real reason is abandonment.

It is harmless today only because the flag is set exclusively by Agent._call_tool_bounded (agent.py:4037) after it has already raised ToolExecutionTimeout and discarded holder["result"]. That makes the return value dead on this path, which is also why raising is safe here:

                if tool_cancelled():
                    raise_if_cancelled()

(with raise_if_cancelled added to the import at shell_tools.py:24), or simply raise_if_cancelled() in place of the whole if. That matches audio_tools.py:494,508,670 — the other long-running tool that opted into this flag — and keeps a cancelled call from masquerading as a rate-limit refusal if the flag ever gains a second setter (e.g. a real Stop path). If you'd rather keep the return-based shape, a distinct key (cancelled: True) instead of rate_limited: True would do.

Worth reconciling the PR description too: it attributes the fix to a user pressing Stop, but grep -n "cancel.set()" src/gaia/agents/base/agent.py shows the timeout expiry is the only setter.

🟢 The new test doesn't cover a mid-wait cancellation (tests/unit/test_shell_rate_pacing.py:110)

test_a_stop_during_the_wait_ends_it_instead_of_sleeping_on patches tool_cancelled to a constant True and asserts clock.slept == [] — i.e. it only exercises the "already cancelled before the first slice" path. The behaviour the fix exists for is a flag that flips during the wait. A counter-based stub covers it and also pins the partial waited accounting:

    host = _Host()
    host.shell_command_times.extend([clock.now - 1] * 3)
    calls = {"n": 0}

    def _cancel_after_two_slices():
        calls["n"] += 1
        return calls["n"] > 2

    monkeypatch.setattr(shell_tools, "tool_cancelled", _cancel_after_two_slices)

    result = _run(host, tmp_path)

    assert result["rate_limited"] is True
    assert result["executed"] is False
    # Stopped partway, nowhere near the full 9s window.
    assert sum(clock.slept) == pytest.approx(2 * ShellToolsMixin._PACE_POLL_SECONDS)

🟢 docs/spec/shell-tools-mixin.mdx is still half pre-#4023

The result shape (line 231-233), the tests (358-375) and Example 3 (477-490) were updated, but the parts of the same page that describe the class surface were not:

  • The Attributes: list (163-164) names max_commands_per_minute / max_commands_per_10_seconds but not max_rate_limit_wait_seconds — which the updated snippets at lines 372 and 488 both rely on.
  • The class listing (181-192) declares _check_rate_limit and _record_command_execution; _pace_rate_limit is absent.
  • ### Rate Limiting under Implementation Details (251-270) shows only _check_rate_limit returning a refusal — no pacing loop, no slicing, no cancellation check.
  • Security layer 1 (204) still reads "Rate limit check (burst + sustained)"; it is now a check-and-pace.

Per CLAUDE.md ("a functional change must update EVERY doc that describes it"), and given de-staling this page is a stated goal of the PR, adding _pace_rate_limit + the attribute to the listing and a short pacing block under Implementation Details would finish it.

🟢 Unused loop variable in the new doc snippet (docs/spec/shell-tools-mixin.mdx:373)

    for _ in range(4):

Strengths

  • The cancellation check is placed at the top of the slice loop, so an already-abandoned call returns without sleeping at all — easy to get backwards, and the test asserts it.
  • assert max(clock.slept) <= ShellToolsMixin._PACE_POLL_SECONDS alongside sum(...) == approx(9.0) tests the property (bounded slices, unchanged total) rather than pinning an implementation detail, so the poll interval can be retuned without touching the test.
  • No busy-spin risk: _check_rate_limit always returns a strictly positive wait_time when it refuses (10 - (current_time - oldest_in_window) with oldest_in_window > ten_sec_ago), so the inner loop always runs at least once and the flag is always polled.
  • The one-line comments explain why (the _call_tool_bounded window, fix(agents): abandoned tool-timeout threads leak log records and state into unrelated code #2600) without the multi-paragraph history CLAUDE.md warns against.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into amd:main with commit 01af64f Sep 25, 2026
39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants