Slide 1

Slide 1 text

Python 3.12's new monitoring and debugging API Johannes Bechberger SapMachine

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

If debugging is the process of removing software bugs, then programming must be the process of putting them in. — Edsger Dijkstra “

Slide 4

Slide 4 text

➜ python3 counter.py \ lines counter.py 0

Slide 5

Slide 5 text

➜ python3 counter.py \ lines counter.py 26

Slide 6

Slide 6 text

Let’s look at the code

Slide 7

Slide 7 text

def main(): match cmd !:= sys.argv[1]: case "lines": count = count_code_lines(Path(sys.argv[2])) print(count) case "help": print_help() case _: raise ValueError(f"Unknown operation {cmd}")

Slide 8

Slide 8 text

def is_code_line(line: str) -> bool: return line.isspace() and line.strip().startswith("#") def count_code_lines(file: Path) -> int: count = 0 with file.open('r') as f: for line in f: if is_code_line(line): count += 1 return count

Slide 9

Slide 9 text

Any ideas?

Slide 10

Slide 10 text

Debuggers are your friend

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

Why do we need a monitoring API?

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

Java has built-in debugging support...

Slide 16

Slide 16 text

But Python?

Slide 17

Slide 17 text

Does the interpreter "know" breakpoints?

Slide 18

Slide 18 text

No.

Slide 19

Slide 19 text

Any ideas?

Slide 20

Slide 20 text

def is_code_line(line: str) -> bool: return line.isspace() and line.strip().startswith("# def count_code_lines(file: Path) -> int: count = 0 with file.open('r') as f: for line in f: if is_code_line(line): count += 1 return count dbg(); dbg(); dbg(); dbg(); dbg(); dbg(); dbg();

Slide 21

Slide 21 text

def dbg(): if at_breakpoint(file, line): dbg_shell() ? dbg(); line

Slide 22

Slide 22 text

sys._getframe

Slide 23

Slide 23 text

sys._getframe

Slide 24

Slide 24 text

sys._getframe CPython implementation detail locals(), globals(), sys._getframe(), sys.exc_info(), and sys.settrace work in PyPy, but they incur a performance penalty that can be huge by disabling the JIT over the enclosing JIT scope. “ – https://www.pypy.org/performance.html

Slide 25

Slide 25 text

main count_code_lines is_code_line dbg sys._getframe(0) sys._getframe(1) …

Slide 26

Slide 26 text

main count_code_lines is_code_line dbg sys._getframe(0) sys._getframe(1) f_back f_lineno 6 f_globals !!... f_locals {'line': 'import sys\n'} f_code. co_filename counter.py

Slide 27

Slide 27 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell() dbg(); line

Slide 28

Slide 28 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) dbg(); line

Slide 29

Slide 29 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) dbg(); line

Slide 30

Slide 30 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line

Slide 31

Slide 31 text

But how do we automate this?

Slide 32

Slide 32 text

The pre-3.12 way

Slide 33

Slide 33 text

sys.settrace

Slide 34

Slide 34 text

sys.settrace(handler) Event = Union['call', 'line', 'return', 'exception', 'opcode'] def handler(frame: FrameType, event: Event, arg): pass

Slide 35

Slide 35 text

def is_code_line(line: str) -> bool: return line.isspace() and line.strip().startswith("#") def count_code_lines(file: Path) -> int: count = 0 with file.open('r') as f: for line in f: if is_code_line(line): count += 1 return count handler(frame, 'call', None) handler(frame, 'call', None)

Slide 36

Slide 36 text

sys.settrace(handler) def inner_handler(frame: FrameType, event: str, arg): pass def handler(frame: FrameType, event: Event, arg) \ -> Optional[Callable[[FrameType, Event, Any], None]]: return inner_handler

Slide 37

Slide 37 text

sys.settrace(handler) def inner_handler(frame: FrameType, event: Event, arg): pass def handler(frame: FrameType, event: Event, arg) \ -> Optional[Callable[[FrameType, Event, Any], None]]: return inner_handler

Slide 38

Slide 38 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line

Slide 39

Slide 39 text

def inner_handler(frame: FrameType, event: str, arg): if event !!= 'line': return line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line

Slide 40

Slide 40 text

def inner_handler(frame: FrameType, event: str, arg): if event !!= 'line': return line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line

Slide 41

Slide 41 text

Single Stepping

Slide 42

Slide 42 text

main:25 count_code_lines:13 is_code_line:6 main:25 count_code_lines:12 step out Just extend at_breakpoint

Slide 43

Slide 43 text

main:25 count_code_lines:12 main:25 count_code_lines:13 step Just extend at_breakpoint

Slide 44

Slide 44 text

main:25 count_code_lines:12 main:25 count_code_lines:13 step into is_code_line:6 Just extend at_breakpoint

Slide 45

Slide 45 text

Do we get line events for every function?

Slide 46

Slide 46 text

def is_code_line(line: str) -> bool: return line.isspace() and line.strip().startswith("#") def count_code_lines(file: Path) -> int: count = 0 with file.open('r') as f: for line in f: if is_code_line(line): count += 1 return count handler(frame, …, None) add breakpoint handler(frame, 'call', None)

Slide 47

Slide 47 text

This is slow, so...

Slide 48

Slide 48 text

Add a new API Python 3.12 and PEP 669

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

# some aliases and constants mon = sys.monitoring E = mon.events TOOL_ID = mon.DEBUGGER_ID # register the tool mon.use_tool_id(TOOL_ID, "dbg") Register Tool

