Skip to content

fix(eval): cancel the task when a rollout gives up during tasks.start - #707

Closed
TanishGudise wants to merge 1 commit into
hud-evals:mainfrom
TanishGudise:fix/rollout-cancel-during-control-call
Closed

TanishGudise wants to merge 1 commit into
hud-evals:mainfrom
TanishGudise:fix/rollout-cancel-during-control-call

Conversation

@TanishGudise

@TanishGudise TanishGudise commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What

HudClient sends one request at a time (_call_lock, from #530). When a rollout times out or is cancelled, rollout() calls asyncio.wait_for(client.cancel(), timeout=2.0) and then client.abort(). If tasks.start is still in flight, that cancel queues behind it. When the start outlasts the 2-second bound, the cancel is never sent, and the transport is closed. The env then finishes the start after the client is gone and parks the session. That's the case the comment above the code describes ("a bare abort parks the session and would leak claims").

Two consequences:

  • The task's teardown (its finally, and _on_task_teardown hooks such as RobotEndpoint.release_claim) doesn't run until the substrate shuts down. On a substrate that outlives the rollout (Shared, or Runtime(url) against a served env), that can mean never.
  • A later client's plain tasks.grade (the split start/grade flow) adopts the orphaned session and receives its grade.

The same happens when the rollout is cancelled from outside:

  • with rollout_timeout=None, the cancellation reaches the in-flight tasks.start call itself, which aborts the transport;
  • with a timeout set, it goes through the same 2-second cancel.

Robot reset() loops until a slot is free, so a slow tasks.start is a realistic place for this.

A rollout that times out while tasks.start or tasks.grade is in flight also returns up to 2 seconds after rollout_timeout, not immediately as its docstring said.

Fix

  • New HudClient.cancel_and_abort(reply_timeout=...).
    • With the channel idle, it does what rollout() did before: an awaited cancel, bounded by reply_timeout, then abort. So a timeout in the agent loop still lets the env finish tearing the task down before the substrate shuts down.
    • While a request holds the channel, it queues tasks.cancel as a JSON-RPC notification (no id; the server already sends no reply for those) and closes the transport. The env handles a session's frames in order, so the cancel runs as soon as the in-flight request returns, and closing the transport flushes the frame first.
  • rollout()'s timeout and CancelledError paths call it with the same 2-second bound.
  • HudClient.start_task queues the same cancel when its own call is abandoned (cancelled, or a transport failure while the connection still works), since nobody received that task's prompt. The mismatched-reply-id branch does the same.
  • docs/v6/internals/control-channel.mdx gains two sentences, on notifications and on abandoned starts.
  • The rollout() docstring now describes the timeout path as it behaves, instead of "returns an errored run immediately".

tasks.grade needs no new path: the env removes the task when grading starts and runs its teardown when grading ends.

abort(cancel_task=) is only used internally; happy to make it private if you'd prefer.

One behaviour change for users who didn't hit the bug: Ctrl-C while hud task start waits for tasks.start now cancels the task instead of leaving it parked for hud task grade to adopt. That start never printed a prompt.

Not covered:

  • A tasks.start that never returns. The env only reads the cancel after the start returns, so that task is still torn down only when the substrate shuts down.
  • A start reply too large for the socket to accept once the client is gone. Here, 1 MB and 8 MB prompts on loopback parked 3 of 3 each. The env's write fails before it reads the queued cancel, and fix(environment): support 16 MiB control frames with explicit size errors #656 made parking on a failed prompt write deliberate ("transport failures leave it parked for session resume"; test_disconnect_parks_the_task_for_a_later_connection). Changing that is a separate decision.
  • A heartbeat hello that times out (an env more than 5 s slow to answer) aborts without a cancel, so a task on a live substrate parks as before.
  • cancel_and_abort decides from whether the call lock is held at that moment. If a request is queued for the lock but hasn't taken it yet, the awaited cancel waits behind it, as on main. If the timeout coincides with a heartbeat hello (milliseconds every 120 s), it queues the cancel and closes at once, as this PR does for in-flight calls.

Tests

Through public APIs only (rollout, Shared, LocalRuntime, an Environment), with no patching of hud names:

  • test_timeout_while_starting_tears_the_task_down_on_a_shared_runtime
  • test_cancelled_rollout_while_starting_tears_the_task_down_on_a_shared_runtime[None]: the driver's own tasks.start call is cancelled.
  • test_cancelled_rollout_while_starting_tears_the_task_down_on_a_shared_runtime[60.0]: rollout()'s handler runs while the start is in flight.
  • test_timeout_in_the_agent_loop_lets_the_task_teardown_finish: a guard. It passes on main; an earlier version of this change, which always queued the cancel and closed immediately, failed it.

test_timeout_aborts_when_cancel_rpc_hangs is kept and still passes; its abort spy now forwards the new cancel_task keyword.

On main the first three tests fail at await asyncio.wait_for(torn_down.wait(), 5.0) because the task's teardown doesn't run. With the fix all four pass, 10 of 10 runs. Each piece of the fix has a test that fails without it:

Removed Fails
the in-flight branch of cancel_and_abort (always await the bounded cancel, as on main) test_timeout_while_starting_..., test_cancelled_rollout_while_starting_...[60.0]
cancel_task_on_abort=True in start_task test_cancelled_rollout_while_starting_...[None]

Against Runtime(url) on a served env with rollout_timeout=0.3, where tasks.start finishes only after the rollout has returned (more than 2 s after the timeout), 5 of 5 runs each:

main this PR
rollout() returns after 2.30 s 0.30 s
task teardown doesn't run until the substrate shuts down runs when the start returns
a later client's plain tasks.grade gets {'score': 1.0} no task in progress

With grading that outlasts the window, on LocalRuntime (3 of 3 each): main returns after 2.30 s, this PR after 0.30 s.

Touches tests that draft #700 moves; happy to update after it lands.

Checks

  • uv run pytest -q: 3 failed, 1524 passed, 6 skipped, 27 deselected. The 3 failures fail the same way on main here: they are the test_docker_provider.py Modal tests that need the modal extra.
  • ruff format --check, ruff check: clean.
  • ty check --error-on-warning: no new diagnostics compared with main. The remaining 9 are unresolved torch/modal/daytona imports, for extras not installed locally.

🤖 Generated with Claude Code


Note

Medium Risk
Changes rollout and control-channel teardown on timeout/cancel; fixes resource leaks on shared runtimes but alters split start/grade behavior when start never delivered a prompt.

Overview
Fixes rollouts that time out or are cancelled while tasks.start (or grading) is still in flight: instead of closing the control channel and leaving a parked session on long-lived substrates (Shared, remote envs), the client now tears the task down reliably.

HudClient adds cancel_and_abort: when the channel is idle it awaits a bounded tasks.cancel RPC then aborts; when a request holds the lock it queues tasks.cancel as a JSON-RPC notification (no id) before closing so the server runs cancel after the in-flight call returns. start_task uses the same cancel-on-abort path when the start is abandoned before a prompt is received. rollout() timeout and CancelledError paths call cancel_and_abort (2s bound) instead of racing cancel behind an in-flight start.

Control-channel docs note notifications and that abandoned starts are cancelled, not parked. New rollout tests cover slow-start timeouts/cancellation on Shared runtimes and agent-loop teardown.

Reviewed by Cursor Bugbot for commit c321263. Bugbot is set up for automated code reviews on this repo. Configure here.

A rollout that timed out or was cancelled while tasks.start was in flight
never reached the env if that call outlasted the cancel's 2s bound: the
cancel RPC queued behind the in-flight call on the client's call lock, and
the transport was aborted. The env then parked the started session, so its
teardown didn't run until the substrate shut down (never, for one that
outlives the rollout such as Shared or Runtime(url)), and a later blind
tasks.grade adopted it.

HudClient.cancel_and_abort keeps the bounded, awaited cancel when the
channel is idle and, while a request is in flight, queues tasks.cancel as
a notification before closing; the env handles a session's frames in
order, so it runs as soon as that request returns. rollout()'s timeout and
CancelledError paths use it, and start_task queues the same cancel when
its own call is abandoned.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
jdchawla29 added a commit that referenced this pull request Oct 27, 2026
A rollout that timed out or was cancelled sent tasks.cancel through the
client's serialized call path, so while tasks.start was in flight the cancel
queued behind it and never went out within its 2 s bound. The transport then
closed, the env let the start finish and parked it, and the task's teardown
(its finally, robot claim release) did not run while the substrate lived; a
later client's plain tasks.grade adopted the orphan. With no rollout_timeout,
the cancellation reached the driver's own call first and closed the transport
before any cancel.

HudClient now has one path for abandoning its task: it writes tasks.cancel
ahead of the call lock, so the env interrupts a start or grade in flight at
once, waits up to 2 s for the cancel's reply (teardown done), then aborts.
rollout's timeout and cancellation paths both use it, and rollout waits on its
driver with asyncio.wait in both modes so a cancellation leaves the in-flight
call to the env's interrupt. A rollout that gives up mid-start or mid-grade
now returns without the 2 s stall.

