From 8deb92099fa0b28ee7f0848ad1a74eeaf06b7816 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Wed, 25 Nov 2026 10:23:49 +0200 Subject: [PATCH 1/6] fix(functions): stop a debugged function when its stream is closed UiPathDebugFunctionsRuntime runs a coded function on its own thread and event loop. Closing or cancelling its stream stopped only the consumer of that thread's events: the function went on running, with its side effects, after the debugger had moved on. dispose() let it run on too, untraced, including a function paused at a breakpoint. Closing the stream before it ends now stops the function and waits for its thread. So does stop(), within its 5 second wait. A function paused at a breakpoint stops there. A running one stops at its next line or call in the project's files, raised from the trace function, or at the await it is waiting in, through its task on the thread's loop. The stop is a CancelledError, so an except Exception in the function lets it through while its finally blocks still run. Code blocked outside Python stops once it returns. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- packages/uipath/pyproject.toml | 2 +- packages/uipath/src/uipath/functions/debug.py | 132 +++++++++++--- .../tests/functions/test_debug_breakpoints.py | 167 ++++++++++++++++++ packages/uipath/ticks.txt | 1 + packages/uipath/uv.lock | 2 +- 5 files changed, 275 insertions(+), 29 deletions(-) create mode 100644 packages/uipath/ticks.txt diff --git a/packages/uipath/pyproject.toml b/packages/uipath/pyproject.toml index b9e832065..ce4a99f01 100644 --- a/packages/uipath/pyproject.toml +++ b/packages/uipath/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath" -version = "2.15.10" +version = "2.15.11" description = "Python SDK and CLI for UiPath Platform, enabling programmatic interaction with automation services, process management, and deployment tools." readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath/src/uipath/functions/debug.py b/packages/uipath/src/uipath/functions/debug.py index 4e26d581f..d3fecce65 100644 --- a/packages/uipath/src/uipath/functions/debug.py +++ b/packages/uipath/src/uipath/functions/debug.py @@ -24,6 +24,7 @@ import queue import sys import threading +from contextlib import aclosing from pathlib import Path from types import FrameType from typing import Any, AsyncGenerator, Literal @@ -78,6 +79,11 @@ def _format_location(filepath: str, line: int) -> str: return f"{relative}:{line}" +def _stopped_error() -> asyncio.CancelledError: + """The error that ends a stopped function; an ``except Exception`` lets it through.""" + return asyncio.CancelledError("Debug session stopped") + + def _is_debugger_tracer(tracer: object) -> bool: """Return True if *tracer* is the trace function of a pydevd-based debugger. @@ -106,7 +112,8 @@ class BreakpointController: UiPathBreakpointResult. 5. resume() unblocks the thread so it continues to the next breakpoint or completion. - 6. stop() terminates the thread gracefully. + 6. request_stop() ends the execution where it is, and join() waits + for its thread; stop() does both. """ def __init__( @@ -140,6 +147,9 @@ def __init__( self._resume_event = threading.Event() self._stopped = False self._thread: threading.Thread | None = None + self._loop: asyncio.AbstractEventLoop | None = None + self._task: asyncio.Task[Any] | None = None + self._lock = threading.Lock() self._abspath_cache: dict[str, str] = {} # Track which breakpoints already fired per frame so that # multiline expressions (where the bytecodes bounce back to the @@ -211,7 +221,7 @@ def _is_tracked_function(self, abspath: str, func_name: str) -> bool: def _trace_callback(self, frame: FrameType, event: str, arg: Any) -> Any: """sys.settrace callback — dispatched for every frame event.""" if self._stopped: - return None + return self._stop_in(frame) try: co_filename = frame.f_code.co_filename @@ -294,7 +304,7 @@ def _trace_callback(self, frame: FrameType, event: str, arg: Any) -> Any: self._resume_event.clear() if self._stopped: - return None + raise _stopped_error() elif event == "return": # Emit a "completed" state event for tracked functions @@ -331,6 +341,19 @@ def _trace_callback(self, frame: FrameType, event: str, arg: Any) -> Any: # Never let our own errors propagate — that would disable tracing. return self._trace_callback + def _stop_in(self, frame: FrameType) -> None: + """Raise the stop in the user's code; let library and interpreter frames run. + + Raising in the event loop's own frames would break the loop instead of + ending the function. + """ + filename = frame.f_code.co_filename + if not filename.startswith("<") and self._is_project_file( + self._abspath(filename) + ): + raise _stopped_error() + return None + # Thread lifecycle def start( @@ -361,17 +384,34 @@ def _run( ) -> None: """Thread entry-point: install the trace, execute, report result.""" try: - sys.settrace(self._trace_callback) - loop = asyncio.new_event_loop() - try: - result = loop.run_until_complete(delegate.execute(input, options)) - finally: - loop.close() - sys.settrace(None) + result = self._execute_traced(delegate, input, options) + except (Exception, asyncio.CancelledError) as exc: + # Also after a stop: a stream that stopped waiting still has a + # wait_for_event() call blocked on the queue. + self._events.put(("error", exc)) + else: self._events.put(("completed", result)) - except Exception as exc: + + def _execute_traced( + self, + delegate: UiPathRuntimeProtocol, + input: dict[str, Any] | None, + options: UiPathExecuteOptions | None, + ) -> UiPathRuntimeResult: + sys.settrace(self._trace_callback) + loop = asyncio.new_event_loop() + try: + task = loop.create_task(delegate.execute(input, options)) + with self._lock: + self._loop, self._task = loop, task + if self._stopped: + task.cancel() + return loop.run_until_complete(task) + finally: sys.settrace(None) - self._events.put(("error", exc)) + with self._lock: + self._loop = self._task = None + loop.close() # Inter-thread communication @@ -383,12 +423,28 @@ def resume(self) -> None: """Unblock the trace thread so it continues past the current breakpoint.""" self._resume_event.set() - def stop(self) -> None: - """Terminate the controller and join the background thread.""" - self._stopped = True - self._resume_event.set() # unblock if paused at a breakpoint + def request_stop(self) -> None: + """End the execution where it is, without waiting for it. + + A function paused at a breakpoint stops there. A running one stops at + its next line or call in the project's files, or at the await it is + waiting in. Code blocked outside Python stops once it returns. + """ + with self._lock: + self._stopped = True + if self._loop is not None and self._task is not None: + self._loop.call_soon_threadsafe(self._task.cancel) + self._resume_event.set() + + def join(self, timeout: float | None = None) -> None: + """Wait for the execution's thread to end.""" if self._thread is not None and self._thread.is_alive(): - self._thread.join(timeout=5.0) + self._thread.join(timeout) + + def stop(self) -> None: + """End the execution and wait up to 5 seconds for its thread.""" + self.request_stop() + self.join(timeout=5.0) class UiPathDebugFunctionsRuntime: @@ -466,8 +522,9 @@ async def stream( self._controller.update_breakpoints(breakpoints) self._controller.resume() - async for event in self._drain_events(): - yield event + async with aclosing(self._drain_events()) as events: + async for event in events: + yield event return # Build the set of tracked functions from the call graph so we @@ -517,8 +574,9 @@ async def stream( ) controller.start(self.delegate, input, delegate_options) - async for event in self._drain_events(): - yield event + async with aclosing(self._drain_events()) as events: + async for event in events: + yield event async def get_schema(self) -> UiPathRuntimeSchema: """Pass-through to delegate.""" @@ -562,14 +620,34 @@ def _build_tracked_functions(self) -> dict[str, set[str]] | None: return None async def _drain_events(self) -> AsyncGenerator[UiPathRuntimeEvent, None]: - """Drain events from the controller, yielding state events and stopping at a terminal event.""" - while self._controller is not None: - event_type, data = await asyncio.to_thread(self._controller.wait_for_event) - if event_type == "state": - yield self._to_state_event(data) - else: + """Drain events from the controller, yielding state events and stopping at a terminal event. + + Closed or cancelled before it gets that far, it ends the execution and + waits for its thread, so a caller that stops consuming the stream knows + the function no longer runs. + """ + controller = self._controller + if controller is None: + return + drained = False + try: + while True: + event_type, data = await asyncio.to_thread(controller.wait_for_event) + if event_type == "state": + yield self._to_state_event(data) + continue yield self._to_runtime_event(event_type, data) + drained = True return + finally: + if not drained: + await self._stop_execution(controller) + + async def _stop_execution(self, controller: BreakpointController) -> None: + controller.request_stop() + await asyncio.to_thread(controller.join) + if self._controller is controller: + self._controller = None @staticmethod def _to_state_event(data: dict[str, Any]) -> UiPathRuntimeStateEvent: diff --git a/packages/uipath/tests/functions/test_debug_breakpoints.py b/packages/uipath/tests/functions/test_debug_breakpoints.py index 7c2573e4f..c0f75852d 100644 --- a/packages/uipath/tests/functions/test_debug_breakpoints.py +++ b/packages/uipath/tests/functions/test_debug_breakpoints.py @@ -36,6 +36,7 @@ UiPathBreakpointResult, UiPathRuntimeResult, UiPathRuntimeStatus, + UiPathStreamOptions, ) from uipath.runtime.debug import UiPathDebugRuntime from uipath.runtime.events import UiPathRuntimeStateEvent, UiPathRuntimeStatePhase @@ -1062,3 +1063,169 @@ def coverage_tracer(frame: FrameType, event: str, arg: Any) -> None: assert not _is_debugger_tracer(None) assert not _is_debugger_tracer(coverage_tracer) + + +def _functions_runtime(script: Path) -> UiPathDebugFunctionsRuntime: + inner = UiPathFunctionsRuntime(str(script), "main", script.name) + return UiPathDebugFunctionsRuntime( + inner, entrypoint_path=str(script), function_name="main" + ) + + +async def _wait_until(path: Path, timeout: float = 5.0) -> None: + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while not path.exists(): + assert loop.time() < deadline, f"{path.name} never appeared" + await asyncio.sleep(0.01) + + +async def _assert_no_more_writes(path: Path) -> None: + before = path.read_text() + await asyncio.sleep(0.1) + assert path.read_text() == before + + +class TestStoppingTheExecution: + """Stopping the stream ends the function before the stream is done closing.""" + + async def test_closing_the_stream_stops_a_running_function(self, script_dir: Path): + script = _write_script( + script_dir, + "ticker.py", + "import time\n" + "from pathlib import Path\n" + "\n" + "def tick(n):\n" + ' Path("ticks.txt").write_text(str(n))\n' + "\n" + "def main(input):\n" + " n = 0\n" + " while True:\n" + " n += 1\n" + " tick(n)\n" + " time.sleep(0.01)\n", + ) + debug_fn = _functions_runtime(script) + events = debug_fn.stream({}) + try: + ticks = 0 + async for event in events: + if ( + isinstance(event, UiPathRuntimeStateEvent) + and event.node_name == "tick" + ): + ticks += 1 + if ticks == 3: + break + controller = debug_fn._controller + assert controller is not None + + await asyncio.wait_for(events.aclose(), timeout=5) + + assert controller._thread is not None + assert not controller._thread.is_alive() + await _assert_no_more_writes(script_dir / "ticks.txt") + finally: + await debug_fn.dispose() + + async def test_cancelling_the_consumer_stops_a_running_function( + self, script_dir: Path + ): + script = _write_script( + script_dir, + "loop.py", + "import time\n" + "from pathlib import Path\n" + "\n" + "def main(input):\n" + " n = 0\n" + " while True:\n" + " n += 1\n" + ' Path("ticks.txt").write_text(str(n))\n' + " time.sleep(0.01)\n", + ) + debug_fn = _functions_runtime(script) + + async def consume() -> None: + async for _event in debug_fn.stream({}): + pass + + consumer = asyncio.create_task(consume()) + try: + await _wait_until(script_dir / "ticks.txt") + controller = debug_fn._controller + assert controller is not None + + consumer.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(consumer, timeout=5) + + assert controller._thread is not None + assert not controller._thread.is_alive() + await _assert_no_more_writes(script_dir / "ticks.txt") + finally: + await debug_fn.dispose() + + async def test_closing_the_stream_stops_an_async_function_where_it_awaits( + self, script_dir: Path + ): + script = _write_script( + script_dir, + "waiter.py", + "import asyncio\n" + "from pathlib import Path\n" + "\n" + "async def main(input):\n" + ' Path("started.txt").write_text("1")\n' + " await asyncio.sleep(30)\n" + ' Path("finished.txt").write_text("1")\n', + ) + debug_fn = _functions_runtime(script) + events = debug_fn.stream({}) + try: + async for _event in events: + break + await _wait_until(script_dir / "started.txt") + controller = debug_fn._controller + assert controller is not None + + await asyncio.wait_for(events.aclose(), timeout=5) + + assert controller._thread is not None + assert not controller._thread.is_alive() + assert not (script_dir / "finished.txt").exists() + finally: + await debug_fn.dispose() + + async def test_dispose_stops_a_function_paused_at_a_breakpoint( + self, script_dir: Path + ): + # Line 4: x = 1 + # Line 5: Path("after.txt").write_text("ran") <- breakpoint + script = _write_script( + script_dir, + "paused.py", + "from pathlib import Path\n" + "\n" + "def main(input):\n" + " x = 1\n" + ' Path("after.txt").write_text("ran")\n' + ' return {"x": x}\n', + ) + debug_fn = _functions_runtime(script) + events = [ + event + async for event in debug_fn.stream( + {}, UiPathStreamOptions(breakpoints=["5"]) + ) + ] + assert isinstance(events[-1], UiPathBreakpointResult) + controller = debug_fn._controller + assert controller is not None + + await debug_fn.dispose() + + assert controller._thread is not None + assert not controller._thread.is_alive() + assert not (script_dir / "after.txt").exists() diff --git a/packages/uipath/ticks.txt b/packages/uipath/ticks.txt new file mode 100644 index 000000000..eed0d1a4a --- /dev/null +++ b/packages/uipath/ticks.txt @@ -0,0 +1 @@ +506 \ No newline at end of file diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index 5df0cda61..183f4f134 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2720,7 +2720,7 @@ wheels = [ [[package]] name = "uipath" -version = "2.15.10" +version = "2.15.11" source = { editable = "." } dependencies = [ { name = "applicationinsights" }, From 1d6504eaeb9a2c9e23a7cfb428f807222a03496a Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Wed, 25 Nov 2026 10:56:39 +0200 Subject: [PATCH 2/6] fix(functions): give the worker thread its tracer back after the run The controller replaced the worker thread's trace function with its own and left none behind when the run ended. It now restores the one the thread started with: a debugger's, or coverage's in the tests. Coverage cannot see code running under the controller's trace function, so the stop paths of the trace callback are also tested directly: a stopped trace raises only in the project's code, and a stop while paused at a breakpoint raises there. _drain_events takes its controller instead of re-reading one that is always set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- packages/uipath/src/uipath/functions/debug.py | 14 +++---- .../tests/functions/test_debug_breakpoints.py | 41 +++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/packages/uipath/src/uipath/functions/debug.py b/packages/uipath/src/uipath/functions/debug.py index d3fecce65..5ebc041e2 100644 --- a/packages/uipath/src/uipath/functions/debug.py +++ b/packages/uipath/src/uipath/functions/debug.py @@ -398,6 +398,7 @@ def _execute_traced( input: dict[str, Any] | None, options: UiPathExecuteOptions | None, ) -> UiPathRuntimeResult: + previous_tracer = sys.gettrace() sys.settrace(self._trace_callback) loop = asyncio.new_event_loop() try: @@ -408,7 +409,7 @@ def _execute_traced( task.cancel() return loop.run_until_complete(task) finally: - sys.settrace(None) + sys.settrace(previous_tracer) with self._lock: self._loop = self._task = None loop.close() @@ -522,7 +523,7 @@ async def stream( self._controller.update_breakpoints(breakpoints) self._controller.resume() - async with aclosing(self._drain_events()) as events: + async with aclosing(self._drain_events(self._controller)) as events: async for event in events: yield event return @@ -574,7 +575,7 @@ async def stream( ) controller.start(self.delegate, input, delegate_options) - async with aclosing(self._drain_events()) as events: + async with aclosing(self._drain_events(controller)) as events: async for event in events: yield event @@ -619,16 +620,15 @@ def _build_tracked_functions(self) -> dict[str, set[str]] | None: logger.debug("Failed to build call graph for state tracking", exc_info=True) return None - async def _drain_events(self) -> AsyncGenerator[UiPathRuntimeEvent, None]: + async def _drain_events( + self, controller: BreakpointController + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: """Drain events from the controller, yielding state events and stopping at a terminal event. Closed or cancelled before it gets that far, it ends the execution and waits for its thread, so a caller that stops consuming the stream knows the function no longer runs. """ - controller = self._controller - if controller is None: - return drained = False try: while True: diff --git a/packages/uipath/tests/functions/test_debug_breakpoints.py b/packages/uipath/tests/functions/test_debug_breakpoints.py index c0f75852d..e49d34edd 100644 --- a/packages/uipath/tests/functions/test_debug_breakpoints.py +++ b/packages/uipath/tests/functions/test_debug_breakpoints.py @@ -474,7 +474,48 @@ async def test_stream_yields_breakpoint_and_result_events(self, script_dir: Path await runtime.dispose() +def _frame_in(path: Path) -> FrameType: + """A frame of code compiled from *path*, paused at its return line (4).""" + path.write_text("import sys\n\ndef capture():\n return sys._getframe()\n") + namespace: dict[str, Any] = {} + exec(compile(path.read_text(), str(path), "exec"), namespace) + return namespace["capture"]() + + class TestBreakpointController: + def test_a_stopped_trace_raises_in_project_code_only(self, script_dir: Path): + controller = BreakpointController(project_dir=str(script_dir), breakpoints=[]) + project_frame = _frame_in(script_dir / "project.py") + controller.request_stop() + + with pytest.raises(asyncio.CancelledError): + controller._trace_callback(project_frame, "line", None) + assert controller._trace_callback(sys._getframe(), "call", None) is None + + def test_a_stop_while_paused_raises_at_the_breakpoint( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch + ): + frame = _frame_in(script_dir / "paused.py") + controller = BreakpointController( + project_dir=str(script_dir), breakpoints=[f"paused.py:{frame.f_lineno}"] + ) + + class _StoppedWhilePaused: + def wait(self) -> None: + controller._stopped = True + + def clear(self) -> None: + pass + + def set(self) -> None: + pass + + monkeypatch.setattr(controller, "_resume_event", _StoppedWhilePaused()) + + with pytest.raises(asyncio.CancelledError): + controller._trace_callback(frame, "line", None) + assert controller._events.get_nowait()[0] == "breakpoint" + def test_parse_bare_line_numbers(self, script_dir: Path): script = script_dir / "entry.py" script.write_text("x = 1\n") From 9f662b4385e5309d271e3d6906f8a9623e1a22d4 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Wed, 25 Nov 2026 11:31:17 +0200 Subject: [PATCH 3/6] fix(functions): reach all project code with a stop, deliver it once, and wait it out - The trace followed only the project files with breakpoints or call graph nodes, so a stop never reached a loop in another project file, such as a helper called through getattr(), and closing the stream waited for it forever. Every project frame is traced now. - A stop could reach an async function twice: through its task at an await, and through the trace at the next line, which was the first line of its finally block, or the other way round, interrupting an await in that block. The stop is now delivered once, by whichever comes first, and the function's cleanup runs like after an ordinary task.cancel(). - A cancellation of the task closing the stream ended the wait for the function's thread early. The wait now goes on through it, and the cancellation is raised once the thread has ended. - Removes ticks.txt, a test artifact committed by mistake. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- packages/uipath/src/uipath/functions/debug.py | 58 ++++-- .../tests/functions/test_debug_breakpoints.py | 175 +++++++++++++++++- packages/uipath/ticks.txt | 1 - 3 files changed, 210 insertions(+), 24 deletions(-) delete mode 100644 packages/uipath/ticks.txt diff --git a/packages/uipath/src/uipath/functions/debug.py b/packages/uipath/src/uipath/functions/debug.py index 5ebc041e2..218e5fda0 100644 --- a/packages/uipath/src/uipath/functions/debug.py +++ b/packages/uipath/src/uipath/functions/debug.py @@ -79,9 +79,13 @@ def _format_location(filepath: str, line: int) -> str: return f"{relative}:{line}" -def _stopped_error() -> asyncio.CancelledError: - """The error that ends a stopped function; an ``except Exception`` lets it through.""" - return asyncio.CancelledError("Debug session stopped") +async def _wait_out(future: asyncio.Future[Any]) -> None: + """Wait until ``future`` is done, through cancellations of the caller, then re-raise the last.""" + try: + await asyncio.wait({future}) + except asyncio.CancelledError: + await _wait_out(future) + raise def _is_debugger_tracer(tracer: object) -> bool: @@ -146,6 +150,8 @@ def __init__( self._events: queue.Queue[tuple[str, Any]] = queue.Queue() self._resume_event = threading.Event() self._stopped = False + # Touched only on the execution's thread: by the trace and by the loop. + self._stop_delivered = False self._thread: threading.Thread | None = None self._loop: asyncio.AbstractEventLoop | None = None self._task: asyncio.Task[Any] | None = None @@ -254,13 +260,9 @@ def _trace_callback(self, frame: FrameType, event: str, arg: Any) -> Any: # Reset per-frame hit tracking so each call starts fresh. self._hit_lines[id(frame)] = set() - # Decide whether to trace *into* this function's frame. - if self._step_mode: - return self._trace_callback if is_project else None - if filepath in self._file_breakpoints: - return self._trace_callback - # Also trace project files that contain tracked functions - if is_project and filepath in (self._state_tracked or {}): + # Trace into every project frame, also those outside the call + # graph, so that a stop reaches a loop running in any of them. + if is_project or filepath in self._file_breakpoints: return self._trace_callback return None @@ -304,7 +306,7 @@ def _trace_callback(self, frame: FrameType, event: str, arg: Any) -> Any: self._resume_event.clear() if self._stopped: - raise _stopped_error() + raise self._deliver_stop() elif event == "return": # Emit a "completed" state event for tracked functions @@ -345,15 +347,28 @@ def _stop_in(self, frame: FrameType) -> None: """Raise the stop in the user's code; let library and interpreter frames run. Raising in the event loop's own frames would break the loop instead of - ending the function. + ending the function. Once the stop is delivered, the function's cleanup + runs undisturbed. """ + if self._stop_delivered: + return None filename = frame.f_code.co_filename if not filename.startswith("<") and self._is_project_file( self._abspath(filename) ): - raise _stopped_error() + raise self._deliver_stop() return None + def _deliver_stop(self) -> asyncio.CancelledError: + self._stop_delivered = True + return asyncio.CancelledError("Debug session stopped") + + def _cancel_task(self) -> None: + """Deliver the stop through the task, unless the trace already raised it.""" + if not self._stop_delivered and self._task is not None: + self._stop_delivered = True + self._task.cancel() + # Thread lifecycle def start( @@ -406,7 +421,7 @@ def _execute_traced( with self._lock: self._loop, self._task = loop, task if self._stopped: - task.cancel() + self._cancel_task() return loop.run_until_complete(task) finally: sys.settrace(previous_tracer) @@ -429,12 +444,13 @@ def request_stop(self) -> None: A function paused at a breakpoint stops there. A running one stops at its next line or call in the project's files, or at the await it is - waiting in. Code blocked outside Python stops once it returns. + waiting in, whichever comes first; it gets the stop once. Code blocked + outside Python stops once it returns. """ with self._lock: self._stopped = True - if self._loop is not None and self._task is not None: - self._loop.call_soon_threadsafe(self._task.cancel) + if self._loop is not None: + self._loop.call_soon_threadsafe(self._cancel_task) self._resume_event.set() def join(self, timeout: float | None = None) -> None: @@ -645,9 +661,11 @@ async def _drain_events( async def _stop_execution(self, controller: BreakpointController) -> None: controller.request_stop() - await asyncio.to_thread(controller.join) - if self._controller is controller: - self._controller = None + try: + await _wait_out(asyncio.ensure_future(asyncio.to_thread(controller.join))) + finally: + if self._controller is controller: + self._controller = None @staticmethod def _to_state_event(data: dict[str, Any]) -> UiPathRuntimeStateEvent: diff --git a/packages/uipath/tests/functions/test_debug_breakpoints.py b/packages/uipath/tests/functions/test_debug_breakpoints.py index e49d34edd..e6b7dbeb2 100644 --- a/packages/uipath/tests/functions/test_debug_breakpoints.py +++ b/packages/uipath/tests/functions/test_debug_breakpoints.py @@ -22,7 +22,7 @@ from contextlib import contextmanager from pathlib import Path from types import FrameType -from typing import Any, Literal +from typing import Any, Literal, cast import pytest @@ -483,14 +483,41 @@ def _frame_in(path: Path) -> FrameType: class TestBreakpointController: - def test_a_stopped_trace_raises_in_project_code_only(self, script_dir: Path): + def test_a_stopped_trace_raises_once_and_in_project_code_only( + self, script_dir: Path + ): controller = BreakpointController(project_dir=str(script_dir), breakpoints=[]) project_frame = _frame_in(script_dir / "project.py") controller.request_stop() + assert controller._trace_callback(sys._getframe(), "call", None) is None with pytest.raises(asyncio.CancelledError): controller._trace_callback(project_frame, "line", None) - assert controller._trace_callback(sys._getframe(), "call", None) is None + assert controller._trace_callback(project_frame, "line", None) is None + + def test_the_task_gets_the_stop_only_if_the_trace_has_not(self, script_dir: Path): + class _Task: + cancels = 0 + + def cancel(self) -> None: + self.cancels += 1 + + controller = BreakpointController(project_dir=str(script_dir), breakpoints=[]) + task = _Task() + controller._task = cast(Any, task) + + controller._cancel_task() + controller._cancel_task() + assert task.cancels == 1 + + stopped_by_the_trace = BreakpointController( + project_dir=str(script_dir), breakpoints=[] + ) + untouched = _Task() + stopped_by_the_trace._task = cast(Any, untouched) + stopped_by_the_trace._deliver_stop() + stopped_by_the_trace._cancel_task() + assert untouched.cancels == 0 def test_a_stop_while_paused_raises_at_the_breakpoint( self, script_dir: Path, monkeypatch: pytest.MonkeyPatch @@ -1270,3 +1297,145 @@ async def test_dispose_stops_a_function_paused_at_a_breakpoint( assert controller._thread is not None assert not controller._thread.is_alive() assert not (script_dir / "after.txt").exists() + + +class TestStopEdgeCases: + """A stop reaches all of the project's code, is delivered once, and is waited out.""" + + async def test_closing_the_stream_stops_a_loop_outside_the_call_graph( + self, script_dir: Path + ): + _write_script( + script_dir, + "spin_helper.py", + "def spin():\n n = 0\n while True:\n n += 1\n", + ) + script = _write_script( + script_dir, + "dynamic.py", + "from pathlib import Path\n" + "import spin_helper\n" + "\n" + "def main(input):\n" + ' Path("started.txt").write_text("1")\n' + ' getattr(spin_helper, "spin")()\n', + ) + debug_fn = _functions_runtime(script) + events = debug_fn.stream({}) + try: + async for _event in events: + break + await _wait_until(script_dir / "started.txt") + controller = debug_fn._controller + assert controller is not None + + await asyncio.wait_for(events.aclose(), timeout=5) + + assert controller._thread is not None + assert not controller._thread.is_alive() + finally: + await debug_fn.dispose() + + async def test_closing_the_stream_lets_an_awaiting_function_finish_its_cleanup( + self, script_dir: Path + ): + script = _write_script( + script_dir, + "awaiting_cleanup.py", + "import asyncio\n" + "from pathlib import Path\n" + "\n" + "async def main(input):\n" + " try:\n" + ' Path("started.txt").write_text("1")\n' + " await asyncio.sleep(30)\n" + " finally:\n" + ' Path("cleanup_started.txt").write_text("1")\n' + " await asyncio.sleep(0.01)\n" + ' Path("cleanup_done.txt").write_text("1")\n', + ) + debug_fn = _functions_runtime(script) + events = debug_fn.stream({}) + try: + async for _event in events: + break + await _wait_until(script_dir / "started.txt") + + await asyncio.wait_for(events.aclose(), timeout=5) + + assert (script_dir / "cleanup_started.txt").exists() + assert (script_dir / "cleanup_done.txt").exists() + finally: + await debug_fn.dispose() + + async def test_a_stop_in_running_code_lets_its_async_cleanup_finish( + self, script_dir: Path + ): + script = _write_script( + script_dir, + "running_cleanup.py", + "import asyncio\n" + "import time\n" + "from pathlib import Path\n" + "\n" + "async def main(input):\n" + " try:\n" + ' Path("started.txt").write_text("1")\n' + " while True:\n" + " time.sleep(0.01)\n" + " finally:\n" + ' Path("cleanup_started.txt").write_text("1")\n' + " await asyncio.sleep(0.01)\n" + ' Path("cleanup_done.txt").write_text("1")\n', + ) + debug_fn = _functions_runtime(script) + events = debug_fn.stream({}) + try: + async for _event in events: + break + await _wait_until(script_dir / "started.txt") + + await asyncio.wait_for(events.aclose(), timeout=5) + + assert (script_dir / "cleanup_started.txt").exists() + assert (script_dir / "cleanup_done.txt").exists() + finally: + await debug_fn.dispose() + + async def test_cancelling_the_close_still_waits_for_the_function( + self, script_dir: Path + ): + script = _write_script( + script_dir, + "blocking.py", + "import time\n" + "from pathlib import Path\n" + "\n" + "def main(input):\n" + ' Path("started.txt").write_text("1")\n' + " time.sleep(1.0)\n" + ' Path("finished.txt").write_text("1")\n', + ) + debug_fn = _functions_runtime(script) + events = debug_fn.stream({}) + try: + async for _event in events: + break + await _wait_until(script_dir / "started.txt") + controller = debug_fn._controller + assert controller is not None + # Let it get past its marker and into the blocking call. + await asyncio.sleep(0.2) + + closer = asyncio.create_task(events.aclose()) + await asyncio.sleep(0.05) + closer.cancel() + done, _ = await asyncio.wait({closer}, timeout=5) + assert closer in done + assert closer.cancelled() + + assert controller._thread is not None + assert not controller._thread.is_alive() + assert not (script_dir / "finished.txt").exists() + finally: + await debug_fn.dispose() diff --git a/packages/uipath/ticks.txt b/packages/uipath/ticks.txt deleted file mode 100644 index eed0d1a4a..000000000 --- a/packages/uipath/ticks.txt +++ /dev/null @@ -1 +0,0 @@ -506 \ No newline at end of file From a87bf7f341d2d7428a46a39625e1fb862e74f07a Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Wed, 25 Nov 2026 14:04:12 +0200 Subject: [PATCH 4/6] fix(functions): stop the function's own task when a stop reaches another task A stop at a breakpoint in a TaskGroup child cancelled only the child: a task group ignores a cancelled child, and the stop counted as delivered, so the parent went on after the group. Each task now gets the stop once: - The trace raises it at the next line in the project's files, never at a "call" event: resuming a coroutine is one, and raising there skips its exception handlers. Raising unsets the thread's trace, so the trace is set again from the loop, for the function's other tasks. - A task unwinding the cancellation of a task it awaits has got the stop, and one whose cancellation is on its way is left to it. - The function's own task is cancelled once the tasks that got the stop have finished, unless the stop reached it already. Earlier, its task group or await would cancel them again during their cleanup. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- packages/uipath/src/uipath/functions/debug.py | 83 +++-- .../tests/functions/test_debug_breakpoints.py | 312 ++++++++++++++++-- 2 files changed, 343 insertions(+), 52 deletions(-) diff --git a/packages/uipath/src/uipath/functions/debug.py b/packages/uipath/src/uipath/functions/debug.py index 218e5fda0..e393df596 100644 --- a/packages/uipath/src/uipath/functions/debug.py +++ b/packages/uipath/src/uipath/functions/debug.py @@ -151,7 +151,8 @@ def __init__( self._resume_event = threading.Event() self._stopped = False # Touched only on the execution's thread: by the trace and by the loop. - self._stop_delivered = False + self._stopped_tasks: set[asyncio.Task[Any]] = set() + self._unwinding_tasks: set[asyncio.Task[Any]] = set() self._thread: threading.Thread | None = None self._loop: asyncio.AbstractEventLoop | None = None self._task: asyncio.Task[Any] | None = None @@ -227,7 +228,7 @@ def _is_tracked_function(self, abspath: str, func_name: str) -> bool: def _trace_callback(self, frame: FrameType, event: str, arg: Any) -> Any: """sys.settrace callback — dispatched for every frame event.""" if self._stopped: - return self._stop_in(frame) + return self._stop_in(frame, event, arg) try: co_filename = frame.f_code.co_filename @@ -306,7 +307,7 @@ def _trace_callback(self, frame: FrameType, event: str, arg: Any) -> Any: self._resume_event.clear() if self._stopped: - raise self._deliver_stop() + return self._stop_in(frame, event, arg) elif event == "return": # Emit a "completed" state event for tracked functions @@ -343,31 +344,62 @@ def _trace_callback(self, frame: FrameType, event: str, arg: Any) -> Any: # Never let our own errors propagate — that would disable tracing. return self._trace_callback - def _stop_in(self, frame: FrameType) -> None: - """Raise the stop in the user's code; let library and interpreter frames run. + def _stop_in(self, frame: FrameType, event: str, arg: Any) -> Any: + """Stop the task running the user's code; let library and interpreter frames run. Raising in the event loop's own frames would break the loop instead of - ending the function. Once the stop is delivered, the function's cleanup - runs undisturbed. + ending the function. Each task gets the stop once, so its cleanup runs + as after an ordinary cancellation. """ - if self._stop_delivered: - return None filename = frame.f_code.co_filename - if not filename.startswith("<") and self._is_project_file( - self._abspath(filename) + loop = self._loop + if ( + loop is None + or filename.startswith("<") + or not self._is_project_file(self._abspath(filename)) ): - raise self._deliver_stop() - return None - - def _deliver_stop(self) -> asyncio.CancelledError: - self._stop_delivered = True - return asyncio.CancelledError("Debug session stopped") + return None + task = asyncio.current_task(loop) + if task is None or task in self._stopped_tasks: + return None + if task.cancelling(): + # Its cancellation stops it; look again if it swallows that one. + return self._trace_callback + if event == "exception" and issubclass(arg[0], asyncio.CancelledError): + # It is unwinding the stop of a task it awaits. + self._mark_stopped(task) + return None + if event != "line": + # A coroutine's resumption is a "call" event, and raising there + # would skip its exception handlers. + return self._trace_callback + self._mark_stopped(task) + # A trace function that raises is unset, and the function's other + # tasks still need it to stop where they run. + loop.call_soon(sys.settrace, self._trace_callback) + raise asyncio.CancelledError("Debug session stopped") + + def _mark_stopped(self, task: asyncio.Task[Any]) -> None: + self._stopped_tasks.add(task) + if task is not self._task: + self._unwinding_tasks.add(task) + task.add_done_callback(self._on_stopped_task_done) + + def _on_stopped_task_done(self, task: asyncio.Task[Any]) -> None: + self._unwinding_tasks.discard(task) + self._cancel_task() def _cancel_task(self) -> None: - """Deliver the stop through the task, unless the trace already raised it.""" - if not self._stop_delivered and self._task is not None: - self._stop_delivered = True - self._task.cancel() + """Stop the function's own task, unless the stop already reached it. + + Waits for the tasks that got the stop to finish: the task groups and + awaits they belong to would cancel them again during their cleanup. + """ + task = self._task + if task is None or task in self._stopped_tasks or self._unwinding_tasks: + return + self._stopped_tasks.add(task) + task.cancel() # Thread lifecycle @@ -427,6 +459,8 @@ def _execute_traced( sys.settrace(previous_tracer) with self._lock: self._loop = self._task = None + self._stopped_tasks.clear() + self._unwinding_tasks.clear() loop.close() # Inter-thread communication @@ -443,9 +477,10 @@ def request_stop(self) -> None: """End the execution where it is, without waiting for it. A function paused at a breakpoint stops there. A running one stops at - its next line or call in the project's files, or at the await it is - waiting in, whichever comes first; it gets the stop once. Code blocked - outside Python stops once it returns. + its next line in the project's files, or at the await it is waiting + in, whichever comes first. Each of its tasks gets the stop once, and + the function's own task gets it after the others have finished. Code + blocked outside Python stops once it returns. """ with self._lock: self._stopped = True diff --git a/packages/uipath/tests/functions/test_debug_breakpoints.py b/packages/uipath/tests/functions/test_debug_breakpoints.py index e6b7dbeb2..e4be2f2b0 100644 --- a/packages/uipath/tests/functions/test_debug_breakpoints.py +++ b/packages/uipath/tests/functions/test_debug_breakpoints.py @@ -482,50 +482,148 @@ def _frame_in(path: Path) -> FrameType: return namespace["capture"]() +class _Loop: + def __init__(self) -> None: + self.scheduled: list[tuple[Any, tuple[Any, ...]]] = [] + + def call_soon(self, callback: Any, *args: Any) -> None: + self.scheduled.append((callback, args)) + + def call_soon_threadsafe(self, callback: Any, *args: Any) -> None: + self.scheduled.append((callback, args)) + + +class _Task: + def __init__(self, cancelling: int = 0) -> None: + self.cancels = 0 + self.done_callbacks: list[Any] = [] + self._cancelling = cancelling + + def cancelling(self) -> int: + return self._cancelling + + def cancel(self) -> bool: + self.cancels += 1 + return True + + def add_done_callback(self, callback: Any) -> None: + self.done_callbacks.append(callback) + + def finish(self) -> None: + for callback in self.done_callbacks: + callback(self) + + +class _Stopped: + """A stopped controller whose execution runs ``function_task`` on a fake loop.""" + + def __init__( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch, breakpoints=() + ) -> None: + self.controller = BreakpointController( + project_dir=str(script_dir), breakpoints=list(breakpoints) + ) + self.loop = _Loop() + self.function_task = _Task() + self.current: _Task | None = self.function_task + self.controller._loop = cast(Any, self.loop) + self.controller._task = cast(Any, self.function_task) + monkeypatch.setattr(asyncio, "current_task", lambda loop=None: self.current) + self.controller.request_stop() + + def trace(self, frame: FrameType, event: str = "line", arg: Any = None) -> Any: + return self.controller._trace_callback(frame, event, arg) + + class TestBreakpointController: - def test_a_stopped_trace_raises_once_and_in_project_code_only( - self, script_dir: Path + def test_a_stop_raises_once_per_task_and_in_project_code_only( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch ): - controller = BreakpointController(project_dir=str(script_dir), breakpoints=[]) + stopped = _Stopped(script_dir, monkeypatch) project_frame = _frame_in(script_dir / "project.py") - controller.request_stop() + child = _Task() + stopped.current = child + + assert stopped.trace(sys._getframe(), "call") is None + # Also a coroutine's resumption: raising there would skip its handlers. + assert ( + stopped.trace(project_frame, "call") == stopped.controller._trace_callback + ) + with pytest.raises(asyncio.CancelledError): + stopped.trace(project_frame) + assert stopped.trace(project_frame) is None - assert controller._trace_callback(sys._getframe(), "call", None) is None + stopped.current = stopped.function_task with pytest.raises(asyncio.CancelledError): - controller._trace_callback(project_frame, "line", None) - assert controller._trace_callback(project_frame, "line", None) is None + stopped.trace(project_frame) + assert stopped.trace(project_frame) is None - def test_the_task_gets_the_stop_only_if_the_trace_has_not(self, script_dir: Path): - class _Task: - cancels = 0 + retrace = (sys.settrace, (stopped.controller._trace_callback,)) + assert stopped.loop.scheduled.count(retrace) == 2 - def cancel(self) -> None: - self.cancels += 1 + def test_a_stop_leaves_code_outside_the_execution_alone( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch + ): + project_frame = _frame_in(script_dir / "project.py") + before_the_loop = BreakpointController( + project_dir=str(script_dir), breakpoints=[] + ) + before_the_loop.request_stop() + assert before_the_loop._trace_callback(project_frame, "line", None) is None - controller = BreakpointController(project_dir=str(script_dir), breakpoints=[]) - task = _Task() - controller._task = cast(Any, task) + stopped = _Stopped(script_dir, monkeypatch) + stopped.current = None + assert stopped.trace(project_frame) is None - controller._cancel_task() - controller._cancel_task() - assert task.cancels == 1 + def test_a_task_with_a_cancellation_on_its_way_is_left_to_it( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch + ): + stopped = _Stopped(script_dir, monkeypatch) + stopped.current = _Task(cancelling=1) - stopped_by_the_trace = BreakpointController( - project_dir=str(script_dir), breakpoints=[] + project_frame = _frame_in(script_dir / "project.py") + assert stopped.trace(project_frame) == stopped.controller._trace_callback + + def test_a_task_unwinding_the_stop_of_a_task_it_awaits_gets_no_other( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch + ): + stopped = _Stopped(script_dir, monkeypatch) + project_frame = _frame_in(script_dir / "project.py") + error = asyncio.CancelledError() + + assert ( + stopped.trace(project_frame, "exception", (type(error), error, None)) + is None ) - untouched = _Task() - stopped_by_the_trace._task = cast(Any, untouched) - stopped_by_the_trace._deliver_stop() - stopped_by_the_trace._cancel_task() - assert untouched.cancels == 0 + assert stopped.trace(project_frame) is None + stopped.controller._cancel_task() + assert stopped.function_task.cancels == 0 + + def test_the_function_task_is_cancelled_once_its_stopped_tasks_are_done( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch + ): + stopped = _Stopped(script_dir, monkeypatch) + child = _Task() + stopped.current = child + with pytest.raises(asyncio.CancelledError): + stopped.trace(_frame_in(script_dir / "project.py")) + + stopped.controller._cancel_task() + assert stopped.function_task.cancels == 0 + + child.finish() + stopped.controller._cancel_task() + assert stopped.function_task.cancels == 1 def test_a_stop_while_paused_raises_at_the_breakpoint( self, script_dir: Path, monkeypatch: pytest.MonkeyPatch ): frame = _frame_in(script_dir / "paused.py") - controller = BreakpointController( - project_dir=str(script_dir), breakpoints=[f"paused.py:{frame.f_lineno}"] + stopped = _Stopped( + script_dir, monkeypatch, breakpoints=[f"paused.py:{frame.f_lineno}"] ) + controller = stopped.controller + controller._stopped = False class _StoppedWhilePaused: def wait(self) -> None: @@ -540,7 +638,7 @@ def set(self) -> None: monkeypatch.setattr(controller, "_resume_event", _StoppedWhilePaused()) with pytest.raises(asyncio.CancelledError): - controller._trace_callback(frame, "line", None) + stopped.trace(frame) assert controller._events.get_nowait()[0] == "breakpoint" def test_parse_bare_line_numbers(self, script_dir: Path): @@ -1439,3 +1537,161 @@ async def test_cancelling_the_close_still_waits_for_the_function( assert not (script_dir / "finished.txt").exists() finally: await debug_fn.dispose() + + +class TestStoppingConcurrentCode: + """A stop that reaches one of the function's tasks ends the function too.""" + + async def test_a_stop_at_a_breakpoint_in_a_task_group_child_stops_the_parent( + self, script_dir: Path + ): + # Line 5: x = 1 <- breakpoint, in the child task + script = _write_script( + script_dir, + "group.py", + "import asyncio\n" + "from pathlib import Path\n" + "\n" + "async def child():\n" + " x = 1\n" + " return x\n" + "\n" + "async def main(input):\n" + " async with asyncio.TaskGroup() as tg:\n" + " tg.create_task(child())\n" + ' Path("after.txt").write_text("ran")\n', + ) + debug_fn = _functions_runtime(script) + events = [ + event + async for event in debug_fn.stream( + {}, UiPathStreamOptions(breakpoints=["5"]) + ) + ] + assert isinstance(events[-1], UiPathBreakpointResult) + controller = debug_fn._controller + assert controller is not None + + await debug_fn.dispose() + + assert controller._thread is not None + assert not controller._thread.is_alive() + assert not (script_dir / "after.txt").exists() + + async def test_a_task_group_child_finishes_its_cleanup_before_the_parent_stops( + self, script_dir: Path + ): + # Line 6: x = 1 <- breakpoint, in the child task + script = _write_script( + script_dir, + "group_cleanup.py", + "import asyncio\n" + "from pathlib import Path\n" + "\n" + "async def child():\n" + " try:\n" + " x = 1\n" + " return x\n" + " finally:\n" + ' Path("cleanup_started.txt").write_text("1")\n' + " await asyncio.sleep(0.01)\n" + ' Path("cleanup_done.txt").write_text("1")\n' + "\n" + "async def main(input):\n" + " async with asyncio.TaskGroup() as tg:\n" + " tg.create_task(child())\n" + ' Path("after.txt").write_text("ran")\n', + ) + debug_fn = _functions_runtime(script) + events = [ + event + async for event in debug_fn.stream( + {}, UiPathStreamOptions(breakpoints=["6"]) + ) + ] + assert isinstance(events[-1], UiPathBreakpointResult) + + await debug_fn.dispose() + + assert (script_dir / "cleanup_started.txt").exists() + assert (script_dir / "cleanup_done.txt").exists() + assert not (script_dir / "after.txt").exists() + + async def test_a_parent_awaiting_a_stopped_child_gets_the_stop_once( + self, script_dir: Path + ): + # Line 5: x = 1 <- breakpoint, in the child task + script = _write_script( + script_dir, + "awaited_child.py", + "import asyncio\n" + "from pathlib import Path\n" + "\n" + "async def child():\n" + " x = 1\n" + " return x\n" + "\n" + "async def main(input):\n" + " try:\n" + " await asyncio.create_task(child())\n" + ' Path("after.txt").write_text("ran")\n' + " finally:\n" + ' Path("cleanup_started.txt").write_text("1")\n' + " await asyncio.sleep(0.01)\n" + ' Path("cleanup_done.txt").write_text("1")\n', + ) + debug_fn = _functions_runtime(script) + events = [ + event + async for event in debug_fn.stream( + {}, UiPathStreamOptions(breakpoints=["5"]) + ) + ] + assert isinstance(events[-1], UiPathBreakpointResult) + + await debug_fn.dispose() + + assert not (script_dir / "after.txt").exists() + assert (script_dir / "cleanup_started.txt").exists() + assert (script_dir / "cleanup_done.txt").exists() + + async def test_closing_the_stream_stops_a_busy_task_group_and_its_idle_tasks( + self, script_dir: Path + ): + script = _write_script( + script_dir, + "group_spin.py", + "import asyncio\n" + "from pathlib import Path\n" + "\n" + "async def spin():\n" + ' Path("started.txt").write_text("1")\n' + " n = 0\n" + " while True:\n" + " n += 1\n" + "\n" + "async def idle():\n" + " await asyncio.Event().wait()\n" + "\n" + "async def main(input):\n" + " async with asyncio.TaskGroup() as tg:\n" + " tg.create_task(idle())\n" + " tg.create_task(spin())\n" + ' Path("after.txt").write_text("ran")\n', + ) + debug_fn = _functions_runtime(script) + events = debug_fn.stream({}) + try: + async for _event in events: + break + await _wait_until(script_dir / "started.txt") + controller = debug_fn._controller + assert controller is not None + + await asyncio.wait_for(events.aclose(), timeout=5) + + assert controller._thread is not None + assert not controller._thread.is_alive() + assert not (script_dir / "after.txt").exists() + finally: + await debug_fn.dispose() From c668dc7eeb7a8a386e3d65fd2f6f740a83d705a1 Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Wed, 25 Nov 2026 18:51:06 +0200 Subject: [PATCH 5/6] fix(functions): let a stopped task finish its cleanup when its parent stops A parent in a task group that resumed while a stopped child was awaiting in its finally got the stop at its next line. The task group then cancelled the child again and cut its cleanup short. The execution's event loop now creates tasks that ignore cancellation once the stop has reached them, so the task groups and awaits they belong to wait for their cleanup. The function's own task no longer waits for the stopped tasks before it is cancelled. A parent whose step was already queued when the child raised also ran its next line untraced: a trace function that raises is unset for the thread, and setting it again was queued behind that step. A one-shot profile hook now sets it again at the thread's next call or return, which the raising task reaches before the loop runs any other. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- packages/uipath/src/uipath/functions/debug.py | 69 ++++++++---- .../tests/functions/test_debug_breakpoints.py | 106 ++++++++++++++---- 2 files changed, 134 insertions(+), 41 deletions(-) diff --git a/packages/uipath/src/uipath/functions/debug.py b/packages/uipath/src/uipath/functions/debug.py index e393df596..81cbfa290 100644 --- a/packages/uipath/src/uipath/functions/debug.py +++ b/packages/uipath/src/uipath/functions/debug.py @@ -88,6 +88,28 @@ async def _wait_out(future: asyncio.Future[Any]) -> None: raise +class _StopOnceTask(asyncio.Task[Any]): + """A task that ignores cancellation once the debug stop has reached it. + + The stop ends it like a cancellation. The task groups and awaits it belongs + to would cancel it again when the stop reaches them, cutting its cleanup + short. + """ + + stopped = False + + def cancel(self, msg: Any | None = None) -> bool: + if self.stopped: + return False + return super().cancel(msg) + + +def _new_stop_once_task( + loop: asyncio.AbstractEventLoop, coro: Any, **kwargs: Any +) -> asyncio.Task[Any]: + return _StopOnceTask(coro, loop=loop, **kwargs) + + def _is_debugger_tracer(tracer: object) -> bool: """Return True if *tracer* is the trace function of a pydevd-based debugger. @@ -152,7 +174,6 @@ def __init__( self._stopped = False # Touched only on the execution's thread: by the trace and by the loop. self._stopped_tasks: set[asyncio.Task[Any]] = set() - self._unwinding_tasks: set[asyncio.Task[Any]] = set() self._thread: threading.Thread | None = None self._loop: asyncio.AbstractEventLoop | None = None self._task: asyncio.Task[Any] | None = None @@ -374,32 +395,36 @@ def _stop_in(self, frame: FrameType, event: str, arg: Any) -> Any: # would skip its exception handlers. return self._trace_callback self._mark_stopped(task) - # A trace function that raises is unset, and the function's other - # tasks still need it to stop where they run. - loop.call_soon(sys.settrace, self._trace_callback) + self._retrace_at_next_call() raise asyncio.CancelledError("Debug session stopped") + def _retrace_at_next_call(self) -> None: + """Set the trace again at the thread's next call or return. + + A trace function that raises is unset for the whole thread, and the + function's other tasks still need it to stop where they run. The task + that raised calls or returns before the loop runs any other. + """ + previous = sys.getprofile() + + def retrace(frame: FrameType, event: str, arg: Any) -> None: + sys.setprofile(previous) + sys.settrace(self._trace_callback) + + sys.setprofile(retrace) + def _mark_stopped(self, task: asyncio.Task[Any]) -> None: self._stopped_tasks.add(task) - if task is not self._task: - self._unwinding_tasks.add(task) - task.add_done_callback(self._on_stopped_task_done) - - def _on_stopped_task_done(self, task: asyncio.Task[Any]) -> None: - self._unwinding_tasks.discard(task) - self._cancel_task() + if isinstance(task, _StopOnceTask): + task.stopped = True def _cancel_task(self) -> None: - """Stop the function's own task, unless the stop already reached it. - - Waits for the tasks that got the stop to finish: the task groups and - awaits they belong to would cancel them again during their cleanup. - """ + """Stop the function's own task, unless the stop already reached it.""" task = self._task - if task is None or task in self._stopped_tasks or self._unwinding_tasks: + if task is None or task in self._stopped_tasks: return - self._stopped_tasks.add(task) task.cancel() + self._mark_stopped(task) # Thread lifecycle @@ -448,6 +473,7 @@ def _execute_traced( previous_tracer = sys.gettrace() sys.settrace(self._trace_callback) loop = asyncio.new_event_loop() + loop.set_task_factory(_new_stop_once_task) try: task = loop.create_task(delegate.execute(input, options)) with self._lock: @@ -460,7 +486,6 @@ def _execute_traced( with self._lock: self._loop = self._task = None self._stopped_tasks.clear() - self._unwinding_tasks.clear() loop.close() # Inter-thread communication @@ -478,9 +503,9 @@ def request_stop(self) -> None: A function paused at a breakpoint stops there. A running one stops at its next line in the project's files, or at the await it is waiting - in, whichever comes first. Each of its tasks gets the stop once, and - the function's own task gets it after the others have finished. Code - blocked outside Python stops once it returns. + in, whichever comes first. Each of its tasks gets the stop once, so + the task groups and awaits a stopped task belongs to wait for its + cleanup. Code blocked outside Python stops once it returns. """ with self._lock: self._stopped = True diff --git a/packages/uipath/tests/functions/test_debug_breakpoints.py b/packages/uipath/tests/functions/test_debug_breakpoints.py index e4be2f2b0..fd0d37db2 100644 --- a/packages/uipath/tests/functions/test_debug_breakpoints.py +++ b/packages/uipath/tests/functions/test_debug_breakpoints.py @@ -30,6 +30,7 @@ BreakpointController, UiPathDebugFunctionsRuntime, _is_debugger_tracer, + _new_stop_once_task, ) from uipath.functions.runtime import UiPathFunctionsRuntime from uipath.runtime import ( @@ -486,9 +487,6 @@ class _Loop: def __init__(self) -> None: self.scheduled: list[tuple[Any, tuple[Any, ...]]] = [] - def call_soon(self, callback: Any, *args: Any) -> None: - self.scheduled.append((callback, args)) - def call_soon_threadsafe(self, callback: Any, *args: Any) -> None: self.scheduled.append((callback, args)) @@ -496,7 +494,6 @@ def call_soon_threadsafe(self, callback: Any, *args: Any) -> None: class _Task: def __init__(self, cancelling: int = 0) -> None: self.cancels = 0 - self.done_callbacks: list[Any] = [] self._cancelling = cancelling def cancelling(self) -> int: @@ -506,13 +503,6 @@ def cancel(self) -> bool: self.cancels += 1 return True - def add_done_callback(self, callback: Any) -> None: - self.done_callbacks.append(callback) - - def finish(self) -> None: - for callback in self.done_callbacks: - callback(self) - class _Stopped: """A stopped controller whose execution runs ``function_task`` on a fake loop.""" @@ -529,6 +519,9 @@ def __init__( self.controller._loop = cast(Any, self.loop) self.controller._task = cast(Any, self.function_task) monkeypatch.setattr(asyncio, "current_task", lambda loop=None: self.current) + # The trace is called directly here, so it stays set when it raises. + self.retraces: list[Any] = [] + monkeypatch.setattr(sys, "setprofile", self.retraces.append) self.controller.request_stop() def trace(self, frame: FrameType, event: str = "line", arg: Any = None) -> Any: @@ -558,8 +551,24 @@ def test_a_stop_raises_once_per_task_and_in_project_code_only( stopped.trace(project_frame) assert stopped.trace(project_frame) is None - retrace = (sys.settrace, (stopped.controller._trace_callback,)) - assert stopped.loop.scheduled.count(retrace) == 2 + assert len(stopped.retraces) == 2 + + def test_the_trace_is_set_again_at_the_next_call_after_it_raises( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch + ): + stopped = _Stopped(script_dir, monkeypatch) + previous_profiler = object() + monkeypatch.setattr(sys, "getprofile", lambda: previous_profiler) + traces: list[Any] = [] + monkeypatch.setattr(sys, "settrace", traces.append) + with pytest.raises(asyncio.CancelledError): + stopped.trace(_frame_in(script_dir / "project.py")) + [retrace] = stopped.retraces + + retrace(sys._getframe(), "call", None) + + assert traces == [stopped.controller._trace_callback] + assert stopped.retraces == [retrace, previous_profiler] def test_a_stop_leaves_code_outside_the_execution_alone( self, script_dir: Path, monkeypatch: pytest.MonkeyPatch @@ -599,22 +608,36 @@ def test_a_task_unwinding_the_stop_of_a_task_it_awaits_gets_no_other( stopped.controller._cancel_task() assert stopped.function_task.cancels == 0 - def test_the_function_task_is_cancelled_once_its_stopped_tasks_are_done( + def test_the_function_task_is_cancelled_once( self, script_dir: Path, monkeypatch: pytest.MonkeyPatch ): stopped = _Stopped(script_dir, monkeypatch) - child = _Task() - stopped.current = child + stopped.current = _Task() with pytest.raises(asyncio.CancelledError): stopped.trace(_frame_in(script_dir / "project.py")) stopped.controller._cancel_task() - assert stopped.function_task.cancels == 0 - - child.finish() stopped.controller._cancel_task() + assert stopped.function_task.cancels == 1 + def test_a_task_the_stop_reached_ignores_cancellation(self, script_dir: Path): + controller = BreakpointController(project_dir=str(script_dir), breakpoints=[]) + loop = asyncio.new_event_loop() + try: + loop.set_task_factory(_new_stop_once_task) + stopped = loop.create_task(asyncio.sleep(0, "done")) + running = loop.create_task(asyncio.sleep(1)) + controller._mark_stopped(stopped) + + assert not stopped.cancel() + assert running.cancel() + assert loop.run_until_complete(stopped) == "done" + with pytest.raises(asyncio.CancelledError): + loop.run_until_complete(running) + finally: + loop.close() + def test_a_stop_while_paused_raises_at_the_breakpoint( self, script_dir: Path, monkeypatch: pytest.MonkeyPatch ): @@ -1617,6 +1640,51 @@ async def test_a_task_group_child_finishes_its_cleanup_before_the_parent_stops( assert (script_dir / "cleanup_done.txt").exists() assert not (script_dir / "after.txt").exists() + async def test_a_parent_resuming_during_a_stopped_childs_cleanup_waits_for_it( + self, script_dir: Path + ): + # Line 6: x = 1 <- breakpoint, in the child task. The parent's next + # step is already queued, so it resumes while the child cleans up. + script = _write_script( + script_dir, + "group_parent_resumes.py", + "import asyncio\n" + "from pathlib import Path\n" + "\n" + "async def child():\n" + " try:\n" + " x = 1\n" + " return x\n" + " finally:\n" + ' Path("cleanup_started.txt").write_text("1")\n' + " await asyncio.sleep(0.2)\n" + ' Path("cleanup_done.txt").write_text("1")\n' + "\n" + "async def main(input):\n" + " try:\n" + " async with asyncio.TaskGroup() as tg:\n" + " tg.create_task(child())\n" + " await asyncio.sleep(0)\n" + ' Path("parent_body.txt").write_text("1")\n' + " finally:\n" + ' Path("parent_cleanup.txt").write_text("1")\n', + ) + debug_fn = _functions_runtime(script) + events = [ + event + async for event in debug_fn.stream( + {}, UiPathStreamOptions(breakpoints=["6"]) + ) + ] + assert isinstance(events[-1], UiPathBreakpointResult) + + await debug_fn.dispose() + + assert (script_dir / "cleanup_started.txt").exists() + assert (script_dir / "cleanup_done.txt").exists() + assert not (script_dir / "parent_body.txt").exists() + assert (script_dir / "parent_cleanup.txt").exists() + async def test_a_parent_awaiting_a_stopped_child_gets_the_stop_once( self, script_dir: Path ): From c3309c452223d604cd73867c963dc47bba2e057c Mon Sep 17 00:00:00 2001 From: Robert Ursu Date: Thu, 26 Nov 2026 10:37:57 +0200 Subject: [PATCH 6/6] chore(uipath): bump to 2.15.12 main released 2.15.11. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fmj9j6BHFgyskAHtyrUX7i --- packages/uipath/pyproject.toml | 2 +- packages/uipath/uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/uipath/pyproject.toml b/packages/uipath/pyproject.toml index ce4a99f01..0a6d27d87 100644 --- a/packages/uipath/pyproject.toml +++ b/packages/uipath/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath" -version = "2.15.11" +version = "2.15.12" description = "Python SDK and CLI for UiPath Platform, enabling programmatic interaction with automation services, process management, and deployment tools." readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index 183f4f134..da98e5923 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2720,7 +2720,7 @@ wheels = [ [[package]] name = "uipath" -version = "2.15.11" +version = "2.15.12" source = { editable = "." } dependencies = [ { name = "applicationinsights" },