Slide 51

Slide 51 text

# some aliases and constants mon = sys.monitoring E = mon.events TOOL_ID = mon.DEBUGGER_ID # register the tool mon.use_tool_id(TOOL_ID, "dbg") # register callbacks for the events we are interested in mon.register_callback(TOOL_ID, E.LINE, line_handler) mon.register_callback(TOOL_ID, E.PY_START, start_handler) def start_handler(code: CodeType, offset: int): pass def line_handler(code: CodeType, line: int) -> DISABLE|Any: pass disable till mon.restart_even Register Tool Register Callbacks Enable PY_START events

Slide 52

Slide 52 text

# some aliases and constants mon = sys.monitoring E = mon.events TOOL_ID = mon.DEBUGGER_ID # register the tool mon.use_tool_id(TOOL_ID, "dbg") # register callbacks for the events we are interested in mon.register_callback(TOOL_ID, E.LINE, line_handler) mon.register_callback(TOOL_ID, E.PY_START, start_handler) def start_handler(code: CodeType, offset: int): pass def line_handler(code: CodeType, line: int) -> DISABLE|Any: pass disable till mon.restart_events()

Slide 53

Slide 53 text

# some aliases and constants mon = sys.monitoring E = mon.events TOOL_ID = mon.DEBUGGER_ID # register the tool mon.use_tool_id(TOOL_ID, "dbg") # register callbacks for the events we are interested in mon.register_callback(TOOL_ID, E.LINE, line_handler) mon.register_callback(TOOL_ID, E.PY_START, start_handler) # enable PY_START event globally mon.set_events(TOOL_ID, E.PY_START) # Later mon.set_local_events(TOOL_ID, code, E.LINE) Enable LINE events in func PY_START for every func run program has breakpoint? LINE for every line run function emitted per thread, not per interpreter

Slide 54

Slide 54 text

The biggest opportunity of PEP 669 isn't even the speed, it's the fact that a debugger built on top of it will automatically support all threads. — Łukasz Langa “ https://github.com/python/cpython/issues/103103#issuecomment-1488312628

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

Globally set events Locally set events Enabled events per function

Slide 57

Slide 57 text

The power is in the fine- grained configuration

Slide 58

Slide 58 text

You can set events in f for f

Slide 59

Slide 59 text

def line_handler(code: CodeType, line_number: int): print(f" {code.co_name}: {line_number}") mon.register_callback(tool_id, E.LINE, line_handler) def f(): print("hello") mon.set_local_events(tool_id, f.!__code!__, E.LINE) print("inner") mon.set_local_events(tool_id, f.!__code!__, 0) print("end") f() # Output hello f: 18 inner f: 19 end

Slide 60

Slide 60 text

What's fast?

Slide 61

Slide 61 text

register_callback get_tool set_local_events use_tool_id set_events Fast Rather fast Slow The earlier the faster

Slide 62

Slide 62 text

Back to the debugger

Slide 63

Slide 63 text

def start_handler(code: CodeType, _: int): # !!... handle first call file = Path(code.co_filename).stem if has_breakpoint(file, code.co_firstlineno, len(list(code.co_lines()))): print(f"enable line events for {code.co_name}") enable_line_events(code) print(f"start {code.co_name}")

Slide 64

Slide 64 text

def line_handler(code: CodeType, line: int): print(f"line {line} in {code.co_name}") if at_breakpoint(code.co_name, line): print(f"in break point at line {line}") dbg_shell(sys._getframe(1))

Slide 65

Slide 65 text

Event kinds Local Events PY_START PY_RESUME PY_RETURN PY_YIELD CALL LINE INSTRUCTION JUMP BRANCH STOP_ITERATION Ancillary Events PY_START C_RAISE C_RETURN PY_YIELD CALL LINE INSTRUCTION JUMP BRANCH STOP_ITERATION Other Events PY_START PY_RAISE PY_UNWIND PY_THROW EXCEPTION_ HANDLED LINE JUMP BRANCH STOP_ITERATION controls not tied to specific location

Slide 66

Slide 66 text

Performance Hacking pyperformance for fun and profit...

Slide 67

Slide 67 text

def line_handler(*args): pass def start_handler(*args): pass mon.use_tool_id(TOOL_ID, "dbg") mon.register_callback(!!...) mon.set_events(TOOL_ID, E.PY_START) def inner_handler(*args): pass def handler(*args): return inner_handler sys.settrace(handler) sys.settrace monitoring vs vs mon.set_events(TOOL_ID, E.PY_START | E.LINE)

Slide 68

Slide 68 text

modified version: https://github.com/parttimenerd/pyperformance/tree/dbg

Slide 69

Slide 69 text

sys.settrace monitoring vs 3.5x runtime 1.2x runtime vs 2.7x runtime

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

Is it used?

Slide 72

Slide 72 text

not yet in pdb but IDEs like PyCharm 2023.3 use it

Slide 73

Slide 73 text

“ After #103082, we will have the chance to build a much faster debugger. For breakpoints, we do not need to trigger trace function all the time and checking for the line number. [...] The bad news is - it's almost impossible to do a completely backward compatible transition because the mechanism is quite different. — Tian Gao “ https://github.com/python/cpython/issues/103103#issue-1644836791

Slide 74

Slide 74 text

@parttimen3rd on Twitter parttimenerd on GitHub mostlynerdless.de @SweetSapMachine sapmachine.io