Skip to content

Cancelled local rollouts never report a trace exit #709

Closed

Description

@TanishGudise

What happens

When a rollout driven by rollout() (any local placement: LocalRuntime, SubprocessRuntime, DockerRuntime, Runtime(url), ...) is cancelled, its except asyncio.CancelledError handler in hud/eval/run.py re-raises without calling trace_exit(run). POST /trace/{id}/enter was already sent when the rollout started, so the platform never hears that the trace ended.

Run.__aexit__ sets trace.status = "cancelled" for exactly this case, but nothing sends it. HostedRuntime.run handles the same situation by cancelling the platform trace (_cancel_later).

The most common way to hit it is Ctrl-C during hud eval tasks.py <agent>: every rollout in flight is entered and never exited. Programmatic cancellation does the same, for example asyncio.timeout(...) around Taskset.run, or a training loop that cancels a batch.

Reproduction

A local HTTP server stands in for the HUD API and telemetry (HUD_API_URL and HUD_TELEMETRY_URL point at it, with a dummy HUD_API_KEY), so nothing reaches hud.ai. A 4-rollout Taskset.run on SubprocessRuntime (the placement hud eval uses for a tasks file) gets SIGINT once all four agents are running. On main (5bdc0fe) its output ends with this every time (3 of 3 runs), after the driver's own tracebacks from the interrupt:

trace enter: 4
trace exit:  0

The script (the agent just waits):

"""Ctrl-C a 4-rollout local batch and count the trace reports a stand-in HUD API receives."""

import os
import signal
import subprocess
import sys
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

ENV = """
from hud import Environment

env = Environment("demo")


@env.template()
async def wait(i: int = 0):
    yield "prompt"
    yield 1.0
"""

DRIVER = """
import asyncio, sys
from pathlib import Path
from hud.agents.base import Agent
from hud.eval import SubprocessRuntime, Task, Taskset

class Waiting(Agent):
    running = 0
    async def __call__(self, run):
        Waiting.running += 1
        if Waiting.running == 4:
            Path(sys.argv[2]).touch()
        await asyncio.Event().wait()

tasks = [Task(env="demo", id="wait", args={"i": i}) for i in range(4)]
asyncio.run(Taskset("demo", tasks).run(Waiting(), runtime=SubprocessRuntime(sys.argv[1])))
"""

paths: list[str] = []


class StandIn(BaseHTTPRequestHandler):
    def do_POST(self) -> None:
        self.rfile.read(int(self.headers.get("Content-Length", 0)))
        paths.append(self.path)
        self.send_response(200)
        self.send_header("Content-Length", "2")
        self.end_headers()
        self.wfile.write(b"{}")

    def log_message(self, format: str, *args: object) -> None:
        pass


server = ThreadingHTTPServer(("127.0.0.1", 0), StandIn)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f"http://127.0.0.1:{server.server_address[1]}"

work = Path(tempfile.mkdtemp())
(work / "env.py").write_text(ENV)
ready = work / "ready"
env = {**os.environ, "HUD_API_KEY": "dummy", "HUD_API_URL": url, "HUD_TELEMETRY_URL": url}
driver = subprocess.Popen([sys.executable, "-c", DRIVER, str(work / "env.py"), str(ready)], env=env)
while not ready.exists():
    time.sleep(0.05)
driver.send_signal(signal.SIGINT)  # Ctrl-C
driver.wait()
time.sleep(0.5)
print("trace enter:", sum("/trace/" in p and p.endswith("/enter") and "/job/" not in p for p in paths))
print("trace exit: ", sum("/trace/" in p and p.endswith("/exit") for p in paths))

Expected

Every trace that was entered gets an exit report (status: "cancelled") before the cancellation propagates, with a short bound so Ctrl-C stays fast.

Possible fix

In the CancelledError handler, set the run's status (synthesizing a cancelled Run when the rollout was cancelled before it went live) and await asyncio.wait_for(trace_exit(run), timeout=...) before re-raising. I didn't open a PR because I can't tell from the SDK what the platform does with traces that never exit. #220 reported a similar symptom (sessions left live after Ctrl-C) on an earlier SDK, and the reply there said environments are cleaned up after 3 hours. If v6 traces have a similar sweep, this may only be cosmetic. Happy to send the PR if it's useful.

Activity

  1. Monarch-25 commented on Oct 14, 2026

    @Monarch-25

    Raised a PR #716

  2. jdchawla29 commented on Oct 27, 2026

    @jdchawla29
    Collaborator

    Superseded or resolved by #700.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions