diff --git a/.github/workflows/test-uipath-langchain.yml b/.github/workflows/test-uipath-langchain.yml index 057ca7e..1c35074 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: | diff --git a/pyproject.toml b/pyproject.toml index a6db49a..5cb6c0c 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 cdccf04..a9ea39d 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 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 @@ -527,3 +548,24 @@ def from_config( setattr(instance, attr_name, kwargs[attr_name]) return instance + + +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. + + 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 + 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/src/uipath/runtime/debug/runtime.py b/src/uipath/runtime/debug/runtime.py index 57ef5ec..e85fa74 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 @@ -60,17 +61,59 @@ 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 + self._reporting_completion = 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.""" + self._stopping = False + self._reporting_completion = False + 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 + ) + # 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() + if not run.done(): + self._stopping = True + run.cancel() + await _wait_out(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)): - 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 @@ -92,10 +135,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( @@ -106,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: @@ -145,14 +192,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") @@ -168,97 +218,110 @@ 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() # 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) + + 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 @@ -358,3 +421,16 @@ async def _wait_with_quit_check(self) -> None: if term_task in done: 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.""" + try: + await asyncio.wait({task}) + except asyncio.CancelledError: + await _wait_out(task) + raise + + +def _quit_requested(terminate: "asyncio.Future[None]") -> bool: + return not terminate.cancelled() and terminate.exception() is None diff --git a/src/uipath/runtime/result.py b/src/uipath/runtime/result.py index 66908f1..e692199 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 0000000..3fc3a31 --- /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_chat.py b/tests/test_chat.py index f453682..4ce419b 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 0c613a1..9061fdd 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,342 @@ 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 _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] + + +@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.""" + + 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] + cast(AsyncMock, bridge.emit_execution_completed).assert_awaited_once() + + +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) + + +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) + + +@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() diff --git a/tests/test_stop.py b/tests/test_stop.py new file mode 100644 index 0000000..a3604c0 --- /dev/null +++ b/tests/test_stop.py @@ -0,0 +1,241 @@ +"""A run its host stops ends as stopped rather than faulted.""" + +import asyncio +import json +from pathlib import Path +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: + 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_result_sink(None) + yield + 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" + ) + + +def _written(ctx: UiPathRuntimeContext) -> dict[str, Any]: + return json.loads(Path(ctx.resolved_result_file_path).read_text()) + + +@pytest.mark.asyncio +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 host.stop_while_running(body) + + content = _written(ctx) + assert content["status"] == UiPathRuntimeStatus.STOPPED.value + assert content.get("error") is None + + +@pytest.mark.asyncio +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 task + + content = _written(ctx) + assert content["status"] == UiPathRuntimeStatus.FAULTED.value + assert content["error"]["code"] == "ERROR_CancelledError" + + +@pytest.mark.asyncio +async def test_a_failing_probe_faults(tmp_path: Path) -> None: + ctx = _ctx(tmp_path) + host = _Host() + + def broken_probe() -> bool: + raise RuntimeError("probe failed") + + async def body() -> None: + set_stop_requested_probe(broken_probe) + with ctx: + await asyncio.sleep(10) + + await host.stop_while_running(body) + + assert _written(ctx)["status"] == UiPathRuntimeStatus.FAULTED.value + + +@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 host.stop_while_running(body) + + assert _written(ctx)["status"] == UiPathRuntimeStatus.STOPPED.value + + +@pytest.mark.asyncio +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 + + 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_child_timeout_while_a_task_group_exits_faults(tmp_path: Path) -> None: + ctx = _ctx(tmp_path) + host = _Host() + + 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(time_out_soon()) + + task = asyncio.create_task(body()) + with pytest.raises(ExceptionGroup): + await task + + 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) + host = _Host() + + 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: + host.install_probe() + with ctx: + async with asyncio.TaskGroup() as group: + group.create_task(fail_on_cancel()) + await asyncio.sleep(10) + + await host.stop_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] = [] + 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 host.stop_while_running(body) + + assert [r.status for r in delivered] == [UiPathRuntimeStatus.STOPPED] diff --git a/uv.lock b/uv.lock index f4a278a..d585534 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" },