Skip to content

Step Out / Step Over never stops when the stepped function is left by an exception (sys.monitoring tracer, Python 3.12+) #2100

Backlog

Description

@debugmcpdev

Environment data

  • debugpy version: 1.8.22 (the current release). The code involved is unchanged on main at 7764458.
  • OS and version: Windows 11 x64
  • Python version (& distribution if applicable, e.g. Anaconda): CPython 3.13.12 (python.org installer), and CPython 3.12.13 and 3.14.5 (python-build-standalone builds, installed with uv). Each was a fresh venv holding only debugpy. pydevd loaded its compiled sys.monitoring tracer (_pydevd_sys_monitoring_cython) on all three. The pure-Python tracer (PYDEVD_USE_CYTHON=NO) behaves the same.
  • Using VS Code or Visual Studio: not run in VS Code. I reproduced it with a minimal DAP client that talks to python -m debugpy.adapter and nothing else (the exchange is below). The steps below are what a VS Code user does with the default "Python Debugger: Current File" configuration (justMyCode on, "Uncaught Exceptions" checked).

I found this while building mcp-debugger, an MCP server that drives debuggers. It is tracked there as debugmcp/mcp-debugger#1194, which also has a Linux run (Python 3.14, debugpy 1.8.22).

Actual behavior

At a breakpoint on raise, Step Out (Shift+F11) or Step Over (F10) never stops. The stepOut/next request succeeds and continued is sent, but no stopped event follows. The rest of the program runs and the session ends with exited {"exitCode": 0}.

Step Over or Step Out from the finally body on line 9 does the same while the exception is propagating. So does the second F10 of "breakpoint on line 7, F10, F10". Unchecking every exception filter changes nothing. Step Into from line 2 stops correctly, on line 9.

Expected behavior

The step stops in the next frame that runs, still inside the call where i == 1. From line 2 that is cleanup_thrower (line 7 or 9). From line 9 it is via_throw (line 14 or 15).

The sys.settrace tracer does this. With PYDEVD_USE_SYS_MONITORING=0 in the debuggee's environment, on the same three interpreters:

  • Step Out from line 2 stops at line 7.
  • Step Over from line 2 stops at line 9.
  • Step Over from line 9 stops at line 15.
  • Step Out from line 9 stops at line 14.

Steps to reproduce:

raise_out.py:

def thrower(i):
    raise ValueError(i)  # line 2


def cleanup_thrower(i):
    try:
        thrower(i)  # line 7
    finally:
        print("finally", i)  # line 9


def via_throw(i):
    try:
        cleanup_thrower(i)  # line 14
    except ValueError:  # line 15
        return i * 2  # line 16
    return -1


for i in range(3):
    print("call", i, "->", via_throw(i))
print("done")
  1. Set a breakpoint on line 2 with the condition i == 1. The condition matters: without it the breakpoint is hit again in the next iteration, which hides the lost step.
  2. F5 with "Python Debugger: Current File". It stops on line 2 with i = 1, after printing finally 0 and call 0 -> 0.
  3. Shift+F11 (Step Out), or F10 (Step Over).
  4. Nothing stops. The program prints finally 1, call 1 -> 2, finally 2, call 2 -> 4 and done, then exits.

Results, one fresh session per run, each row with exception filters ["uncaught"] and with []:

breakpoint (i == 1) step 1.8.22 as released PYDEVD_USE_SYS_MONITORING=0 with the patch below
line 2 stepOut no stop, program ends cleanup_thrower line 7 cleanup_thrower line 9
line 2 next no stop, program ends line 9 line 9
line 9 next no stop, program ends via_throw line 15 line 15
line 9 stepOut no stop, program ends via_throw line 14 line 15
line 7 next, next line 9, then no stop line 9, line 15 line 9, line 15
line 2 stepIn line 9 line 7 line 9

Runs per column:

  • 1.8.22 as released: 3 runs of 3 on each of 3.12.13, 3.13.12 and 3.14.5.
  • =0: 3 of 3 on 3.13, 1 run per row on 3.12 and 3.14.
  • Patch: the pure-Python tracer on all three (3 of 3 on 3.13, 1 run on 3.12 and 3.14), and the compiled tracer on 3.13 only (3 of 3).
DAP exchange (1.8.22, Python 3.13.12, the Step Out row; paths shortened)
-> request  initialize {"clientID": "bare-dap", "adapterID": "debugpy", "linesStartAt1": true, "columnsStartAt1": true, "pathFormat": "path", "supportsRunInTerminalRequest": false}
<- response initialize success=True {...capabilities...}
-> request  launch {"name": "repro", "type": "debugpy", "request": "launch", "program": "C:\\repro\\raise_out.py", "cwd": "C:\\repro", "console": "internalConsole", "justMyCode": true, "python": ["python"], "env": {}}
<- event    initialized
-> request  setBreakpoints {"source": {"path": "C:\\repro\\raise_out.py"}, "breakpoints": [{"line": 2, "condition": "i == 1"}]}
<- response setBreakpoints success=True {"breakpoints": [{"verified": true, "id": 0, "source": {"path": "C:\\repro\\raise_out.py"}, "line": 2}]}
-> request  setExceptionBreakpoints {"filters": ["uncaught"]}
<- response setExceptionBreakpoints success=True
-> request  configurationDone
<- response configurationDone success=True
<- response launch success=True
<- event    thread {"reason": "started", "threadId": 1}
<- event    output {"category": "stdout", "output": "finally"}
<- event    stopped {"reason": "breakpoint", "threadId": 1, "preserveFocusHint": false, "allThreadsStopped": true, "hitBreakpointIds": [0]}
-> request  stackTrace {"threadId": 1, "levels": 20}
<- event    output {"category": "stdout", "output": " 0\ncall 0 -> 0\n"}
<- response stackTrace success=True [thrower:2, cleanup_thrower:7, via_throw:14, <module>:21]
-> request  stepOut {"threadId": 1}
<- response stepOut success=True
<- event    output {"category": "stdout", "output": "finally"}
<- event    output {"category": "stdout", "output": " 1\ncall 1 -> 2\n"}
<- event    continued {"threadId": 1, "allThreadsContinued": true}
<- event    output {"category": "stdout", "output": "finally 2\ncall 2 -> 4\ndone\n"}
<- event    exited {"exitCode": 0}
-> request  disconnect {"terminateDebuggee": true}
<- event    terminated
<- response disconnect success=True

The same exchange with the patch below applied:

-> request  stepOut {"threadId": 1}
<- response stepOut success=True
<- event    continued {"threadId": 1, "allThreadsContinued": true}
<- event    stopped {"reason": "step", "threadId": 1, "preserveFocusHint": false, "allThreadsStopped": true}
-> request  stackTrace {"threadId": 1, "levels": 20}
<- response stackTrace success=True [cleanup_thrower:9, via_throw:14, <module>:21]

Cause

Under sys.monitoring, a function left by an exception gets PY_UNWIND and never gets PY_RETURN. Under sys.settrace the same exit arrives as a return event with arg=None. I checked this with a small script that registers both APIs, on 3.12, 3.13 and 3.14.

References below are to src/debugpy/_vendored/pydevd/_pydevd_sys_monitoring/_pydevd_sys_monitoring.py at v1.8.22:

  • _return_event, the PY_RETURN callback, is where a step whose frame exits gets handed on ("If we are in single step mode and something causes us to exit the current frame, we need to make sure we break eventually"). It switches the step to step-into and clears pydev_step_stop.
  • _unwind_event, the PY_UNWIND callback, only handles exception breakpoints. It never reads pydev_step_cmd or pydev_step_stop, so the step stays anchored on a frame that will never run another line or return. A Step Out also arms only PY_RETURN for that code object (L871-L872).
  • update_monitor_events registers _unwind_event only while an exception filter is set. With no filter, PY_UNWIND is not delivered at all.
  • The sys.settrace tracer does not have the gap. There the exit is a return event and takes the same hand-over (pydevd_frame.py L480-L500).

_unwind_event, _return_event and update_monitor_events are identical in microsoft/debugpy main (7764458) and in fabioz/PyDev.Debugger main (d6bc5f50cc31).

Possible fix

There are two hunks. The first hands the step on in _unwind_event, the way _return_event does. The second delivers PY_UNWIND while a thread is suspended or stepping, even when no exception filter is set. Line numbers are those of v1.8.22:

--- a/src/debugpy/_vendored/pydevd/_pydevd_sys_monitoring/_pydevd_sys_monitoring.py
+++ b/src/debugpy/_vendored/pydevd/_pydevd_sys_monitoring/_pydevd_sys_monitoring.py
@@ -913,6 +913,8 @@ class _TryExceptContainerObj:
 # cdef _unwind_event(code, instruction, exc):
 #     cdef ThreadInfo thread_info
 #     cdef FuncCodeInfo func_code_info
+#     cdef PyDBAdditionalThreadInfo info
+#     cdef int step_cmd
 # ELSE
 def _unwind_event(code, instruction, exc):
 # ENDIF
@@ -941,6 +943,20 @@ def _unwind_event(code, instruction, exc):
     frame = _getframe(1)
     arg = (type(exc), exc, exc.__traceback__)
 
+    # A pending step whose frame is left by an exception gets PY_UNWIND, not PY_RETURN: hand it on
+    # the same way _return_event does, so that it stops in the next frame that runs.
+    info = thread_info.additional_info
+    step_cmd = info.pydev_step_cmd
+    if step_cmd in (CMD_STEP_OVER, CMD_STEP_RETURN, CMD_STEP_OVER_MY_CODE, CMD_STEP_RETURN_MY_CODE, CMD_SMART_STEP_INTO):
+        stop_frame = info.pydev_step_stop
+        if stop_frame is frame and not info.pydev_use_scoped_step_frame:
+            if step_cmd in (CMD_STEP_OVER, CMD_STEP_RETURN, CMD_SMART_STEP_INTO):
+                info.pydev_step_cmd = CMD_STEP_INTO
+            else:
+                info.pydev_step_cmd = CMD_STEP_INTO_MY_CODE
+            info.pydev_step_stop = None
+            _enable_code_tracing_for_frame_and_parents(thread_info, stop_frame.f_back)
+
     has_caught_exception_breakpoint_in_pydb = (
         py_db.break_on_caught_exceptions or py_db.break_on_user_uncaught_exceptions or py_db.has_plugin_exception_breaks
     )
@@ -1977,7 +1993,12 @@ def update_monitor_events(suspend_requested: Optional[bool]=None) -> None:
             monitor.register_callback(DEBUGGER_ID, monitor.events.PY_UNWIND, _unwind_event)
         else:
             monitor.register_callback(DEBUGGER_ID, monitor.events.RAISE, None)
-            monitor.register_callback(DEBUGGER_ID, monitor.events.PY_UNWIND, None)
+            if suspend_requested:
+                # A pending step must be handed on when its frame is left by an exception.
+                required_events |= monitor.events.PY_UNWIND
+                monitor.register_callback(DEBUGGER_ID, monitor.events.PY_UNWIND, _unwind_event)
+            else:
+                monitor.register_callback(DEBUGGER_ID, monitor.events.PY_UNWIND, None)
 
     has_breaks = py_db.has_plugin_line_breaks
     if not has_breaks:

What I tested, against the program above:

  • The patch on the pure-Python tracer (PYDEVD_USE_CYTHON=NO). Every row of the table stops: 3.13.12 3 runs of 3, 3.12.13 and 3.14.5 1 run each, with filters ["uncaught"] and [].
  • The same change applied by hand to _pydevd_sys_monitoring_cython.pyx (with the step constants as the numbers the generator emits), built with Cython 3.2.4 and MSVC on 3.13.12. Every row stops, 3 runs of 3, with both filter settings.
  • The first hunk alone fixes every row with the uncaught filter (VS Code's default). From the source, the same should hold for any filter, since _unwind_event is registered whenever one is set; I only measured uncaught. With no filter the step is still lost, and the second hunk fixes that case.
  • Not run: the debugpy and pydevd test suites.
  • Regeneration: the .pyx and .c need regenerating from the .py (build_tools/build.py).
  • Cost of the second hunk (from reading the code, not measured): it registers _unwind_event whenever update_monitor_events sees a thread suspended or stepping, not only for a step. It stays registered until the next call recomputes it, so a program that raises a lot pays one callback per unwound frame in that window. Registering it on the step request instead, and dropping it when the step completes, would avoid that.

Workaround until then: PYDEVD_USE_SYS_MONITORING=0 in the debuggee's environment keeps these steps, at the cost of the sys.settrace tracer's overhead: on Python 3.13.12, a loop of 10M calls to a small function took a median of 2.26 s with it, against 0.38 s under the default tracer and 0.37 s with no debugger (5 runs each, one breakpoint in a function that is never called).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions