Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/uipath/pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
26 changes: 25 additions & 1 deletion packages/uipath/src/uipath/functions/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
137 changes: 136 additions & 1 deletion packages/uipath/tests/functions/test_debug_breakpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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)
2 changes: 1 addition & 1 deletion packages/uipath/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading