From 08a3321b9b2f71a4b905e67337714c4b98ba23d9 Mon Sep 17 00:00:00 2001 From: Rares Popa Date: Wed, 18 Nov 2026 13:12:06 +0200 Subject: [PATCH] fix(functions): keep an attached debugger's breakpoints working on Python < 3.12 The functions debug runtime runs a function on a worker thread with its own sys.settrace hook whenever the entrypoint has a call graph, to emit state events, even when no breakpoints are set. Before Python 3.12, pydevd-based debuggers such as debugpy trace threads through sys.settrace too, so with `uipath run --debug` the runtime replaced the debugger's hook on that thread: breakpoints were verified but never hit, and debugpy warned that sys.settrace() should not be used while debugging. Without breakpoints of our own, skip the call-graph state events while a pydevd trace function is active, so the function runs in the thread the debugger traces. Breakpoints requested through the debug bridge keep the current behavior, and nothing changes from Python 3.12, where debugpy uses sys.monitoring, or under coverage tools. Co-Authored-By: Claude Opus 5.5 --- packages/uipath/pyproject.toml | 2 +- packages/uipath/src/uipath/functions/debug.py | 26 +++- .../tests/functions/test_debug_breakpoints.py | 137 +++++++++++++++++- packages/uipath/uv.lock | 2 +- 4 files changed, 163 insertions(+), 4 deletions(-) diff --git a/packages/uipath/pyproject.toml b/packages/uipath/pyproject.toml index 032d8b139..5133f9bfa 100644 --- a/packages/uipath/pyproject.toml +++ b/packages/uipath/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath" -version = "2.15.2" +version = "2.15.3" 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 e9f67e22f..5906db08c 100644 --- a/packages/uipath/src/uipath/functions/debug.py +++ b/packages/uipath/src/uipath/functions/debug.py @@ -78,6 +78,20 @@ def _format_location(filepath: str, line: int) -> str: return f"{relative}:{line}" +def _is_debugger_tracer(tracer: object) -> bool: + """Return True if *tracer* is the trace function of a pydevd-based debugger. + + debugpy (VS Code) and PyCharm are built on pydevd, which traces threads + through sys.settrace before Python 3.12. Installing our own trace function + on a thread replaces theirs, so their breakpoints are never hit there. From + Python 3.12 debugpy uses sys.monitoring and leaves sys.gettrace() empty. + """ + if tracer is None: + return False + module = getattr(tracer, "__module__", None) or type(tracer).__module__ + return "pydevd" in str(module) + + class BreakpointController: """Synchronises a sys.settrace-instrumented thread with an async stream. @@ -390,7 +404,9 @@ class UiPathDebugFunctionsRuntime: Additionally emits ``UiPathRuntimeStateEvent`` for every function call that appears in the entrypoint's call graph, so the debug bridge can - visualise execution flow through the graph nodes. + visualise execution flow through the graph nodes. Without breakpoints, + these are skipped while a debugger traces the process through + sys.settrace (debugpy before Python 3.12), so its breakpoints still hit. Works for both sync and async user functions — async functions run in a dedicated asyncio event loop on the background thread. @@ -458,6 +474,14 @@ async def stream( # can emit state events even without breakpoints. tracked = self._build_tracked_functions() + # A debugger tracing this thread through sys.settrace (debugpy before + # Python 3.12) would lose the worker thread to our trace function and + # never hit its breakpoints there. Without breakpoints of ours, state + # events are all we would trace, so skip them and leave it in charge. + if tracked and not breakpoints and _is_debugger_tracer(sys.gettrace()): + logger.debug("A debugger traces this thread; skipping state events") + tracked = None + # Nothing to trace → transparent delegation. The controller # path runs delegate.execute() in a background thread with a # new asyncio event loop, so we only use it when there is diff --git a/packages/uipath/tests/functions/test_debug_breakpoints.py b/packages/uipath/tests/functions/test_debug_breakpoints.py index a5a5bced1..e2ed02723 100644 --- a/packages/uipath/tests/functions/test_debug_breakpoints.py +++ b/packages/uipath/tests/functions/test_debug_breakpoints.py @@ -15,12 +15,20 @@ import asyncio import os +import sys +from collections.abc import Iterator +from contextlib import contextmanager from pathlib import Path +from types import FrameType from typing import Any, Literal import pytest -from uipath.functions.debug import BreakpointController, UiPathDebugFunctionsRuntime +from uipath.functions.debug import ( + BreakpointController, + UiPathDebugFunctionsRuntime, + _is_debugger_tracer, +) from uipath.functions.runtime import UiPathFunctionsRuntime from uipath.runtime import ( UiPathBreakpointResult, @@ -112,6 +120,31 @@ def _build_stack( return runtime, bridge +class _FakeDebuggerTracer: + """Stands in for the trace function of a pydevd-based debugger (debugpy, PyCharm).""" + + __module__ = "_pydevd_bundle.pydevd_fake" + + def __init__(self) -> None: + self.called: list[str] = [] + + def __call__(self, frame: FrameType, event: str, arg: Any) -> Any: + if event == "call": + self.called.append(frame.f_code.co_name) + return self + + +@contextmanager +def _traced_by(tracer: _FakeDebuggerTracer) -> Iterator[None]: + """Trace this thread with *tracer*, as a debugger does before Python 3.12.""" + previous = sys.gettrace() + sys.settrace(tracer) + try: + yield + finally: + sys.settrace(previous) + + @pytest.fixture() def script_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: """Temp directory used as cwd so BreakpointController treats scripts as project files.""" @@ -885,3 +918,105 @@ async def test_stream_phase_events_from_functions_runtime(self, script_dir: Path assert result_events[0].output == {"value": 6} finally: await inner.dispose() + + +class TestAttachedDebugger: + """A debugger that traces through sys.settrace (debugpy before Python 3.12).""" + + async def test_debugger_keeps_tracing_the_function(self, script_dir: Path): + """Without breakpoints of ours, the debugger's trace function sees every call.""" + _write_script( + script_dir, + "debugged_helpers.py", + "def helper(n):\n return n * 2\n", + ) + script = _write_script( + script_dir, + "main.py", + "from debugged_helpers import helper\n" + "\n" + "def main(input):\n" + ' return {"result": helper(input["n"])}\n', + ) + runtime, bridge = _build_stack(script, breakpoints=[]) + debugger = _FakeDebuggerTracer() + + try: + with _traced_by(debugger): + result = await runtime.execute({"n": 3}) + + assert result.status == UiPathRuntimeStatus.SUCCESSFUL + assert result.output == {"result": 6} + assert {"main", "helper"} <= set(debugger.called) + finally: + await runtime.dispose() + + async def test_breakpoints_of_ours_still_pause(self, script_dir: Path): + """Breakpoints requested through the debug bridge still pause the function.""" + script = _write_script( + script_dir, + "calc.py", + "def main(input):\n" + ' x = input["value"]\n' + " y = x * 2\n" + ' return {"result": y}\n', + ) + runtime, bridge = _build_stack(script, breakpoints=["3"]) + + try: + with _traced_by(_FakeDebuggerTracer()): + result = await runtime.execute({"value": 4}) + + assert len(bridge.breakpoint_hits) == 1 + assert bridge.breakpoint_hits[0].current_state["x"] == 4 + assert result.output == {"result": 8} + finally: + await runtime.dispose() + + async def test_no_call_graph_state_events_while_a_debugger_traces( + self, script_dir: Path, monkeypatch: pytest.MonkeyPatch + ): + """Call-graph state events need our trace function, so they are skipped.""" + monkeypatch.setattr( + "uipath.functions.debug._is_debugger_tracer", lambda tracer: True + ) + _write_script( + script_dir, + "skipped_helpers.py", + "def helper(n):\n return n + 1\n", + ) + script = _write_script( + script_dir, + "main.py", + "from skipped_helpers import helper\n" + "\n" + "def main(input):\n" + ' return {"result": helper(input["n"])}\n', + ) + runtime, bridge = _build_stack(script, breakpoints=[]) + + try: + result = await runtime.execute({"n": 1}) + + assert result.output == {"result": 2} + assert "helper" not in [s.node_name for s in bridge.state_updates] + finally: + await runtime.dispose() + + def test_recognizes_pydevd_trace_functions(self): + def trace_dispatch(frame: FrameType, event: str, arg: Any) -> None: + return None + + trace_dispatch.__module__ = "_pydevd_bundle.pydevd_trace_dispatch_regular" + + assert _is_debugger_tracer(_FakeDebuggerTracer()) # Cython build: an object + assert _is_debugger_tracer(trace_dispatch) # pure-Python build: a function + + def test_ignores_other_trace_functions(self): + def coverage_tracer(frame: FrameType, event: str, arg: Any) -> None: + return None + + coverage_tracer.__module__ = "coverage.pytracer" + + assert not _is_debugger_tracer(None) + assert not _is_debugger_tracer(coverage_tracer) diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index 2134be71c..3b6c6c5f4 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2599,7 +2599,7 @@ wheels = [ [[package]] name = "uipath" -version = "2.15.2" +version = "2.15.3" source = { editable = "." } dependencies = [ { name = "applicationinsights" },