From 81168f3e90d3842118b41bceb09893aa4cc34472 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Mon, 5 Oct 2026 14:54:12 +0300 Subject: [PATCH 01/11] feat(runtime): end a run the host stopped as stopped A run cancelled because its host asked it to stop was reported as faulted with ERROR_CancelledError, indistinguishable from a crash. A host can now install a stop-requested probe (uipath.runtime.stop). When the run ends in a cancellation, or in an error raised because of one, and the probe says a stop was requested, the context writes the new stopped status with no error, and the result sink receives it like any final result. Without a probe, or when the probe says no, nothing changes. Co-Authored-By: Claude Opus 5.5 (1M context) --- pyproject.toml | 2 +- src/uipath/runtime/context.py | 34 ++++++- src/uipath/runtime/result.py | 1 + src/uipath/runtime/stop.py | 28 ++++++ tests/test_stop.py | 162 ++++++++++++++++++++++++++++++++++ uv.lock | 2 +- 6 files changed, 226 insertions(+), 3 deletions(-) create mode 100644 src/uipath/runtime/stop.py create mode 100644 tests/test_stop.py diff --git a/pyproject.toml b/pyproject.toml index a6db49ad..5cb6c0cf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-runtime" -version = "0.13.6" +version = "0.13.7" description = "Runtime abstractions and interfaces for building agents and automation scripts in the UiPath ecosystem" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/src/uipath/runtime/context.py b/src/uipath/runtime/context.py index cdccf045..9290d942 100644 --- a/src/uipath/runtime/context.py +++ b/src/uipath/runtime/context.py @@ -1,5 +1,6 @@ """Context information passed throughout the runtime execution.""" +import asyncio import json import logging import os @@ -21,6 +22,7 @@ from uipath.runtime.logging._interceptor import UiPathRuntimeLogsInterceptor from uipath.runtime.output_sinks import ResultSink, get_log_handler, get_result_sink from uipath.runtime.result import UiPathRuntimeResult, UiPathRuntimeStatus +from uipath.runtime.stop import StopRequestedProbe, get_stop_requested_probe logger = logging.getLogger(__name__) @@ -127,6 +129,7 @@ class UiPathRuntimeContext(BaseModel): # installed when the context started is the one that receives the result — even if the registry is # changed in between or __exit__ runs on a different event loop. _result_sink: ResultSink | None = PrivateAttr(default=None) + _stop_requested_probe: StopRequestedProbe | None = PrivateAttr(default=None) def _apply_execution_source(self) -> None: """Derive execution_source from the command, if not already set. @@ -247,6 +250,7 @@ def __enter__(self): # the result sink is stashed for __exit__ so the two are read at the same moment (same context). log_handler = get_log_handler() self._result_sink = get_result_sink() + self._stop_requested_probe = get_stop_requested_probe() self.logs_interceptor = UiPathRuntimeLogsInterceptor( min_level=self.logs_min_level, @@ -271,7 +275,10 @@ def __exit__(self, exc_type, exc_val, exc_tb): if self.result is None: self.result = UiPathRuntimeResult() - if exc_type and exc_val: + if exc_type and exc_val and self._stopped_on_request(exc_val): + self.result.status = UiPathRuntimeStatus.STOPPED + self.result.error = None + elif exc_type and exc_val: # Create error info from exception match exc_val: case UiPathFaultedTriggerError(): @@ -327,6 +334,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): if result_sink is not None and self.result.status in ( UiPathRuntimeStatus.SUCCESSFUL, UiPathRuntimeStatus.FAULTED, + UiPathRuntimeStatus.STOPPED, ): try: self._deliver_result(result_sink, output_payload) @@ -377,6 +385,19 @@ def __exit__(self, exc_type, exc_val, exc_tb): if hasattr(self, "logs_interceptor"): self.logs_interceptor.teardown() + def _stopped_on_request(self, exc: BaseException) -> bool: + """Whether the run ended by a cancellation the host asked for.""" + probe = self._stop_requested_probe + if probe is None or not _caused_by_cancellation(exc): + return False + try: + return bool(probe()) + except Exception: + logger.exception( + "Stop-requested probe failed; the run is reported as faulted" + ) + return False + def _deliver_result(self, sink: ResultSink, output_payload: Any) -> None: """Spill the output arguments to a file, then hand the result + that path to the sink.""" args_path = self.resolved_output_arguments_file_path @@ -527,3 +548,14 @@ def from_config( setattr(instance, attr_name, kwargs[attr_name]) return instance + + +def _caused_by_cancellation(exc: BaseException | None) -> bool: + """Whether ``exc`` is a cancellation, or was raised while handling or because of one.""" + seen: set[int] = set() + while exc is not None and id(exc) not in seen: + if isinstance(exc, asyncio.CancelledError): + return True + seen.add(id(exc)) + exc = exc.__cause__ or exc.__context__ + return False diff --git a/src/uipath/runtime/result.py b/src/uipath/runtime/result.py index 66908f12..e692199f 100644 --- a/src/uipath/runtime/result.py +++ b/src/uipath/runtime/result.py @@ -16,6 +16,7 @@ class UiPathRuntimeStatus(str, Enum): SUCCESSFUL = "successful" FAULTED = "faulted" SUSPENDED = "suspended" + STOPPED = "stopped" class UiPathRuntimeResult(UiPathRuntimeEvent): diff --git a/src/uipath/runtime/stop.py b/src/uipath/runtime/stop.py new file mode 100644 index 00000000..6a820eb4 --- /dev/null +++ b/src/uipath/runtime/stop.py @@ -0,0 +1,28 @@ +"""Per-execution slot through which a host says whether it asked the execution to stop. + +Unset, a cancelled execution ends like any other failure. Set, a cancellation the host asked for +ends the execution as stopped. A contextvar, so concurrent jobs in one process each see their own +host's answer. +""" + +from __future__ import annotations + +from contextvars import ContextVar +from typing import Callable + +# () -> whether the host has asked this execution to stop +StopRequestedProbe = Callable[[], bool] + +_stop_requested_probe: ContextVar[StopRequestedProbe | None] = ContextVar( + "uipath_stop_requested_probe", default=None +) + + +def set_stop_requested_probe(probe: StopRequestedProbe | None) -> None: + """Install the probe (``None`` clears).""" + _stop_requested_probe.set(probe) + + +def get_stop_requested_probe() -> StopRequestedProbe | None: + """The installed probe, or None.""" + return _stop_requested_probe.get() diff --git a/tests/test_stop.py b/tests/test_stop.py new file mode 100644 index 00000000..51f328d9 --- /dev/null +++ b/tests/test_stop.py @@ -0,0 +1,162 @@ +"""A run the host asked to stop ends as stopped rather than faulted.""" + +import asyncio +import json +from pathlib import Path +from typing import Any + +import pytest + +from uipath.runtime.context import UiPathRuntimeContext +from uipath.runtime.output_sinks import set_result_sink +from uipath.runtime.result import UiPathRuntimeResult, UiPathRuntimeStatus +from uipath.runtime.stop import get_stop_requested_probe, set_stop_requested_probe + + +class _DummyInterceptor: + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + def setup(self) -> None: + pass + + def teardown(self) -> None: + pass + + +@pytest.fixture(autouse=True) +def _isolate(monkeypatch: pytest.MonkeyPatch) -> Any: + monkeypatch.setattr( + "uipath.runtime.context.UiPathRuntimeLogsInterceptor", _DummyInterceptor + ) + set_stop_requested_probe(None) + set_result_sink(None) + yield + set_stop_requested_probe(None) + set_result_sink(None) + + +def _ctx(tmp_path: Path) -> UiPathRuntimeContext: + return UiPathRuntimeContext( + job_id="job-key", runtime_dir=str(tmp_path / "rt"), result_file="output.json" + ) + + +def _written(ctx: UiPathRuntimeContext) -> dict[str, Any]: + return json.loads(Path(ctx.resolved_result_file_path).read_text()) + + +def _run_cancelled(ctx: UiPathRuntimeContext) -> None: + with pytest.raises(asyncio.CancelledError): + with ctx: + raise asyncio.CancelledError() + + +def test_probe_is_unset_by_default() -> None: + assert get_stop_requested_probe() is None + + +def test_a_cancellation_the_host_asked_for_ends_as_stopped(tmp_path: Path) -> None: + set_stop_requested_probe(lambda: True) + ctx = _ctx(tmp_path) + + _run_cancelled(ctx) + + content = _written(ctx) + assert content["status"] == UiPathRuntimeStatus.STOPPED.value + assert content.get("error") is None + + +def test_a_cancellation_without_a_probe_still_faults(tmp_path: Path) -> None: + ctx = _ctx(tmp_path) + + _run_cancelled(ctx) + + content = _written(ctx) + assert content["status"] == UiPathRuntimeStatus.FAULTED.value + assert content["error"]["code"] == "ERROR_CancelledError" + + +def test_a_cancellation_the_host_did_not_ask_for_faults(tmp_path: Path) -> None: + set_stop_requested_probe(lambda: False) + ctx = _ctx(tmp_path) + + _run_cancelled(ctx) + + assert _written(ctx)["status"] == UiPathRuntimeStatus.FAULTED.value + + +def test_an_error_while_stopping_ends_as_stopped(tmp_path: Path) -> None: + set_stop_requested_probe(lambda: True) + ctx = _ctx(tmp_path) + + with pytest.raises(RuntimeError): + with ctx: + try: + raise asyncio.CancelledError() + except asyncio.CancelledError: + raise RuntimeError("cleanup failed while stopping") from None + + assert _written(ctx)["status"] == UiPathRuntimeStatus.STOPPED.value + + +def test_an_unrelated_error_still_faults_after_a_stop_request(tmp_path: Path) -> None: + set_stop_requested_probe(lambda: True) + ctx = _ctx(tmp_path) + + with pytest.raises(ValueError): + with ctx: + raise ValueError("bad input") + + content = _written(ctx) + assert content["status"] == UiPathRuntimeStatus.FAULTED.value + assert content["error"]["code"] == "ERROR_ValueError" + + +def test_a_run_that_completes_after_a_stop_request_keeps_its_result( + tmp_path: Path, +) -> None: + set_stop_requested_probe(lambda: True) + ctx = _ctx(tmp_path) + + with ctx: + ctx.result = UiPathRuntimeResult(output={"done": True}) + + content = _written(ctx) + assert content["status"] == UiPathRuntimeStatus.SUCCESSFUL.value + assert content["output"] == {"done": True} + + +def test_a_probe_that_raises_reports_the_run_as_faulted(tmp_path: Path) -> None: + def _broken() -> bool: + raise RuntimeError("probe broke") + + set_stop_requested_probe(_broken) + ctx = _ctx(tmp_path) + + _run_cancelled(ctx) + + assert _written(ctx)["status"] == UiPathRuntimeStatus.FAULTED.value + + +def test_the_result_sink_receives_a_stopped_result(tmp_path: Path) -> None: + delivered: list[UiPathRuntimeResult] = [] + set_result_sink(lambda result, _path: delivered.append(result)) + set_stop_requested_probe(lambda: True) + ctx = _ctx(tmp_path) + + _run_cancelled(ctx) + + assert [r.status for r in delivered] == [UiPathRuntimeStatus.STOPPED] + + +def test_the_probe_is_read_when_the_context_starts(tmp_path: Path) -> None: + set_stop_requested_probe(lambda: True) + ctx = _ctx(tmp_path) + + with pytest.raises(asyncio.CancelledError): + with ctx: + set_stop_requested_probe(None) + raise asyncio.CancelledError() + + assert _written(ctx)["status"] == UiPathRuntimeStatus.STOPPED.value diff --git a/uv.lock b/uv.lock index f4a278a1..d5855340 100644 --- a/uv.lock +++ b/uv.lock @@ -1153,7 +1153,7 @@ wheels = [ [[package]] name = "uipath-runtime" -version = "0.13.6" +version = "0.13.7" source = { editable = "." } dependencies = [ { name = "chardet" }, From 5856c178c0a2df97c96c95b8e480d8b8dba591e6 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Mon, 5 Oct 2026 14:58:19 +0300 Subject: [PATCH 02/11] fix(debug): stop a run when the debugger quits while it is going The debug runtime looked at the bridge's terminate signal only while it was waiting: before the first resume, at a breakpoint, or while polling a trigger. A Quit from Studio Web while the agent was running was logged and then ignored, and the run went on to completion. The delegate's stream is now watched for a quit. One that arrives while the delegate is working cancels it where it waits, as a stop would; one that arrives while an event is being handled ends the stream before the next. The delegate is closed either way and the run ends with the result a quit has always produced. A cancellation from anywhere else still propagates. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/uipath/runtime/debug/runtime.py | 67 +++++++++++- tests/test_debugger.py | 163 ++++++++++++++++++++++++++++ 2 files changed, 228 insertions(+), 2 deletions(-) diff --git a/src/uipath/runtime/debug/runtime.py b/src/uipath/runtime/debug/runtime.py index 57ef5ec6..4637533f 100644 --- a/src/uipath/runtime/debug/runtime.py +++ b/src/uipath/runtime/debug/runtime.py @@ -60,6 +60,7 @@ def __init__( if trigger_poll_interval < 0: raise ValueError("trigger_poll_interval must be >= 0") self.trigger_poll_interval = trigger_poll_interval + self._quit_requested = False async def execute( self, @@ -120,6 +121,7 @@ async def _stream_and_debug( """Stream events from inner runtime and handle debug interactions.""" final_result: UiPathRuntimeResult execution_completed = False + self._quit_requested = False # Starting in paused state - wait for breakpoints and resume try: @@ -172,8 +174,8 @@ async def _stream_and_debug( debug_options.breakpoints = self.debug_bridge.get_breakpoints() # Stream events from inner runtime - async for event in self.delegate.stream( - current_input, options=debug_options + async for event in self._until_quit( + self.delegate.stream(current_input, options=debug_options) ): yield event @@ -260,6 +262,61 @@ async def _stream_and_debug( elif isinstance(event, UiPathRuntimeStateEvent): await self.debug_bridge.emit_state_update(event) + if self._quit_requested and not execution_completed: + logger.info("Debug session quit by user during execution") + final_result = UiPathRuntimeResult( + status=UiPathRuntimeStatus.SUCCESSFUL, + ) + yield final_result + execution_completed = True + + async def _until_quit( + self, events: AsyncGenerator[UiPathRuntimeEvent, None] + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: + """Pass the delegate's events through until the debugger quits. + + A quit while the delegate is working cancels it where it waits, as a stop would; one + between events ends the stream before the next. Either way the delegate is closed and + ``_quit_requested`` is set. A cancellation from anywhere else still propagates. + """ + task = asyncio.current_task() + assert task is not None + terminate = asyncio.ensure_future(self.debug_bridge.wait_for_terminate()) + in_delegate = False + cancelled = False + + def on_terminate(done: "asyncio.Future[None]") -> None: + nonlocal cancelled + if in_delegate and _requested(done): + cancelled = True + task.cancel() + + terminate.add_done_callback(on_terminate) + try: + while not _requested(terminate): + in_delegate = True + try: + event = await anext(events) + except StopAsyncIteration: + return + except asyncio.CancelledError: + if cancelled: + cancelled = False + if task.uncancel() == 0: + break + raise + finally: + in_delegate = False + yield event + self._quit_requested = True + finally: + terminate.remove_done_callback(on_terminate) + if cancelled: + # The delegate swallowed the cancellation this sent it. + task.uncancel() + terminate.cancel() + await events.aclose() + def get_resumable_runtime( self, max_depth: int = 10 ) -> UiPathResumableRuntime | None: @@ -358,3 +415,9 @@ async def _wait_with_quit_check(self) -> None: if term_task in done: raise UiPathDebugQuitError("Debugging terminated during polling.") + + +def _requested(terminate: "asyncio.Future[None]") -> bool: + return ( + terminate.done() and not terminate.cancelled() and terminate.exception() is None + ) diff --git a/tests/test_debugger.py b/tests/test_debugger.py index 0c613a16..0c4150cb 100644 --- a/tests/test_debugger.py +++ b/tests/test_debugger.py @@ -27,6 +27,10 @@ from uipath.runtime.schema import UiPathRuntimeSchema +async def _never() -> None: + await asyncio.Event().wait() + + def make_debug_bridge_mock() -> UiPathDebugProtocol: """Create a debug bridge mock with all methods that UiPathDebugRuntime uses. @@ -43,6 +47,8 @@ def make_debug_bridge_mock() -> UiPathDebugProtocol: bridge_mock.emit_breakpoint_hit = AsyncMock() bridge_mock.emit_state_update = AsyncMock() bridge_mock.wait_for_resume = AsyncMock() + # The bridge returns from wait_for_terminate only once the user quits. + bridge_mock.wait_for_terminate = AsyncMock(side_effect=_never) bridge_mock.get_breakpoints = Mock(return_value=["node-1"]) @@ -475,3 +481,160 @@ async def test_debug_runtime_dispose_suppresses_disconnect_errors(): await debug_runtime.dispose() cast(AsyncMock, bridge.disconnect).assert_awaited_once() + + +class _WorkingRuntime: + """A delegate that emits one state event, then works until it is cancelled.""" + + def __init__(self) -> None: + self.cleaned_up = False + self.emitted: list[str] = [] + + async def dispose(self) -> None: + pass + + async def execute( + self, + input: dict[str, Any] | None = None, + options: UiPathExecuteOptions | None = None, + ) -> UiPathRuntimeResult: + raise AssertionError("streaming is used") + + async def stream( + self, + input: dict[str, Any] | None = None, + options: UiPathStreamOptions | None = None, + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: + try: + self.emitted.append("first") + yield UiPathRuntimeStateEvent(node_name="first", payload={}) + await asyncio.sleep(30) + self.emitted.append("second") + yield UiPathRuntimeStateEvent(node_name="second", payload={}) + yield UiPathRuntimeResult(status=UiPathRuntimeStatus.SUCCESSFUL) + finally: + self.cleaned_up = True + + async def get_schema(self) -> UiPathRuntimeSchema: + raise NotImplementedError + + +def _bridge_with_quit() -> tuple[UiPathDebugProtocol, asyncio.Event]: + bridge = make_debug_bridge_mock() + quit_event = asyncio.Event() + cast(Mock, bridge).wait_for_terminate = AsyncMock(side_effect=quit_event.wait) + cast(Mock, bridge.get_breakpoints).return_value = [] + return bridge, quit_event + + +@pytest.mark.asyncio +async def test_debug_runtime_quit_while_running_cancels_the_delegate(): + """A quit that arrives while the delegate works stops it instead of letting it finish.""" + runtime_impl = _WorkingRuntime() + bridge, quit_event = _bridge_with_quit() + debug_runtime = UiPathDebugRuntime(delegate=runtime_impl, debug_bridge=bridge) + + async def quit_soon() -> None: + await asyncio.sleep(0.05) + quit_event.set() + + quitter = asyncio.create_task(quit_soon()) + result = await asyncio.wait_for(debug_runtime.execute({}), timeout=5) + await quitter + + assert result.status == UiPathRuntimeStatus.SUCCESSFUL + assert runtime_impl.emitted == ["first"] + assert runtime_impl.cleaned_up + cast(AsyncMock, bridge.emit_execution_completed).assert_awaited_once_with(result) + + +@pytest.mark.asyncio +async def test_debug_runtime_quit_between_events_ends_before_the_next_one(): + """A quit that arrives while an event is being handled ends the stream before the next.""" + runtime_impl = _WorkingRuntime() + bridge, quit_event = _bridge_with_quit() + + async def quit_on_first_state(_event: Any) -> None: + quit_event.set() + await asyncio.sleep(0) + + cast(AsyncMock, bridge.emit_state_update).side_effect = quit_on_first_state + debug_runtime = UiPathDebugRuntime(delegate=runtime_impl, debug_bridge=bridge) + + result = await asyncio.wait_for(debug_runtime.execute({}), timeout=5) + + assert result.status == UiPathRuntimeStatus.SUCCESSFUL + assert runtime_impl.emitted == ["first"] + assert runtime_impl.cleaned_up + + +@pytest.mark.asyncio +async def test_debug_runtime_cancellation_from_elsewhere_still_propagates(): + """Only a quit is turned into a result; a host's cancellation keeps cancelling.""" + runtime_impl = _WorkingRuntime() + bridge, _quit_event = _bridge_with_quit() + debug_runtime = UiPathDebugRuntime(delegate=runtime_impl, debug_bridge=bridge) + + run = asyncio.create_task(debug_runtime.execute({})) + await asyncio.sleep(0.05) + run.cancel() + + with pytest.raises(asyncio.CancelledError): + await run + assert runtime_impl.cleaned_up + cast(AsyncMock, bridge.emit_execution_completed).assert_not_awaited() + + +class _BreakpointRuntime: + """A delegate that pauses at a breakpoint: its stream ends with the breakpoint result.""" + + async def dispose(self) -> None: + pass + + async def execute( + self, + input: dict[str, Any] | None = None, + options: UiPathExecuteOptions | None = None, + ) -> UiPathRuntimeResult: + raise AssertionError("streaming is used") + + async def stream( + self, + input: dict[str, Any] | None = None, + options: UiPathStreamOptions | None = None, + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: + yield UiPathRuntimeStateEvent(node_name="node-quit", payload={}) + yield UiPathBreakpointResult( + breakpoint_node="node-quit", + breakpoint_type="before", + next_nodes=[], + current_state={}, + ) + + async def get_schema(self) -> UiPathRuntimeSchema: + raise NotImplementedError + + +@pytest.mark.asyncio +async def test_debug_runtime_quit_at_a_breakpoint_yields_one_result(): + """A quit answered at a breakpoint is not reported a second time by the stream watch.""" + bridge, quit_event = _bridge_with_quit() + + async def resume_then_quit() -> None: + if cast(AsyncMock, bridge.wait_for_resume).await_count > 1: + quit_event.set() + raise UiPathDebugQuitError("quit") + + cast(AsyncMock, bridge.wait_for_resume).side_effect = resume_then_quit + debug_runtime = UiPathDebugRuntime( + delegate=_BreakpointRuntime(), debug_bridge=bridge + ) + + results = [ + event + async for event in debug_runtime.stream({}) + if isinstance(event, UiPathRuntimeResult) + and not isinstance(event, UiPathBreakpointResult) + ] + + assert [r.status for r in results] == [UiPathRuntimeStatus.SUCCESSFUL] From 1a8ed92752dabe68701e47e9a1d09807d082bfff Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Tue, 6 Oct 2026 14:35:02 +0300 Subject: [PATCH 03/11] refactor(runtime): detect a stop from the task, and watch for a quit in execute() A stopped run is now told apart from a failure by Task.cancelling() on the task that entered the context: a cancel() someone called keeps it above zero through cleanup, and a stray CancelledError leaves it at zero. This replaces the host-installed stop-requested probe and the walk of the exception chain, so uipath.runtime.stop goes away and hosts install nothing. The debug quit is watched in execute(), which runs the stream in its own task and races it against wait_for_terminate(). A quit cancels that task instead of the caller's, so no uncancel() bookkeeping or in-delegate tracking is needed, and the execute() fallback for a delegate that cannot stream is covered too. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_011be41L1VE33oixHNnJRPhw --- src/uipath/runtime/context.py | 34 +++------ src/uipath/runtime/debug/runtime.py | 104 ++++++++++----------------- src/uipath/runtime/stop.py | 28 -------- tests/test_debugger.py | 43 +++++++++++ tests/test_stop.py | 107 +++++++++++----------------- 5 files changed, 130 insertions(+), 186 deletions(-) delete mode 100644 src/uipath/runtime/stop.py diff --git a/src/uipath/runtime/context.py b/src/uipath/runtime/context.py index 9290d942..58e02cb1 100644 --- a/src/uipath/runtime/context.py +++ b/src/uipath/runtime/context.py @@ -22,7 +22,6 @@ from uipath.runtime.logging._interceptor import UiPathRuntimeLogsInterceptor from uipath.runtime.output_sinks import ResultSink, get_log_handler, get_result_sink from uipath.runtime.result import UiPathRuntimeResult, UiPathRuntimeStatus -from uipath.runtime.stop import StopRequestedProbe, get_stop_requested_probe logger = logging.getLogger(__name__) @@ -129,7 +128,6 @@ class UiPathRuntimeContext(BaseModel): # installed when the context started is the one that receives the result — even if the registry is # changed in between or __exit__ runs on a different event loop. _result_sink: ResultSink | None = PrivateAttr(default=None) - _stop_requested_probe: StopRequestedProbe | None = PrivateAttr(default=None) def _apply_execution_source(self) -> None: """Derive execution_source from the command, if not already set. @@ -250,7 +248,6 @@ def __enter__(self): # the result sink is stashed for __exit__ so the two are read at the same moment (same context). log_handler = get_log_handler() self._result_sink = get_result_sink() - self._stop_requested_probe = get_stop_requested_probe() self.logs_interceptor = UiPathRuntimeLogsInterceptor( min_level=self.logs_min_level, @@ -275,7 +272,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): if self.result is None: self.result = UiPathRuntimeResult() - if exc_type and exc_val and self._stopped_on_request(exc_val): + if exc_type and exc_val and _task_is_being_cancelled(): self.result.status = UiPathRuntimeStatus.STOPPED self.result.error = None elif exc_type and exc_val: @@ -385,19 +382,6 @@ def __exit__(self, exc_type, exc_val, exc_tb): if hasattr(self, "logs_interceptor"): self.logs_interceptor.teardown() - def _stopped_on_request(self, exc: BaseException) -> bool: - """Whether the run ended by a cancellation the host asked for.""" - probe = self._stop_requested_probe - if probe is None or not _caused_by_cancellation(exc): - return False - try: - return bool(probe()) - except Exception: - logger.exception( - "Stop-requested probe failed; the run is reported as faulted" - ) - return False - def _deliver_result(self, sink: ResultSink, output_payload: Any) -> None: """Spill the output arguments to a file, then hand the result + that path to the sink.""" args_path = self.resolved_output_arguments_file_path @@ -550,12 +534,10 @@ def from_config( return instance -def _caused_by_cancellation(exc: BaseException | None) -> bool: - """Whether ``exc`` is a cancellation, or was raised while handling or because of one.""" - seen: set[int] = set() - while exc is not None and id(exc) not in seen: - if isinstance(exc, asyncio.CancelledError): - return True - seen.add(id(exc)) - exc = exc.__cause__ or exc.__context__ - return False +def _task_is_being_cancelled() -> bool: + """Whether someone called ``cancel()`` on the running task, as opposed to a stray CancelledError.""" + try: + task = asyncio.current_task() + except RuntimeError: + return False + return task is not None and task.cancelling() > 0 diff --git a/src/uipath/runtime/debug/runtime.py b/src/uipath/runtime/debug/runtime.py index 4637533f..b2308e05 100644 --- a/src/uipath/runtime/debug/runtime.py +++ b/src/uipath/runtime/debug/runtime.py @@ -60,16 +60,48 @@ def __init__( if trigger_poll_interval < 0: raise ValueError("trigger_poll_interval must be >= 0") self.trigger_poll_interval = trigger_poll_interval - self._quit_requested = False async def execute( self, input: dict[str, Any] | None = None, options: UiPathExecuteOptions | None = None, ) -> UiPathRuntimeResult: - """Execute the workflow with debug support.""" + """Execute the workflow with debug support; a quit while it runs stops it.""" + run = asyncio.ensure_future( + self._run(input, cast(UiPathStreamOptions, options)) + ) + terminate = asyncio.ensure_future(self.debug_bridge.wait_for_terminate()) + try: + done, _ = await asyncio.wait( + {run, terminate}, return_when=asyncio.FIRST_COMPLETED + ) + if run not in done and not _quit_requested(terminate): + done, _ = await asyncio.wait({run}) + finally: + terminate.cancel() + if not run.done(): + run.cancel() + await asyncio.wait({run}) + + if run in done: + return run.result() + + if not run.cancelled() and run.exception(): + logger.warning( + "Delegate failed while stopping on quit", exc_info=run.exception() + ) + logger.info("Debug session quit by user during execution") + result = UiPathRuntimeResult(status=UiPathRuntimeStatus.SUCCESSFUL) + await self.debug_bridge.emit_execution_completed(result) + return result + + async def _run( + self, + input: dict[str, Any] | None, + options: UiPathStreamOptions | None, + ) -> UiPathRuntimeResult: final_result = None - async for event in self.stream(input, cast(UiPathStreamOptions, options)): + async for event in self.stream(input, options): if isinstance(event, UiPathRuntimeResult): final_result = event @@ -121,7 +153,6 @@ async def _stream_and_debug( """Stream events from inner runtime and handle debug interactions.""" final_result: UiPathRuntimeResult execution_completed = False - self._quit_requested = False # Starting in paused state - wait for breakpoints and resume try: @@ -174,8 +205,8 @@ async def _stream_and_debug( debug_options.breakpoints = self.debug_bridge.get_breakpoints() # Stream events from inner runtime - async for event in self._until_quit( - self.delegate.stream(current_input, options=debug_options) + async for event in self.delegate.stream( + current_input, options=debug_options ): yield event @@ -262,61 +293,6 @@ async def _stream_and_debug( elif isinstance(event, UiPathRuntimeStateEvent): await self.debug_bridge.emit_state_update(event) - if self._quit_requested and not execution_completed: - logger.info("Debug session quit by user during execution") - final_result = UiPathRuntimeResult( - status=UiPathRuntimeStatus.SUCCESSFUL, - ) - yield final_result - execution_completed = True - - async def _until_quit( - self, events: AsyncGenerator[UiPathRuntimeEvent, None] - ) -> AsyncGenerator[UiPathRuntimeEvent, None]: - """Pass the delegate's events through until the debugger quits. - - A quit while the delegate is working cancels it where it waits, as a stop would; one - between events ends the stream before the next. Either way the delegate is closed and - ``_quit_requested`` is set. A cancellation from anywhere else still propagates. - """ - task = asyncio.current_task() - assert task is not None - terminate = asyncio.ensure_future(self.debug_bridge.wait_for_terminate()) - in_delegate = False - cancelled = False - - def on_terminate(done: "asyncio.Future[None]") -> None: - nonlocal cancelled - if in_delegate and _requested(done): - cancelled = True - task.cancel() - - terminate.add_done_callback(on_terminate) - try: - while not _requested(terminate): - in_delegate = True - try: - event = await anext(events) - except StopAsyncIteration: - return - except asyncio.CancelledError: - if cancelled: - cancelled = False - if task.uncancel() == 0: - break - raise - finally: - in_delegate = False - yield event - self._quit_requested = True - finally: - terminate.remove_done_callback(on_terminate) - if cancelled: - # The delegate swallowed the cancellation this sent it. - task.uncancel() - terminate.cancel() - await events.aclose() - def get_resumable_runtime( self, max_depth: int = 10 ) -> UiPathResumableRuntime | None: @@ -417,7 +393,5 @@ async def _wait_with_quit_check(self) -> None: raise UiPathDebugQuitError("Debugging terminated during polling.") -def _requested(terminate: "asyncio.Future[None]") -> bool: - return ( - terminate.done() and not terminate.cancelled() and terminate.exception() is None - ) +def _quit_requested(terminate: "asyncio.Future[None]") -> bool: + return not terminate.cancelled() and terminate.exception() is None diff --git a/src/uipath/runtime/stop.py b/src/uipath/runtime/stop.py deleted file mode 100644 index 6a820eb4..00000000 --- a/src/uipath/runtime/stop.py +++ /dev/null @@ -1,28 +0,0 @@ -"""Per-execution slot through which a host says whether it asked the execution to stop. - -Unset, a cancelled execution ends like any other failure. Set, a cancellation the host asked for -ends the execution as stopped. A contextvar, so concurrent jobs in one process each see their own -host's answer. -""" - -from __future__ import annotations - -from contextvars import ContextVar -from typing import Callable - -# () -> whether the host has asked this execution to stop -StopRequestedProbe = Callable[[], bool] - -_stop_requested_probe: ContextVar[StopRequestedProbe | None] = ContextVar( - "uipath_stop_requested_probe", default=None -) - - -def set_stop_requested_probe(probe: StopRequestedProbe | None) -> None: - """Install the probe (``None`` clears).""" - _stop_requested_probe.set(probe) - - -def get_stop_requested_probe() -> StopRequestedProbe | None: - """The installed probe, or None.""" - return _stop_requested_probe.get() diff --git a/tests/test_debugger.py b/tests/test_debugger.py index 0c4150cb..a88689fb 100644 --- a/tests/test_debugger.py +++ b/tests/test_debugger.py @@ -638,3 +638,46 @@ async def resume_then_quit() -> None: ] assert [r.status for r in results] == [UiPathRuntimeStatus.SUCCESSFUL] + + +class _NonStreamingWorkingRuntime(_WorkingRuntime): + """A delegate without streaming that works until it is cancelled.""" + + async def execute( + self, + input: dict[str, Any] | None = None, + options: UiPathExecuteOptions | None = None, + ) -> UiPathRuntimeResult: + try: + await asyncio.sleep(30) + return UiPathRuntimeResult(status=UiPathRuntimeStatus.FAULTED) + finally: + self.cleaned_up = True + + async def stream( + self, + input: dict[str, Any] | None = None, + options: UiPathStreamOptions | None = None, + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: + raise UiPathStreamNotSupportedError("no streaming") + yield + + +@pytest.mark.asyncio +async def test_debug_runtime_quit_stops_a_delegate_that_cannot_stream(): + """The quit also reaches a delegate run through the execute() fallback.""" + runtime_impl = _NonStreamingWorkingRuntime() + bridge, quit_event = _bridge_with_quit() + debug_runtime = UiPathDebugRuntime(delegate=runtime_impl, debug_bridge=bridge) + + async def quit_soon() -> None: + await asyncio.sleep(0.05) + quit_event.set() + + quitter = asyncio.create_task(quit_soon()) + result = await asyncio.wait_for(debug_runtime.execute({}), timeout=5) + await quitter + + assert result.status == UiPathRuntimeStatus.SUCCESSFUL + assert runtime_impl.cleaned_up + cast(AsyncMock, bridge.emit_execution_completed).assert_awaited_once_with(result) diff --git a/tests/test_stop.py b/tests/test_stop.py index 51f328d9..43b530ee 100644 --- a/tests/test_stop.py +++ b/tests/test_stop.py @@ -1,4 +1,4 @@ -"""A run the host asked to stop ends as stopped rather than faulted.""" +"""A run whose task is cancelled ends as stopped rather than faulted.""" import asyncio import json @@ -10,7 +10,6 @@ from uipath.runtime.context import UiPathRuntimeContext from uipath.runtime.output_sinks import set_result_sink from uipath.runtime.result import UiPathRuntimeResult, UiPathRuntimeStatus -from uipath.runtime.stop import get_stop_requested_probe, set_stop_requested_probe class _DummyInterceptor: @@ -29,10 +28,8 @@ def _isolate(monkeypatch: pytest.MonkeyPatch) -> Any: monkeypatch.setattr( "uipath.runtime.context.UiPathRuntimeLogsInterceptor", _DummyInterceptor ) - set_stop_requested_probe(None) set_result_sink(None) yield - set_stop_requested_probe(None) set_result_sink(None) @@ -46,62 +43,72 @@ def _written(ctx: UiPathRuntimeContext) -> dict[str, Any]: return json.loads(Path(ctx.resolved_result_file_path).read_text()) -def _run_cancelled(ctx: UiPathRuntimeContext) -> None: - with pytest.raises(asyncio.CancelledError): - with ctx: - raise asyncio.CancelledError() - - -def test_probe_is_unset_by_default() -> None: - assert get_stop_requested_probe() is None +async def _cancel_while_running(body: Any) -> None: + task = asyncio.create_task(body()) + await asyncio.sleep(0.01) + task.cancel() + await asyncio.wait({task}) -def test_a_cancellation_the_host_asked_for_ends_as_stopped(tmp_path: Path) -> None: - set_stop_requested_probe(lambda: True) +@pytest.mark.asyncio +async def test_a_cancelled_run_ends_as_stopped(tmp_path: Path) -> None: ctx = _ctx(tmp_path) - _run_cancelled(ctx) + async def body() -> None: + with ctx: + await asyncio.sleep(10) + + await _cancel_while_running(body) content = _written(ctx) assert content["status"] == UiPathRuntimeStatus.STOPPED.value assert content.get("error") is None -def test_a_cancellation_without_a_probe_still_faults(tmp_path: Path) -> None: +@pytest.mark.asyncio +async def test_a_stray_cancelled_error_still_faults(tmp_path: Path) -> None: ctx = _ctx(tmp_path) - _run_cancelled(ctx) + with pytest.raises(asyncio.CancelledError): + with ctx: + child = asyncio.ensure_future(asyncio.sleep(10)) + await asyncio.sleep(0) + child.cancel() + await child content = _written(ctx) assert content["status"] == UiPathRuntimeStatus.FAULTED.value assert content["error"]["code"] == "ERROR_CancelledError" -def test_a_cancellation_the_host_did_not_ask_for_faults(tmp_path: Path) -> None: - set_stop_requested_probe(lambda: False) +def test_a_cancelled_error_outside_an_event_loop_faults(tmp_path: Path) -> None: ctx = _ctx(tmp_path) - _run_cancelled(ctx) + with pytest.raises(asyncio.CancelledError): + with ctx: + raise asyncio.CancelledError() assert _written(ctx)["status"] == UiPathRuntimeStatus.FAULTED.value -def test_an_error_while_stopping_ends_as_stopped(tmp_path: Path) -> None: - set_stop_requested_probe(lambda: True) +@pytest.mark.asyncio +async def test_an_error_while_stopping_ends_as_stopped(tmp_path: Path) -> None: ctx = _ctx(tmp_path) - with pytest.raises(RuntimeError): + async def body() -> None: with ctx: try: - raise asyncio.CancelledError() + await asyncio.sleep(10) except asyncio.CancelledError: raise RuntimeError("cleanup failed while stopping") from None + await _cancel_while_running(body) + assert _written(ctx)["status"] == UiPathRuntimeStatus.STOPPED.value -def test_an_unrelated_error_still_faults_after_a_stop_request(tmp_path: Path) -> None: - set_stop_requested_probe(lambda: True) +@pytest.mark.asyncio +async def test_an_error_in_a_run_nobody_cancelled_faults(tmp_path: Path) -> None: ctx = _ctx(tmp_path) with pytest.raises(ValueError): @@ -113,50 +120,16 @@ def test_an_unrelated_error_still_faults_after_a_stop_request(tmp_path: Path) -> assert content["error"]["code"] == "ERROR_ValueError" -def test_a_run_that_completes_after_a_stop_request_keeps_its_result( - tmp_path: Path, -) -> None: - set_stop_requested_probe(lambda: True) - ctx = _ctx(tmp_path) - - with ctx: - ctx.result = UiPathRuntimeResult(output={"done": True}) - - content = _written(ctx) - assert content["status"] == UiPathRuntimeStatus.SUCCESSFUL.value - assert content["output"] == {"done": True} - - -def test_a_probe_that_raises_reports_the_run_as_faulted(tmp_path: Path) -> None: - def _broken() -> bool: - raise RuntimeError("probe broke") - - set_stop_requested_probe(_broken) - ctx = _ctx(tmp_path) - - _run_cancelled(ctx) - - assert _written(ctx)["status"] == UiPathRuntimeStatus.FAULTED.value - - -def test_the_result_sink_receives_a_stopped_result(tmp_path: Path) -> None: +@pytest.mark.asyncio +async def test_the_result_sink_receives_a_stopped_result(tmp_path: Path) -> None: delivered: list[UiPathRuntimeResult] = [] set_result_sink(lambda result, _path: delivered.append(result)) - set_stop_requested_probe(lambda: True) - ctx = _ctx(tmp_path) - - _run_cancelled(ctx) - - assert [r.status for r in delivered] == [UiPathRuntimeStatus.STOPPED] - - -def test_the_probe_is_read_when_the_context_starts(tmp_path: Path) -> None: - set_stop_requested_probe(lambda: True) ctx = _ctx(tmp_path) - with pytest.raises(asyncio.CancelledError): + async def body() -> None: with ctx: - set_stop_requested_probe(None) - raise asyncio.CancelledError() + await asyncio.sleep(10) - assert _written(ctx)["status"] == UiPathRuntimeStatus.STOPPED.value + await _cancel_while_running(body) + + assert [r.status for r in delivered] == [UiPathRuntimeStatus.STOPPED] From a570087907a9472cc568af8bcb1ea7de6491f03b Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Tue, 24 Nov 2026 17:24:36 +0200 Subject: [PATCH 04/11] fix(runtime): don't take a TaskGroup's own cancellation for a stop Before Python 3.13, a TaskGroup whose child fails after the group's body has ended cancels the parent task and never takes that back, so the task still reads cancelling() == 1 when the group's ExceptionGroup reaches the context. The context took that for a stop, wrote stopped and dropped the error. A run now ends as stopped only when its task is being cancelled and the exception is the CancelledError, or was raised while handling one or because of one. For an exception group, every error in it must be. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- src/uipath/runtime/context.py | 29 +++++++++++++++++++++- tests/test_stop.py | 46 +++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/src/uipath/runtime/context.py b/src/uipath/runtime/context.py index 58e02cb1..81d13fa6 100644 --- a/src/uipath/runtime/context.py +++ b/src/uipath/runtime/context.py @@ -272,7 +272,12 @@ def __exit__(self, exc_type, exc_val, exc_tb): if self.result is None: self.result = UiPathRuntimeResult() - if exc_type and exc_val and _task_is_being_cancelled(): + if ( + exc_type + and exc_val + and _task_is_being_cancelled() + and _raised_by_a_cancellation(exc_val) + ): self.result.status = UiPathRuntimeStatus.STOPPED self.result.error = None elif exc_type and exc_val: @@ -541,3 +546,25 @@ def _task_is_being_cancelled() -> bool: except RuntimeError: return False return task is not None and task.cancelling() > 0 + + +def _raised_by_a_cancellation( + exc: BaseException, _seen: frozenset[int] = frozenset() +) -> bool: + """Whether ``exc`` is a CancelledError, or was raised while handling one or because of one. + + ``cancelling()`` alone is not enough: before Python 3.13, a TaskGroup whose child fails + after the group's body has ended cancels the parent task and never takes it back. + """ + if id(exc) in _seen: + return False + seen = _seen | {id(exc)} + if isinstance(exc, asyncio.CancelledError): + return True + if isinstance(exc, BaseExceptionGroup): + return all(_raised_by_a_cancellation(e, seen) for e in exc.exceptions) + return any( + _raised_by_a_cancellation(e, seen) + for e in (exc.__cause__, exc.__context__) + if e is not None + ) diff --git a/tests/test_stop.py b/tests/test_stop.py index 43b530ee..d4444d2b 100644 --- a/tests/test_stop.py +++ b/tests/test_stop.py @@ -120,6 +120,52 @@ async def test_an_error_in_a_run_nobody_cancelled_faults(tmp_path: Path) -> None assert content["error"]["code"] == "ERROR_ValueError" +@pytest.mark.asyncio +async def test_a_task_group_whose_child_fails_after_its_body_faults( + tmp_path: Path, +) -> None: + ctx = _ctx(tmp_path) + + async def fail_soon() -> None: + await asyncio.sleep(0.01) + raise ValueError("child failed") + + async def body() -> None: + with ctx: + async with asyncio.TaskGroup() as group: + group.create_task(fail_soon()) + + with pytest.raises(ExceptionGroup): + await asyncio.create_task(body()) + + content = _written(ctx) + assert content["status"] == UiPathRuntimeStatus.FAULTED.value + assert content["error"]["code"] == "ERROR_ExceptionGroup" + + +@pytest.mark.asyncio +async def test_a_task_group_stopped_while_its_child_cleans_up_ends_as_stopped( + tmp_path: Path, +) -> None: + ctx = _ctx(tmp_path) + + async def fail_on_cancel() -> None: + try: + await asyncio.sleep(10) + except asyncio.CancelledError: + raise RuntimeError("cleanup failed while stopping") from None + + async def body() -> None: + with ctx: + async with asyncio.TaskGroup() as group: + group.create_task(fail_on_cancel()) + await asyncio.sleep(10) + + await _cancel_while_running(body) + + assert _written(ctx)["status"] == UiPathRuntimeStatus.STOPPED.value + + @pytest.mark.asyncio async def test_the_result_sink_receives_a_stopped_result(tmp_path: Path) -> None: delivered: list[UiPathRuntimeResult] = [] From ab38d4e1b882892ef23d93a82fb7bb87de3936ae Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Tue, 24 Nov 2026 17:24:38 +0200 Subject: [PATCH 05/11] fix(debug): close the delegate's stream before reporting a quit A quit that arrived while the debug runtime awaited a bridge call between events, such as a state update, left the delegate's stream suspended at its yield. Nothing closed it, so its cleanup ran later from the event loop's finalizer, after execute() had reported the run as completed. Every stream the debug runtime iterates is now closed when it stops iterating, so cancelling the run closes and awaits the delegate's stream before execute() reports the quit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- src/uipath/runtime/debug/runtime.py | 185 +++++++++++++++------------- tests/test_debugger.py | 46 +++++++ 2 files changed, 143 insertions(+), 88 deletions(-) diff --git a/src/uipath/runtime/debug/runtime.py b/src/uipath/runtime/debug/runtime.py index b2308e05..e8f27b81 100644 --- a/src/uipath/runtime/debug/runtime.py +++ b/src/uipath/runtime/debug/runtime.py @@ -2,6 +2,7 @@ import asyncio import logging +from contextlib import aclosing from typing import Any, AsyncGenerator, cast from uipath.core.errors import UiPathPendingTriggerError @@ -101,9 +102,10 @@ async def _run( options: UiPathStreamOptions | None, ) -> UiPathRuntimeResult: final_result = None - async for event in self.stream(input, options): - if isinstance(event, UiPathRuntimeResult): - final_result = event + async with aclosing(self.stream(input, options)) as events: + async for event in events: + if isinstance(event, UiPathRuntimeResult): + final_result = event return ( final_result @@ -125,10 +127,13 @@ async def stream( # Try to stream events from inner runtime try: - async for event in self._stream_and_debug(input, options=options): - yield event - if isinstance(event, UiPathRuntimeResult): - result = event + async with aclosing( + self._stream_and_debug(input, options=options) + ) as events: + async for event in events: + yield event + if isinstance(event, UiPathRuntimeResult): + result = event except UiPathStreamNotSupportedError: # Fallback to regular execute if streaming not supported logger.debug( @@ -178,14 +183,17 @@ async def _stream_and_debug( except Exception as e: logger.warning(f"Error disconnecting debug bridge: {e}") - async for event in self.delegate.stream( - input, - options=UiPathStreamOptions( - resume=options.resume if options else False, - breakpoints=None, - ), - ): - yield event + async with aclosing( + self.delegate.stream( + input, + options=UiPathStreamOptions( + resume=options.resume if options else False, + breakpoints=None, + ), + ) + ) as events: + async for event in events: + yield event return except UiPathDebugQuitError: logger.info("Debug session quit by user before execution started") @@ -205,93 +213,94 @@ async def _stream_and_debug( debug_options.breakpoints = self.debug_bridge.get_breakpoints() # Stream events from inner runtime - async for event in self.delegate.stream( - current_input, options=debug_options - ): - yield event + async with aclosing( + self.delegate.stream(current_input, options=debug_options) + ) as events: + async for event in events: + yield event - # Handle final result - if isinstance(event, UiPathRuntimeResult): - final_result = event + # Handle final result + if isinstance(event, UiPathRuntimeResult): + final_result = event - # Check if it's a breakpoint result - if isinstance(event, UiPathBreakpointResult): - try: - # Hit a breakpoint - wait for resume and continue - await self.debug_bridge.emit_breakpoint_hit(event) - await self.debug_bridge.wait_for_resume() - - # Tell inner runtime we're resuming - debug_options.resume = True - current_input = ( - None # Resume with no new input (very important) - ) - - except UiPathDebugQuitError: - final_result = UiPathRuntimeResult( - status=UiPathRuntimeStatus.SUCCESSFUL, - ) - yield final_result - execution_completed = True - else: - # Normal completion or suspension with dynamic interrupt - - # Check if this is a suspended execution that needs polling - if ( - (resumable_runtime := self.get_resumable_runtime()) - and self.trigger_poll_interval > 0 - and final_result.status == UiPathRuntimeStatus.SUSPENDED - and final_result.trigger - ): - await self.debug_bridge.emit_execution_suspended( - final_result - ) - - interrupt_id = final_result.trigger.interrupt_id - assert interrupt_id is not None - - resume_data: dict[str, Any] | None = None + # Check if it's a breakpoint result + if isinstance(event, UiPathBreakpointResult): try: - trigger_data: dict[str, Any] | None = None - if final_result.trigger.trigger_type in ( - UiPathResumeTriggerType.API, - UiPathResumeTriggerType.INBOX, - UiPathResumeTriggerType.TIMER, - ): - trigger_data = ( - await self.debug_bridge.wait_for_resume() - ) - else: - trigger_data = await self._poll_trigger( - final_result.trigger, - resumable_runtime.trigger_manager, - ) - resume_data = {interrupt_id: trigger_data} + # Hit a breakpoint - wait for resume and continue + await self.debug_bridge.emit_breakpoint_hit(event) + await self.debug_bridge.wait_for_resume() + + # Tell inner runtime we're resuming + debug_options.resume = True + current_input = ( + None # Resume with no new input (very important) + ) + except UiPathDebugQuitError: final_result = UiPathRuntimeResult( status=UiPathRuntimeStatus.SUCCESSFUL, ) yield final_result execution_completed = True - - if resume_data is not None: - await self.debug_bridge.emit_execution_resumed( - resume_data + else: + # Normal completion or suspension with dynamic interrupt + + # Check if this is a suspended execution that needs polling + if ( + (resumable_runtime := self.get_resumable_runtime()) + and self.trigger_poll_interval > 0 + and final_result.status == UiPathRuntimeStatus.SUSPENDED + and final_result.trigger + ): + await self.debug_bridge.emit_execution_suspended( + final_result ) - # Continue with resumed execution - current_input = resume_data - debug_options.resume = True - # Don't mark as completed - continue the loop + interrupt_id = final_result.trigger.interrupt_id + assert interrupt_id is not None + + resume_data: dict[str, Any] | None = None + try: + trigger_data: dict[str, Any] | None = None + if final_result.trigger.trigger_type in ( + UiPathResumeTriggerType.API, + UiPathResumeTriggerType.INBOX, + UiPathResumeTriggerType.TIMER, + ): + trigger_data = ( + await self.debug_bridge.wait_for_resume() + ) + else: + trigger_data = await self._poll_trigger( + final_result.trigger, + resumable_runtime.trigger_manager, + ) + resume_data = {interrupt_id: trigger_data} + except UiPathDebugQuitError: + final_result = UiPathRuntimeResult( + status=UiPathRuntimeStatus.SUCCESSFUL, + ) + yield final_result + execution_completed = True + + if resume_data is not None: + await self.debug_bridge.emit_execution_resumed( + resume_data + ) + + # Continue with resumed execution + current_input = resume_data + debug_options.resume = True + # Don't mark as completed - continue the loop + else: + execution_completed = True else: + # Normal completion - mark as done execution_completed = True - else: - # Normal completion - mark as done - execution_completed = True - # Handle state update events - send to debug bridge - elif isinstance(event, UiPathRuntimeStateEvent): - await self.debug_bridge.emit_state_update(event) + # Handle state update events - send to debug bridge + elif isinstance(event, UiPathRuntimeStateEvent): + await self.debug_bridge.emit_state_update(event) def get_resumable_runtime( self, max_depth: int = 10 diff --git a/tests/test_debugger.py b/tests/test_debugger.py index a88689fb..4f28be80 100644 --- a/tests/test_debugger.py +++ b/tests/test_debugger.py @@ -585,6 +585,52 @@ async def test_debug_runtime_cancellation_from_elsewhere_still_propagates(): cast(AsyncMock, bridge.emit_execution_completed).assert_not_awaited() +class _SlowCleanupRuntime(_WorkingRuntime): + """A delegate whose cleanup awaits, so it is done only once that await returns.""" + + def __init__(self) -> None: + super().__init__() + self.cleanup_started = asyncio.Event() + + async def stream( + self, + input: dict[str, Any] | None = None, + options: UiPathStreamOptions | None = None, + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: + try: + self.emitted.append("first") + yield UiPathRuntimeStateEvent(node_name="first", payload={}) + await asyncio.sleep(30) + yield UiPathRuntimeResult(status=UiPathRuntimeStatus.SUCCESSFUL) + finally: + self.cleanup_started.set() + await asyncio.sleep(0.1) + self.cleaned_up = True + + +@pytest.mark.asyncio +async def test_debug_runtime_quit_during_a_state_send_reports_after_the_delegate_cleans_up(): + """A quit while a state update is being sent closes the delegate before completing.""" + runtime_impl = _SlowCleanupRuntime() + bridge, quit_event = _bridge_with_quit() + + async def quit_during_send(_event: Any) -> None: + quit_event.set() + await asyncio.sleep(30) + + cleaned_up_at_completion: list[bool] = [] + cast(AsyncMock, bridge.emit_state_update).side_effect = quit_during_send + cast(AsyncMock, bridge.emit_execution_completed).side_effect = ( + lambda _result: cleaned_up_at_completion.append(runtime_impl.cleaned_up) + ) + debug_runtime = UiPathDebugRuntime(delegate=runtime_impl, debug_bridge=bridge) + + result = await asyncio.wait_for(debug_runtime.execute({}), timeout=5) + + assert result.status == UiPathRuntimeStatus.SUCCESSFUL + assert cleaned_up_at_completion == [True] + + class _BreakpointRuntime: """A delegate that pauses at a breakpoint: its stream ends with the breakpoint result.""" From 5804547df75afca693ba4933ba2c090bd57da32f Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Tue, 24 Nov 2026 17:24:38 +0200 Subject: [PATCH 06/11] fix(debug): finish stopping on a quit even if the caller is cancelled meanwhile A host cancellation while execute() waited for the quit's cleanup made it raise at once, while the run's task was still closing the delegate. It now waits for that task through any cancellation and then re-raises the cancellation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- src/uipath/runtime/debug/runtime.py | 14 +++++++++++++- tests/test_debugger.py | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/uipath/runtime/debug/runtime.py b/src/uipath/runtime/debug/runtime.py index e8f27b81..f9c786ed 100644 --- a/src/uipath/runtime/debug/runtime.py +++ b/src/uipath/runtime/debug/runtime.py @@ -82,7 +82,7 @@ async def execute( terminate.cancel() if not run.done(): run.cancel() - await asyncio.wait({run}) + await _wait_out(run) if run in done: return run.result() @@ -402,5 +402,17 @@ async def _wait_with_quit_check(self) -> None: raise UiPathDebugQuitError("Debugging terminated during polling.") +async def _wait_out(task: "asyncio.Future[Any]") -> None: + """Wait until ``task`` is done, through cancellations of the caller, then re-raise the last.""" + cancelled: asyncio.CancelledError | None = None + while not task.done(): + try: + await asyncio.wait({task}) + except asyncio.CancelledError as e: + cancelled = e + if cancelled is not None: + raise cancelled + + def _quit_requested(terminate: "asyncio.Future[None]") -> bool: return not terminate.cancelled() and terminate.exception() is None diff --git a/tests/test_debugger.py b/tests/test_debugger.py index 4f28be80..53adcb3b 100644 --- a/tests/test_debugger.py +++ b/tests/test_debugger.py @@ -631,6 +631,25 @@ async def quit_during_send(_event: Any) -> None: assert cleaned_up_at_completion == [True] +@pytest.mark.asyncio +async def test_debug_runtime_cancelled_while_stopping_on_quit_waits_for_the_delegate(): + """A host cancellation during the quit's cleanup propagates once the delegate is done.""" + runtime_impl = _SlowCleanupRuntime() + bridge, quit_event = _bridge_with_quit() + debug_runtime = UiPathDebugRuntime(delegate=runtime_impl, debug_bridge=bridge) + + run = asyncio.create_task(debug_runtime.execute({})) + await asyncio.sleep(0.05) + quit_event.set() + await asyncio.wait_for(runtime_impl.cleanup_started.wait(), timeout=5) + run.cancel() + + with pytest.raises(asyncio.CancelledError): + await run + assert runtime_impl.cleaned_up + cast(AsyncMock, bridge.emit_execution_completed).assert_not_awaited() + + class _BreakpointRuntime: """A delegate that pauses at a breakpoint: its stream ends with the breakpoint result.""" From 6a8220d8bc6f6d0be3badc6ec46f49ec975ceaab Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Tue, 24 Nov 2026 17:24:50 +0200 Subject: [PATCH 07/11] ci: pass GATEWAY_FOLDER_KEY to the gateway-and-direct-models testcase The testcase from uipath-langchain-python now checks the LLM Gateway's spans and needs the key of the folder the Gateway publishes them to. It fails its setup without it. Pass it the way uipath-python's copy of this workflow does, from the _GATEWAY_FOLDER_KEY secrets. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- .github/workflows/test-uipath-langchain.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/test-uipath-langchain.yml b/.github/workflows/test-uipath-langchain.yml index 057ca7e6..1c350747 100644 --- a/.github/workflows/test-uipath-langchain.yml +++ b/.github/workflows/test-uipath-langchain.yml @@ -181,6 +181,8 @@ jobs: CLIENT_SECRET: ${{ matrix.environment == 'alpha' && secrets.ALPHA_TEST_CLIENT_SECRET || matrix.environment == 'staging' && secrets.STAGING_TEST_CLIENT_SECRET || matrix.environment == 'cloud' && secrets.CLOUD_TEST_CLIENT_SECRET }} BASE_URL: ${{ matrix.environment == 'alpha' && secrets.ALPHA_BASE_URL || matrix.environment == 'staging' && secrets.STAGING_BASE_URL || matrix.environment == 'cloud' && secrets.CLOUD_BASE_URL }} USE_AZURE_CHAT: ${{ matrix.use_azure_chat }} + # Only gateway-and-direct-models needs it: the folder the LLM Gateway publishes its spans to. + GATEWAY_FOLDER_KEY: ${{ matrix.testcase == 'gateway-and-direct-models' && (matrix.environment == 'alpha' && secrets.ALPHA_GATEWAY_FOLDER_KEY || matrix.environment == 'staging' && secrets.STAGING_GATEWAY_FOLDER_KEY || matrix.environment == 'cloud' && secrets.CLOUD_GATEWAY_FOLDER_KEY) || '' }} UV_PYTHON: "3.12" working-directory: uipath-langchain-python/testcases/${{ matrix.testcase }} run: | From 87c81e43f7e2d84018f0f5f6a13da83e2f639380 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Tue, 24 Nov 2026 17:36:54 +0200 Subject: [PATCH 08/11] refactor: address SonarCloud's findings on the stop changes - _wait_out re-raises the caller's cancellation from its handler, after waiting again for the task, instead of keeping it for after the loop. - Each pytest.raises block in test_stop.py holds a single call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- src/uipath/runtime/debug/runtime.py | 13 +++++-------- tests/test_stop.py | 8 ++++++-- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/uipath/runtime/debug/runtime.py b/src/uipath/runtime/debug/runtime.py index f9c786ed..b0b39866 100644 --- a/src/uipath/runtime/debug/runtime.py +++ b/src/uipath/runtime/debug/runtime.py @@ -404,14 +404,11 @@ async def _wait_with_quit_check(self) -> None: async def _wait_out(task: "asyncio.Future[Any]") -> None: """Wait until ``task`` is done, through cancellations of the caller, then re-raise the last.""" - cancelled: asyncio.CancelledError | None = None - while not task.done(): - try: - await asyncio.wait({task}) - except asyncio.CancelledError as e: - cancelled = e - if cancelled is not None: - raise cancelled + try: + await asyncio.wait({task}) + except asyncio.CancelledError: + await _wait_out(task) + raise def _quit_requested(terminate: "asyncio.Future[None]") -> bool: diff --git a/tests/test_stop.py b/tests/test_stop.py index d4444d2b..d08ce7cd 100644 --- a/tests/test_stop.py +++ b/tests/test_stop.py @@ -69,13 +69,16 @@ async def body() -> None: async def test_a_stray_cancelled_error_still_faults(tmp_path: Path) -> None: ctx = _ctx(tmp_path) - with pytest.raises(asyncio.CancelledError): + async def body() -> None: with ctx: child = asyncio.ensure_future(asyncio.sleep(10)) await asyncio.sleep(0) child.cancel() await child + with pytest.raises(asyncio.CancelledError): + await body() + content = _written(ctx) assert content["status"] == UiPathRuntimeStatus.FAULTED.value assert content["error"]["code"] == "ERROR_CancelledError" @@ -135,8 +138,9 @@ async def body() -> None: async with asyncio.TaskGroup() as group: group.create_task(fail_soon()) + task = asyncio.create_task(body()) with pytest.raises(ExceptionGroup): - await asyncio.create_task(body()) + await task content = _written(ctx) assert content["status"] == UiPathRuntimeStatus.FAULTED.value From 2ea824b24551f4a876ed1e9b707b07085e63ce55 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Wed, 25 Nov 2026 09:39:56 +0200 Subject: [PATCH 09/11] fix(runtime): end a run as stopped only when its host confirms the stop A cancellation on its own does not say the host stopped the run. On Python 3.11 and 3.12, a TaskGroup whose child fails after the group's body has ended leaves the parent's cancelling() count raised, and a child whose asyncio.timeout() expires fails with a TimeoutError chained to a CancelledError. Such a run was written as stopped with its error cleared. The host now confirms the stop through a probe in uipath.runtime.stop, read from the context the run entered. uipath 2.15.8 already installs one that answers whether its stop reached the still-running root task. The run ends as stopped when that probe says yes and the exception is the cancellation or was raised because of one. Without a probe, a cancelled run faults as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- src/uipath/runtime/context.py | 35 +++++------ src/uipath/runtime/stop.py | 29 +++++++++ tests/test_stop.py | 112 +++++++++++++++++++++++++--------- 3 files changed, 131 insertions(+), 45 deletions(-) create mode 100644 src/uipath/runtime/stop.py diff --git a/src/uipath/runtime/context.py b/src/uipath/runtime/context.py index 81d13fa6..a9ea39da 100644 --- a/src/uipath/runtime/context.py +++ b/src/uipath/runtime/context.py @@ -22,6 +22,7 @@ from uipath.runtime.logging._interceptor import UiPathRuntimeLogsInterceptor from uipath.runtime.output_sinks import ResultSink, get_log_handler, get_result_sink from uipath.runtime.result import UiPathRuntimeResult, UiPathRuntimeStatus +from uipath.runtime.stop import StopRequestedProbe, get_stop_requested_probe logger = logging.getLogger(__name__) @@ -128,6 +129,7 @@ class UiPathRuntimeContext(BaseModel): # installed when the context started is the one that receives the result — even if the registry is # changed in between or __exit__ runs on a different event loop. _result_sink: ResultSink | None = PrivateAttr(default=None) + _stop_requested_probe: StopRequestedProbe | None = PrivateAttr(default=None) def _apply_execution_source(self) -> None: """Derive execution_source from the command, if not already set. @@ -248,6 +250,7 @@ def __enter__(self): # the result sink is stashed for __exit__ so the two are read at the same moment (same context). log_handler = get_log_handler() self._result_sink = get_result_sink() + self._stop_requested_probe = get_stop_requested_probe() self.logs_interceptor = UiPathRuntimeLogsInterceptor( min_level=self.logs_min_level, @@ -272,12 +275,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): if self.result is None: self.result = UiPathRuntimeResult() - if ( - exc_type - and exc_val - and _task_is_being_cancelled() - and _raised_by_a_cancellation(exc_val) - ): + if exc_type and exc_val and self._stopped_on_request(exc_val): self.result.status = UiPathRuntimeStatus.STOPPED self.result.error = None elif exc_type and exc_val: @@ -387,6 +385,19 @@ def __exit__(self, exc_type, exc_val, exc_tb): if hasattr(self, "logs_interceptor"): self.logs_interceptor.teardown() + def _stopped_on_request(self, exc: BaseException) -> bool: + """Whether the run ended in a cancellation its host confirms it asked for.""" + probe = self._stop_requested_probe + if probe is None or not _raised_by_a_cancellation(exc): + return False + try: + return bool(probe()) + except Exception: + logger.exception( + "Stop-requested probe failed; the run is reported as faulted" + ) + return False + def _deliver_result(self, sink: ResultSink, output_payload: Any) -> None: """Spill the output arguments to a file, then hand the result + that path to the sink.""" args_path = self.resolved_output_arguments_file_path @@ -539,22 +550,12 @@ def from_config( return instance -def _task_is_being_cancelled() -> bool: - """Whether someone called ``cancel()`` on the running task, as opposed to a stray CancelledError.""" - try: - task = asyncio.current_task() - except RuntimeError: - return False - return task is not None and task.cancelling() > 0 - - def _raised_by_a_cancellation( exc: BaseException, _seen: frozenset[int] = frozenset() ) -> bool: """Whether ``exc`` is a CancelledError, or was raised while handling one or because of one. - ``cancelling()`` alone is not enough: before Python 3.13, a TaskGroup whose child fails - after the group's body has ended cancels the parent task and never takes it back. + An error the run raised on its own while the stop was on its way is still a failure. """ if id(exc) in _seen: return False diff --git a/src/uipath/runtime/stop.py b/src/uipath/runtime/stop.py new file mode 100644 index 00000000..3fc3a310 --- /dev/null +++ b/src/uipath/runtime/stop.py @@ -0,0 +1,29 @@ +"""Per-execution slot through which a host says whether it stopped the execution. + +A cancelled execution ends as stopped only when the host's probe confirms the stop: a +CancelledError on its own cannot tell a stop from a timeout or a TaskGroup tearing down. +Unset, a cancelled execution ends like any other failure. A contextvar, so concurrent +executions in one process each see their own host's answer. +""" + +from __future__ import annotations + +from contextvars import ContextVar +from typing import Callable + +# () -> whether the host has stopped this execution +StopRequestedProbe = Callable[[], bool] + +_stop_requested_probe: ContextVar[StopRequestedProbe | None] = ContextVar( + "uipath_stop_requested_probe", default=None +) + + +def set_stop_requested_probe(probe: StopRequestedProbe | None) -> None: + """Install the probe for the current context (``None`` clears).""" + _stop_requested_probe.set(probe) + + +def get_stop_requested_probe() -> StopRequestedProbe | None: + """The installed probe, or None.""" + return _stop_requested_probe.get() diff --git a/tests/test_stop.py b/tests/test_stop.py index d08ce7cd..a3604c00 100644 --- a/tests/test_stop.py +++ b/tests/test_stop.py @@ -1,15 +1,16 @@ -"""A run whose task is cancelled ends as stopped rather than faulted.""" +"""A run its host stops ends as stopped rather than faulted.""" import asyncio import json from pathlib import Path -from typing import Any +from typing import Any, Callable, Coroutine import pytest from uipath.runtime.context import UiPathRuntimeContext from uipath.runtime.output_sinks import set_result_sink from uipath.runtime.result import UiPathRuntimeResult, UiPathRuntimeStatus +from uipath.runtime.stop import set_stop_requested_probe class _DummyInterceptor: @@ -33,6 +34,25 @@ def _isolate(monkeypatch: pytest.MonkeyPatch) -> Any: set_result_sink(None) +class _Host: + """Stops a run the way uipath server does: it records the stop, then cancels the task.""" + + def __init__(self) -> None: + self.stopped = False + + def install_probe(self) -> None: + set_stop_requested_probe(lambda: self.stopped) + + async def stop_while_running( + self, body: Callable[[], Coroutine[Any, Any, None]] + ) -> None: + task = asyncio.create_task(body()) + await asyncio.sleep(0.01) + self.stopped = True + task.cancel() + await asyncio.wait({task}) + + def _ctx(tmp_path: Path) -> UiPathRuntimeContext: return UiPathRuntimeContext( job_id="job-key", runtime_dir=str(tmp_path / "rt"), result_file="output.json" @@ -43,22 +63,17 @@ def _written(ctx: UiPathRuntimeContext) -> dict[str, Any]: return json.loads(Path(ctx.resolved_result_file_path).read_text()) -async def _cancel_while_running(body: Any) -> None: - task = asyncio.create_task(body()) - await asyncio.sleep(0.01) - task.cancel() - await asyncio.wait({task}) - - @pytest.mark.asyncio -async def test_a_cancelled_run_ends_as_stopped(tmp_path: Path) -> None: +async def test_a_run_the_host_stops_ends_as_stopped(tmp_path: Path) -> None: ctx = _ctx(tmp_path) + host = _Host() async def body() -> None: + host.install_probe() with ctx: await asyncio.sleep(10) - await _cancel_while_running(body) + await host.stop_while_running(body) content = _written(ctx) assert content["status"] == UiPathRuntimeStatus.STOPPED.value @@ -66,30 +81,56 @@ async def body() -> None: @pytest.mark.asyncio -async def test_a_stray_cancelled_error_still_faults(tmp_path: Path) -> None: +async def test_a_cancelled_run_without_a_probe_faults(tmp_path: Path) -> None: + ctx = _ctx(tmp_path) + + async def body() -> None: + with ctx: + await asyncio.sleep(10) + + await _Host().stop_while_running(body) + + content = _written(ctx) + assert content["status"] == UiPathRuntimeStatus.FAULTED.value + assert content["error"]["code"] == "ERROR_CancelledError" + + +@pytest.mark.asyncio +async def test_a_cancellation_the_host_did_not_ask_for_faults(tmp_path: Path) -> None: ctx = _ctx(tmp_path) + host = _Host() async def body() -> None: + host.install_probe() with ctx: child = asyncio.ensure_future(asyncio.sleep(10)) await asyncio.sleep(0) child.cancel() await child + task = asyncio.create_task(body()) with pytest.raises(asyncio.CancelledError): - await body() + await task content = _written(ctx) assert content["status"] == UiPathRuntimeStatus.FAULTED.value assert content["error"]["code"] == "ERROR_CancelledError" -def test_a_cancelled_error_outside_an_event_loop_faults(tmp_path: Path) -> None: +@pytest.mark.asyncio +async def test_a_failing_probe_faults(tmp_path: Path) -> None: ctx = _ctx(tmp_path) + host = _Host() - with pytest.raises(asyncio.CancelledError): + def broken_probe() -> bool: + raise RuntimeError("probe failed") + + async def body() -> None: + set_stop_requested_probe(broken_probe) with ctx: - raise asyncio.CancelledError() + await asyncio.sleep(10) + + await host.stop_while_running(body) assert _written(ctx)["status"] == UiPathRuntimeStatus.FAULTED.value @@ -97,46 +138,57 @@ def test_a_cancelled_error_outside_an_event_loop_faults(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_an_error_while_stopping_ends_as_stopped(tmp_path: Path) -> None: ctx = _ctx(tmp_path) + host = _Host() async def body() -> None: + host.install_probe() with ctx: try: await asyncio.sleep(10) except asyncio.CancelledError: raise RuntimeError("cleanup failed while stopping") from None - await _cancel_while_running(body) + await host.stop_while_running(body) assert _written(ctx)["status"] == UiPathRuntimeStatus.STOPPED.value @pytest.mark.asyncio -async def test_an_error_in_a_run_nobody_cancelled_faults(tmp_path: Path) -> None: +async def test_an_error_of_its_own_faults_even_once_a_stop_is_requested( + tmp_path: Path, +) -> None: ctx = _ctx(tmp_path) + host = _Host() + host.stopped = True - with pytest.raises(ValueError): + async def body() -> None: + host.install_probe() with ctx: raise ValueError("bad input") + task = asyncio.create_task(body()) + with pytest.raises(ValueError): + await task + content = _written(ctx) assert content["status"] == UiPathRuntimeStatus.FAULTED.value assert content["error"]["code"] == "ERROR_ValueError" @pytest.mark.asyncio -async def test_a_task_group_whose_child_fails_after_its_body_faults( - tmp_path: Path, -) -> None: +async def test_a_child_timeout_while_a_task_group_exits_faults(tmp_path: Path) -> None: ctx = _ctx(tmp_path) + host = _Host() - async def fail_soon() -> None: - await asyncio.sleep(0.01) - raise ValueError("child failed") + async def time_out_soon() -> None: + async with asyncio.timeout(0.01): + await asyncio.sleep(10) async def body() -> None: + host.install_probe() with ctx: async with asyncio.TaskGroup() as group: - group.create_task(fail_soon()) + group.create_task(time_out_soon()) task = asyncio.create_task(body()) with pytest.raises(ExceptionGroup): @@ -152,6 +204,7 @@ async def test_a_task_group_stopped_while_its_child_cleans_up_ends_as_stopped( tmp_path: Path, ) -> None: ctx = _ctx(tmp_path) + host = _Host() async def fail_on_cancel() -> None: try: @@ -160,12 +213,13 @@ async def fail_on_cancel() -> None: raise RuntimeError("cleanup failed while stopping") from None async def body() -> None: + host.install_probe() with ctx: async with asyncio.TaskGroup() as group: group.create_task(fail_on_cancel()) await asyncio.sleep(10) - await _cancel_while_running(body) + await host.stop_while_running(body) assert _written(ctx)["status"] == UiPathRuntimeStatus.STOPPED.value @@ -175,11 +229,13 @@ async def test_the_result_sink_receives_a_stopped_result(tmp_path: Path) -> None delivered: list[UiPathRuntimeResult] = [] set_result_sink(lambda result, _path: delivered.append(result)) ctx = _ctx(tmp_path) + host = _Host() async def body() -> None: + host.install_probe() with ctx: await asyncio.sleep(10) - await _cancel_while_running(body) + await host.stop_while_running(body) assert [r.status for r in delivered] == [UiPathRuntimeStatus.STOPPED] From ecd0eb47aa59b9b0a224e3885f1fd0ff4a08c2d7 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Wed, 25 Nov 2026 09:39:56 +0200 Subject: [PATCH 10/11] fix(debug): don't resume a stopped run when a bridge answers its cancellation The console bridge catches the CancelledError while it waits for a resume and returns a continue command, so a Ctrl+C at a breakpoint cancelled the run and then resumed the delegate's next segment. Python 3.11's asyncio.wait_for can swallow the cancellation the same way during the initial resume wait. Once execute() stops the run, the debug runtime raises the cancellation again before it starts a delegate segment and after it handles each event. The chat test's debug bridge returned from wait_for_terminate at once, which is a quit before the run starts. It now blocks like a real bridge. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- src/uipath/runtime/debug/runtime.py | 15 +++++++++ tests/test_chat.py | 3 ++ tests/test_debugger.py | 48 +++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) diff --git a/src/uipath/runtime/debug/runtime.py b/src/uipath/runtime/debug/runtime.py index b0b39866..a3478179 100644 --- a/src/uipath/runtime/debug/runtime.py +++ b/src/uipath/runtime/debug/runtime.py @@ -61,6 +61,7 @@ def __init__( if trigger_poll_interval < 0: raise ValueError("trigger_poll_interval must be >= 0") self.trigger_poll_interval = trigger_poll_interval + self._stopping = False async def execute( self, @@ -68,6 +69,7 @@ async def execute( options: UiPathExecuteOptions | None = None, ) -> UiPathRuntimeResult: """Execute the workflow with debug support; a quit while it runs stops it.""" + self._stopping = False run = asyncio.ensure_future( self._run(input, cast(UiPathStreamOptions, options)) ) @@ -81,6 +83,7 @@ async def execute( finally: terminate.cancel() if not run.done(): + self._stopping = True run.cancel() await _wait_out(run) @@ -209,6 +212,7 @@ async def _stream_and_debug( # Keep streaming until execution completes (not just paused at breakpoint) while not execution_completed: + self._raise_if_stopping() # Update breakpoints from debug bridge debug_options.breakpoints = self.debug_bridge.get_breakpoints() @@ -302,6 +306,17 @@ async def _stream_and_debug( elif isinstance(event, UiPathRuntimeStateEvent): await self.debug_bridge.emit_state_update(event) + self._raise_if_stopping() + + def _raise_if_stopping(self) -> None: + """Keep a stopped run from going on when a bridge call answered the stop's cancellation. + + A bridge may catch the CancelledError while it waits, the console bridge's resume wait + does, and return as if the user had resumed. + """ + if self._stopping: + raise asyncio.CancelledError() + def get_resumable_runtime( self, max_depth: int = 10 ) -> UiPathResumableRuntime | None: diff --git a/tests/test_chat.py b/tests/test_chat.py index f4536827..4ce419b6 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from typing import Any, AsyncGenerator, Sequence, cast from unittest.mock import AsyncMock, Mock @@ -507,6 +508,8 @@ async def test_chat_runtime_under_debugger_ends_exchange_after_reply(): debug_bridge.emit_execution_completed = AsyncMock() debug_bridge.emit_breakpoint_hit = AsyncMock() debug_bridge.wait_for_resume = AsyncMock() + # The bridge returns from wait_for_terminate only once the user quits. + debug_bridge.wait_for_terminate = AsyncMock(side_effect=asyncio.Event().wait) debug_bridge.get_breakpoints = Mock(return_value="*") calls = Mock() diff --git a/tests/test_debugger.py b/tests/test_debugger.py index 53adcb3b..9b3d858c 100644 --- a/tests/test_debugger.py +++ b/tests/test_debugger.py @@ -746,3 +746,51 @@ async def quit_soon() -> None: assert result.status == UiPathRuntimeStatus.SUCCESSFUL assert runtime_impl.cleaned_up cast(AsyncMock, bridge.emit_execution_completed).assert_awaited_once_with(result) + + +class _TwoSegmentRuntime(_BreakpointRuntime): + """Pauses at a breakpoint, then runs a second segment when resumed.""" + + def __init__(self) -> None: + self.resumed = False + + async def stream( + self, + input: dict[str, Any] | None = None, + options: UiPathStreamOptions | None = None, + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: + if options and options.resume: + self.resumed = True + yield UiPathRuntimeResult(status=UiPathRuntimeStatus.SUCCESSFUL) + return + async for event in super().stream(input, options): + yield event + + +@pytest.mark.asyncio +async def test_debug_runtime_quit_at_a_breakpoint_does_not_resume_when_the_bridge_swallows_the_stop(): + """A bridge that answers the stop's cancellation with a resume does not resume the delegate.""" + runtime_impl = _TwoSegmentRuntime() + bridge, quit_event = _bridge_with_quit() + at_breakpoint = asyncio.Event() + + async def resume_like_the_console() -> Any: + if cast(AsyncMock, bridge.wait_for_resume).await_count == 1: + return None + at_breakpoint.set() + try: + await asyncio.sleep(30) + except asyncio.CancelledError: + return {"command": "continue", "args": None} + + cast(AsyncMock, bridge.wait_for_resume).side_effect = resume_like_the_console + debug_runtime = UiPathDebugRuntime(delegate=runtime_impl, debug_bridge=bridge) + + run = asyncio.create_task(debug_runtime.execute({})) + await asyncio.wait_for(at_breakpoint.wait(), timeout=5) + quit_event.set() + result = await asyncio.wait_for(run, timeout=5) + + assert result.status == UiPathRuntimeStatus.SUCCESSFUL + assert not runtime_impl.resumed + cast(AsyncMock, bridge.emit_execution_completed).assert_awaited_once_with(result) From 92a229a37c53b6175cdb093a5cae46eaffbc0307 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Wed, 25 Nov 2026 10:53:06 +0200 Subject: [PATCH 11/11] fix(debug): report a quit at a breakpoint's completion once A quit at a breakpoint makes the resume wait raise and sets the bridge's terminate signal. stream() then reports the quit's result, and execute()'s watcher could cancel the run while that send was awaited and report completion again. A run that has started reporting its completion now owns it: a quit that lands meanwhile waits for the run instead of cancelling it. A run the quit cancels before that point still gets its completion from execute(). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- src/uipath/runtime/debug/runtime.py | 8 +++++++- tests/test_debugger.py | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/uipath/runtime/debug/runtime.py b/src/uipath/runtime/debug/runtime.py index a3478179..e85fa742 100644 --- a/src/uipath/runtime/debug/runtime.py +++ b/src/uipath/runtime/debug/runtime.py @@ -62,6 +62,7 @@ def __init__( raise ValueError("trigger_poll_interval must be >= 0") self.trigger_poll_interval = trigger_poll_interval self._stopping = False + self._reporting_completion = False async def execute( self, @@ -70,6 +71,7 @@ async def execute( ) -> UiPathRuntimeResult: """Execute the workflow with debug support; a quit while it runs stops it.""" self._stopping = False + self._reporting_completion = False run = asyncio.ensure_future( self._run(input, cast(UiPathStreamOptions, options)) ) @@ -78,7 +80,10 @@ async def execute( done, _ = await asyncio.wait( {run, terminate}, return_when=asyncio.FIRST_COMPLETED ) - if run not in done and not _quit_requested(terminate): + # A run already reporting its completion owns it, so a quit lets it finish. + if run not in done and ( + not _quit_requested(terminate) or self._reporting_completion + ): done, _ = await asyncio.wait({run}) finally: terminate.cancel() @@ -147,6 +152,7 @@ async def stream( yield result if result: + self._reporting_completion = True await self.debug_bridge.emit_execution_completed(result) except Exception as e: diff --git a/tests/test_debugger.py b/tests/test_debugger.py index 9b3d858c..9061fdd5 100644 --- a/tests/test_debugger.py +++ b/tests/test_debugger.py @@ -703,6 +703,7 @@ async def resume_then_quit() -> None: ] assert [r.status for r in results] == [UiPathRuntimeStatus.SUCCESSFUL] + cast(AsyncMock, bridge.emit_execution_completed).assert_awaited_once() class _NonStreamingWorkingRuntime(_WorkingRuntime): @@ -794,3 +795,28 @@ async def resume_like_the_console() -> Any: assert result.status == UiPathRuntimeStatus.SUCCESSFUL assert not runtime_impl.resumed cast(AsyncMock, bridge.emit_execution_completed).assert_awaited_once_with(result) + + +@pytest.mark.asyncio +async def test_debug_runtime_quit_at_a_breakpoint_reports_completion_once(): + """A quit that lands while the breakpoint's quit result is being reported sends it once.""" + bridge, quit_event = _bridge_with_quit() + + async def quit_at_the_breakpoint() -> None: + if cast(AsyncMock, bridge.wait_for_resume).await_count > 1: + quit_event.set() + raise UiPathDebugQuitError("quit") + + async def slow_send(_result: Any) -> None: + await asyncio.sleep(0.05) + + cast(AsyncMock, bridge.wait_for_resume).side_effect = quit_at_the_breakpoint + cast(AsyncMock, bridge.emit_execution_completed).side_effect = slow_send + debug_runtime = UiPathDebugRuntime( + delegate=_BreakpointRuntime(), debug_bridge=bridge + ) + + result = await asyncio.wait_for(debug_runtime.execute({}), timeout=5) + + assert result.status == UiPathRuntimeStatus.SUCCESSFUL + cast(AsyncMock, bridge.emit_execution_completed).assert_awaited_once()