Refs #707
Co-authored-by: Tanish Gudise <[email protected]>
@jdchawla29

Copy link
Copy Markdown
Collaborator

Incorporated into #758.

@jdchawla29 jdchawla29 closed this Oct 27, 2026
jdchawla29 added a commit that referenced this pull request Oct 27, 2026
* fix(graders): don't read "NOT MET" or a missing verdict as MET in the judge

When a judge reply wasn't JSON, LLMJudgeGrader read it as MET whenever the
uppercased text contained "MET" but not "UNMET", so "Criterion status: NOT
MET", "the wrong method" and "something went wrong" all gave full credit on a
positive criterion, or applied the penalty on a negative one. An empty reply
or a JSON reply whose criterion_status was missing or unknown silently read
as UNMET.

The prose fallback now takes MET only as a whole uppercase word, counts an
UN or NOT prefix as UNMET, and lets any UNMET win. A reply with no verdict,
in prose or as a JSON criterion_status other than MET/UNMET, raises
ValueError, so the run is reported as a grading error and left out of the
job's reward instead of being scored.

Refs #719

Co-authored-by: Mike-7777777 <[email protected]>

* fix(graders): parse complete decimal and scientific numbers in numeric_match

numeric_match read the first number with -?\d+\.?\d*, which stops at a
leading decimal point or an exponent: ".5" read as 5 and "1e3" as 1, so the
correct answer scored 0 and the misread one scored 1. It now reads a signed
decimal with an optional leading-dot form and exponent, which float() always
parses, so the unreachable ValueError branch is gone.

Refs #747

Co-authored-by: Lohith248 <[email protected]>

* fix(train): validate GRPO groups the way the training request sends them

The training request carries only group_size, and the service normalizes
advantages over contiguous slices of that size (the whole batch when it is
None). The client-side check keyed groups by each run's group_id instead, so
an interleaved batch [A1, B1, A2, B2] passed validation and was trained as two
mixed groups, while the SDK warned that no group had reward spread. With no
group_size, a batch rewarded [1, 1, 0, 0] across two group_ids drew the same
false warning although the service sees one group with spread.

A batch of runs whose positional slices mix group_ids is now refused before
anything is sent, and the reward-spread warning reads the same positional
slices the service uses.

Refs #749
Closes #748

Co-authored-by: Suyash Bhattarai <[email protected]>

* fix(train): refuse runs without a valid grade

A run that ended before grading, whether it failed, timed out or was
cancelled, kept a default Grade: reward 0.0 with is_error false. Job.reward
and Job.errors each combined the grade with the trace's status to tell it
apart, and the training client checked neither, so such a run, or one whose
grade was an error (an EvaluationResult(reward=0.7, isError=True) trained as
0.7), was sent to forward-backward.

A run now starts with an error grade, "not graded", that only a real grade
replaces, as hosted runs already reported an ungraded failure. grade.is_error
is the one test: Job.reward and Job.errors read it, the training client
refuses such a run and names it, and the training docs and cookbooks filter
on it. The daytona-rl trainer, which installs the released SDK, leaves out
every GRPO group that contains a run from job.errors instead of sending it.

Refs #754

Co-authored-by: Qais-Hweidi <[email protected]>

* fix(claude): don't execute a tool call cut off by max_tokens

The Anthropic SDK's stream accumulator parses tool input JSON in partial
mode, silently dropping an unfinished trailing value and returning a
well-formed dict. ClaudeAgent turned that dict into the call's arguments,
so a tool_use cut off by max_tokens ran with truncated arguments.

When a response stops at max_tokens, its final content block is the one
that was cut off. If that block is a tool_use, its arguments now reach the
tool loop as a JSON string, which is never executed: the model gets an
"arrived incomplete ... re-issue" error result, as the OpenAI adapters
already produce for unparseable arguments. This covers plain tools and
computer-toolset members alike; earlier tool_use blocks in the same
response still run.

Refs #720

Co-authored-by: Mike-7777777 <[email protected]>

* fix(eval): finish hosted cancellation before shutdown

On Ctrl-C or a rollout deadline, HostedRuntime scheduled the platform's
/rollouts/cancel as a background task and returned. Under `hud eval
--remote`, asyncio.run then cancelled that task while shutting the loop
down, so the cancel never reached the platform and the hosted rollouts kept
running until the platform's own runtime limit.

