Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 78 additions & 42 deletions components/src/dynamo/sglang/request_handlers/cancellation.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@
_CANCELLATION_DISPATCH_WAIT_TIMEOUT_S = 0.25


async def _next_stream_item(iterator: AsyncIterator[Any]) -> Any:
return await anext(iterator)


def _consume_detached_task(task: asyncio.Task[Any]) -> None:
"""Consume a detached cancellation task result without surfacing closure."""
try:
Expand Down Expand Up @@ -108,50 +104,71 @@ async def _stream_until_cancelled(
stream_source: AsyncIterator[Any],
cancellation_task: asyncio.Task[Any],
) -> AsyncGenerator[Any, None]:
"""Drain briefly after abort, then stop a stream that did not terminate."""
"""Drain briefly after abort, then stop a stream that did not terminate.

One reader task per stream fetches a chunk each time the consumer asks,
so the consumer only waits on a plain future, not a Task plus
asyncio.wait() per chunk. Cancellation resolves that future at the drain
deadline (at once if the monitor failed), even if the stream is slow to
honor cancellation; the reader is then cancelled and detached.
"""
iterator = aiter(stream_source)
drain_deadline: float | None = None
while True:
next_item = asyncio.create_task(_next_stream_item(iterator))
try:
if drain_deadline is None:
done, _ = await asyncio.wait(
(next_item, cancellation_task),
return_when=asyncio.FIRST_COMPLETED,
)
if cancellation_task in done:
cancellation_task.result()
drain_deadline = (
asyncio.get_running_loop().time()
+ _CANCELLATION_DRAIN_TIMEOUT_S
)
if next_item in done:
try:
yield next_item.result()
except StopAsyncIteration:
return
continue

assert drain_deadline is not None
remaining = drain_deadline - asyncio.get_running_loop().time()
if remaining <= 0:
logging.warning(
"Timed out draining SGLang stream after cancellation"
)
loop = asyncio.get_running_loop()
# Carries the consumer's reply future to the reader.
request: asyncio.Future[asyncio.Future[Any]] = loop.create_future()
reply: asyncio.Future[Any] | None = None
interrupted = False
timer: asyncio.TimerHandle | None = None

async def read_on_request() -> None:
nonlocal request
while True:
pending = await request
request = loop.create_future()
try:
item = await anext(iterator)
except (Exception, asyncio.CancelledError) as exc:
if not pending.done():
pending.set_exception(exc)
return
Comment thread
jthomson04 marked this conversation as resolved.
Resolved
done, _ = await asyncio.wait((next_item,), timeout=remaining)
if next_item not in done:
logging.warning(
"Timed out draining SGLang stream after cancellation"
)
if pending.done(): # the consumer stopped waiting
return
pending.set_result(item)

def interrupt() -> None:
nonlocal interrupted
interrupted = True
if reply is not None and not reply.done():
reply.set_result(None)

def on_cancellation(task: asyncio.Task[Any]) -> None:
nonlocal timer
if task.cancelled() or task.exception() is not None:
interrupt()
else:
timer = loop.call_later(_CANCELLATION_DRAIN_TIMEOUT_S, interrupt)

reader = asyncio.create_task(read_on_request())
cancellation_task.add_done_callback(on_cancellation)
try:
while not interrupted:
reply = loop.create_future()
request.set_result(reply)
try:
yield next_item.result()
item = await reply
except StopAsyncIteration:
return
finally:
if not next_item.done():
_cancel_and_detach(next_item)
if interrupted:
break
yield item
cancellation_task.result() # re-raise a monitor failure
logging.warning("Timed out draining SGLang stream after cancellation")
finally:
cancellation_task.remove_done_callback(on_cancellation)
if timer is not None:
timer.cancel()
if not reader.done():
_cancel_and_detach(reader)

@asynccontextmanager
async def _wait_for_signal(self, context: Context) -> AsyncGenerator[bool, None]:
Expand Down Expand Up @@ -433,7 +450,24 @@ async def _cancellation_monitor(
finally:
request_id = self._resolved_request_id(request_id_future)
ordered_abort_task = None
owner_cancelled: asyncio.CancelledError | None = None
try:
if not cancellation_task.done() and (
context.is_stopped()
or (
self.shutdown_event is not None and self.shutdown_event.is_set()
)
):
# The signal fired and the stream ended first: let the monitor
# finish ordering its abort rather than racing a fallback abort.
try:
await asyncio.wait(
(cancellation_task,),
timeout=_CANCELLATION_DISPATCH_WAIT_TIMEOUT_S,
)
except asyncio.CancelledError as exc:
# Finish the cleanup below, then propagate.
owner_cancelled = exc
Comment thread
jthomson04 marked this conversation as resolved.
Resolved
if not cancellation_task.done():
logging.debug(
"Cancelling cancellation monitor task for SGLang Request ID %s, Context: %s",
Expand All @@ -457,3 +491,5 @@ async def _cancellation_monitor(

if self.shutdown_event and self.shutdown_event.is_set():
raise EngineShutdown("Engine was shut down during token generation")
if owner_cancelled is not None:
raise owner_cancelled
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,63 @@ async def set_shutdown_when_cancelled(*_args):
handler._handle_cancellation = set_shutdown_when_cancelled
request_id_future = asyncio.get_running_loop().create_future()
request_id_future.set_result("sglang-request-id")
context = SimpleNamespace(id=lambda: "request-id")
context = SimpleNamespace(id=lambda: "request-id", is_stopped=lambda: False)

with pytest.raises(EngineShutdown, match="shut down during token generation"):
async with handler._cancellation_monitor(request_id_future, context):
await asyncio.sleep(0)


@pytest.mark.asyncio
@pytest.mark.timeout(5)
async def test_cancellation_monitor_cleanup_finishes_when_owner_cancelled(
monkeypatch,
):
monkeypatch.setattr(
"dynamo.sglang.request_handlers.cancellation._CANCELLATION_DISPATCH_WAIT_TIMEOUT_S",
5,
)
handler = DecodeWorkerHandler.__new__(DecodeWorkerHandler)
handler.shutdown_event = None
handler._abort_tasks = set()
abort_calls = []
handler.engine = SimpleNamespace(
tokenizer_manager=SimpleNamespace(
abort_request=lambda rid, abort_all: abort_calls.append(rid)
)
)
monitor_cancelled = asyncio.Event()

async def monitor_never_finishes(*_args):
try:
await asyncio.Future()
except asyncio.CancelledError:
monitor_cancelled.set()
raise

handler._handle_cancellation = monitor_never_finishes
request_id_future = asyncio.get_running_loop().create_future()
request_id_future.set_result("sglang-request-id")
context = SimpleNamespace(id=lambda: "request-id", is_stopped=lambda: True)
in_cleanup = asyncio.Event()

async def owner():
async with handler._cancellation_monitor(
request_id_future, context, request_ids={"sglang-request-id"}
):
in_cleanup.set()

owner_task = asyncio.create_task(owner())
await in_cleanup.wait()
await asyncio.sleep(0) # the owner is now waiting on the monitor
owner_task.cancel()

with pytest.raises(asyncio.CancelledError):
await owner_task
assert monitor_cancelled.is_set()
assert abort_calls == ["sglang-request-id"]


@pytest.mark.asyncio
@pytest.mark.timeout(5)
async def test_cancellation_monitor_keeps_pending_ordered_abort_alive(
Expand Down Expand Up @@ -607,8 +657,9 @@ async def buffered_stream():

@pytest.mark.asyncio
@pytest.mark.timeout(5)
@pytest.mark.parametrize("cancel_during_read", [False, True])
async def test_cancelled_stream_drain_does_not_wait_for_resistant_iterator(
decode_cancellation_case, monkeypatch, caplog
decode_cancellation_case, monkeypatch, caplog, cancel_during_read
):
caplog.set_level(logging.WARNING)
monkeypatch.setattr(
Expand All @@ -627,8 +678,11 @@ async def resistant_stream():
iterator_finished.set()
yield {}

cancellation_task = asyncio.create_task(asyncio.sleep(0))
await cancellation_task
if cancel_during_read:
cancellation_task = asyncio.create_task(asyncio.sleep(0.005))
else:
cancellation_task = asyncio.create_task(asyncio.sleep(0))
await cancellation_task
started = asyncio.get_running_loop().time()
outputs = await _collect(
decode_cancellation_case.handler._stream_until_cancelled(
Expand All @@ -644,6 +698,96 @@ async def resistant_stream():
assert cancellation_seen.is_set()


@pytest.mark.asyncio
@pytest.mark.timeout(5)
async def test_stream_does_not_race_each_chunk_against_cancellation(
decode_cancellation_case, monkeypatch
):
async def no_race(*_args, **_kwargs):
raise AssertionError("chunks must not race cancellation before it fires")

monkeypatch.setattr(
"dynamo.sglang.request_handlers.cancellation.asyncio.wait", no_race
)

async def chunks():
for i in range(3):
await asyncio.sleep(0)
yield {"chunk": i}

cancellation_task = asyncio.create_task(asyncio.Event().wait())
try:
outputs = await _collect(
decode_cancellation_case.handler._stream_until_cancelled(
chunks(), cancellation_task
)
)
finally:
cancellation_task.cancel()
await asyncio.gather(cancellation_task, return_exceptions=True)

assert outputs == [{"chunk": 0}, {"chunk": 1}, {"chunk": 2}]


@pytest.mark.asyncio
@pytest.mark.timeout(5)
async def test_cancellation_during_read_is_bounded_by_drain_deadline(
decode_cancellation_case, monkeypatch, caplog
):
caplog.set_level(logging.WARNING)
monkeypatch.setattr(
"dynamo.sglang.request_handlers.cancellation._CANCELLATION_DRAIN_TIMEOUT_S",
0.01,
)
read_cancelled = asyncio.Event()

async def stalls_after_first_chunk():
yield {"chunk": 0}
try:
await asyncio.Future()
except asyncio.CancelledError:
read_cancelled.set()
raise
yield {"chunk": 1}

cancellation_task = asyncio.create_task(asyncio.sleep(0.01))
consumer = asyncio.create_task(
_collect(
decode_cancellation_case.handler._stream_until_cancelled(
stalls_after_first_chunk(), cancellation_task
)
)
)
outputs = await asyncio.wait_for(consumer, timeout=1)

assert outputs == [{"chunk": 0}]
assert "Timed out draining SGLang stream after cancellation" in caplog.messages
await asyncio.wait_for(read_cancelled.wait(), timeout=1)


@pytest.mark.asyncio
@pytest.mark.timeout(5)
async def test_monitor_failure_during_read_is_raised(decode_cancellation_case):
async def stalled_stream():
await asyncio.Future()
yield {}

async def failing_monitor():
await asyncio.sleep(0.01)
raise EngineShutdown("Engine was shut down during token generation")

cancellation_task = asyncio.create_task(failing_monitor())
with pytest.raises(EngineShutdown, match="shut down during token generation"):
await asyncio.wait_for(
_collect(
decode_cancellation_case.handler._stream_until_cancelled(
stalled_stream(), cancellation_task
)
),
timeout=0.5,
)


@pytest.mark.asyncio
@pytest.mark.timeout(5)
async def test_decode_cancellation_drains_buffered_empty_chunk(
Expand Down
Loading