The runtime now awaits the cancel request, bounded at five seconds, before
it propagates the cancellation or returns the timeout result. A failed or
slow cancel is logged and never replaces the caller's outcome.

Refs #746

Co-authored-by: Lohith248 <[email protected]>

* fix(cli): tear down spawned environments when hud eval gets SIGTERM

hud eval, hud task start and hud task grade ran their work under a plain
asyncio.run, which handles Ctrl-C but not SIGTERM. Environments they spawn
locally run in sessions of their own, so a SIGTERM to the CLI (timeout,
kill, a supervisor) killed it outright and left those environments running.
The environment server had its own SIGTERM handling for the same idea.

hud.utils.process.run_until_terminated is now the one way an entry point
runs its main coroutine: SIGTERM cancels it the way Ctrl-C does, so
placements tear down what they started; a repeated SIGTERM is ignored so it
cannot cut that teardown short; and a run SIGTERM ended exits with 143
(128 + SIGTERM). hud eval, hud task start/grade, hud serve and
python -m hud.environment.server all use it, which replaces
serve_until_terminated. A served environment stopped by SIGTERM now exits
143 instead of 0.

Refs #708

Co-authored-by: Tanish Gudise <[email protected]>

* fix(eval): cancel the task when a rollout gives up during tasks.start

A rollout that timed out or was cancelled sent tasks.cancel through the
client's serialized call path, so while tasks.start was in flight the cancel
queued behind it and never went out within its 2 s bound. The transport then
closed, the env let the start finish and parked it, and the task's teardown
(its finally, robot claim release) did not run while the substrate lived; a
later client's plain tasks.grade adopted the orphan. With no rollout_timeout,
the cancellation reached the driver's own call first and closed the transport
before any cancel.

HudClient now has one path for abandoning its task: it writes tasks.cancel
ahead of the call lock, so the env interrupts a start or grade in flight at
once, waits up to 2 s for the cancel's reply (teardown done), then aborts.
rollout's timeout and cancellation paths both use it, and rollout waits on its
driver with asyncio.wait in both modes so a cancellation leaves the in-flight
call to the env's interrupt. A rollout that gives up mid-start or mid-grade
now returns without the 2 s stall.

Refs #707
Co-authored-by: Tanish Gudise <[email protected]>

* fix(environment): guard every way a process opens a connection to a protected port

The process guard compared each connect() destination with its protected
relay addresses exactly. It now checks every way a guarded process can open
a TCP connection to a protected port: a connect to an unspecified address
(0.0.0.0, ::, ::ffff:0.0.0.0) counts as reaching every protected relay on
that port, since Linux delivers it to a loopback listener there; sendto,
sendmsg and sendmmsg with MSG_FASTOPEN fail with EOPNOTSUPP, as they do when
client Fast Open is disabled, so clients fall back to connect(); and x32
syscalls fail with ENOSYS, as on kernels without x32.

The process-bound connection scenario covers these, reads a child's exit
status from the last line of its output, and counts every request a relay
receives rather than the distinct ones.

Refs #756

Co-authored-by: Qais-Hweidi <[email protected]>

* fix(environment): reject a non-finite reward instead of averaging it in

A template that yielded NaN or an infinity, as a number, a {"score": ...}
dict, or an EvaluationResult, passed the grade checks on both sides of the
wire because they looked only at the type. The run counted as graded, one
such run turned Job.reward into NaN, `hud task grade --json` printed
`NaN`/`Infinity` (not JSON), and the trace exit report could not be
serialized.

The environment server now rejects a non-finite score for every grade
shape with a message naming the task, and Grade.from_dict rejects one too,
since environment images pinned to older releases still send it. The run
takes the existing failed-grade path: it lands in Job.errors and stays out
of Job.reward.

Refs #721
Co-authored-by: Mike-7777777 <[email protected]>

* fix(eval): collect a task exposed under several names once

Taskset.from_module collects every public Task and every Task in a public
list, tuple, or Taskset. A module that names a task and also groups it
(`task = t(); tasks = [task]`), or a directory where one module imports a
task from another, yielded the same object more than once, so loading it
failed with "duplicate task slugs". That broke `hud task list`, `hud eval`,
`hud sync`, and the Harbor export for such sources, including the featured
browser-use environment.

from_module now keeps one entry per task object, in first-seen order.
Distinct tasks that share a slug still fail.

Refs #750
Co-authored-by: Kunal Roy Choudhury <[email protected]>

* fix(coding): grade a timed-out test run as a failure

grade_tests checked for a missing JUnit report before checking for a
timeout. A hidden-test run killed at GRADING_TIMEOUT usually never writes
its report, so it was returned as "test command did not write JUnit XML",
which the template turns into a grading error: the run was left out of
the job's mean reward instead of scoring 0. Check the timeout first, in
both the coding template and the flask-coding featured environment.

Refs #740

Co-authored-by: Salma <[email protected]>

* fix(file-analysis): make reconcile_supplier_payments attachments optional

The reconcile_supplier_payments template describes its uploads as
optional and reviews the bundled supplier records either way, but it
declared attachments without a default, so the manifest listed it as
required and starting the task without it failed with "missing a
required argument: 'attachments'". Default it to no uploads. The
parameters become keyword-only so the field order stays the same.

Refs #752

Co-authored-by: Asadullo Ganiev <[email protected]>

* fix(eval): treat a normal tunnel close as the end of the stream

When the gateway closed a HUD runtime tunnel's websocket normally while the
local side was still sending, the send raised ConnectionClosedOK, and the
splice re-raised it out of the server callback, so asyncio logged an
unhandled-exception traceback for an orderly close. A normal close now ends
the splice quietly, as it already did on the receiving side; an abnormal
close still raises.

Refs #693

Co-authored-by: Lukass Kellijs <[email protected]>

* feat(cli): report runs that failed mid-run but were still graded

When a run's agent loop failed partway, for example on a model provider
error or a timeout, its trace ended in error and the environment graded
what was there. Such a run counts toward the mean reward and is not an
error, so hud eval showed it only as a low reward: a job where the
provider was down looked like one where the agent scored 0.

The summary now counts these runs, and each run in the --json document
carries trace_error, the error its trace ended with. Rewards, error
counts, and exit codes are unchanged.

Refs #717

* fix(coding): score a run without a usable JUnit report as a failure

The hidden tests import the agent's code, so that code can end the run
before pytest writes its report (os._exit at import) or overwrite it.
grade_tests recorded the missing or unreadable report in info["error"],
and the template turned that into a grading error, so the run was left
out of the job's mean reward instead of scoring 0.

The template now returns that run as a 0 score, with the reason still
in the tests subscore's info["error"]. The test selection checks
(duplicate, overlapping or empty node IDs) move out of scoring to the
start of the task, next to the test_path check, so a bad selection
still fails before the agent runs. A hidden test patch that does not
apply stays a grading error. Applied to the coding template and the
flask-coding featured environment.

Refs #740
Closes #737

Co-authored-by: Salma <[email protected]>

* fix(harbor): keep the head and tail of verifier output on the evaluation

evaluation() stored only the last 4000 characters of verifier stdout and
stderr, so a long report lost its head, including the first failures, and
the stored text started mid-line. Each stream now keeps its head and tail
around a [truncated] marker within the same 4000 characters.

bound_shell_output moves from hud.agents.tools.ssh to hud.utils.process so
the in-image Harbor controller can use it without importing hud.agents.

Refs #753
Co-authored-by: Asadullo Ganiev <[email protected]>

* test: show a real model's answer when it misses a fixture's reward

The live end-to-end cells failed with only (0.0, None), so a model that
refused, misformatted its answer or never called a tool looked the same.

* fix(daytona-rl): leave out timed-out groups when training

The trainer left out groups containing a run from job.errors, but a run that
timed out and was still graded is not one, and the training client refuses
timed-out runs, so an agent timeout ended the training loop. Groups with a
timed-out run are now left out too.

* fix(eval): treat a hosted run that finished without a reward as ungraded

A hosted rollout that reached a terminal status with neither a reward nor an
evaluation result got a 0.0 grade unless it errored or was cancelled, so a
completed run that was never graded counted as a real zero in Job.reward and
could be trained on. A missing reward is now an error grade whatever the
status, as for local runs.

---------

Co-authored-by: Mike-7777777 <[email protected]>
Co-authored-by: Lohith248 <[email protected]>
Co-authored-by: Suyash Bhattarai <[email protected]>
Co-authored-by: Qais-Hweidi <[email protected]>
Co-authored-by: Tanish Gudise <[email protected]>
Co-authored-by: Kunal Roy Choudhury <[email protected]>
Co-authored-by: Salma <[email protected]>
Co-authored-by: Asadullo Ganiev <[email protected]>
Co-authored-by: Lukass Kellijs <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants