Skip to content

Instantly share code, notes, and snippets.

@youtux
Created December 18, 2025 15:19
Show Gist options
  • Select an option

  • Save youtux/ed1da3d45ebd03a57a3b414d9abfed2a to your computer and use it in GitHub Desktop.

Select an option

Save youtux/ed1da3d45ebd03a57a3b414d9abfed2a to your computer and use it in GitHub Desktop.
Fixing slow pydevd_pep_669_tracing - py_raise_callback
Subject: [PATCH] Add O(1) _is_top_level_frame() check to avoid stack walking
---
Index: _pydevd_bundle/pydevd_pep_669_tracing.py
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/_pydevd_bundle/pydevd_pep_669_tracing.py b/_pydevd_bundle/pydevd_pep_669_tracing.py
--- a/_pydevd_bundle/pydevd_pep_669_tracing.py (revision 20ca0a6613a48dd84e62ed92bd182b042788e7cb)
+++ b/_pydevd_bundle/pydevd_pep_669_tracing.py (revision 078dd18b21e4c6d7e88a3cfb921a0f37f0c515d9)
@@ -347,6 +347,16 @@
# ENDIF
+def _is_top_level_frame(frame):
+ """Check if frame is a top-level entry point (O(1) instead of walking stack)."""
+ name = splitext(basename(frame.f_code.co_filename))[0]
+ if name == 'pydevd' and frame.f_code.co_name == '_exec':
+ return True
+ if name == 'threading' and frame.f_code.co_name == '_bootstrap_inner':
+ return True
+ return False
+
+
def _get_top_level_frame():
f_unhandled = _getframe()
@@ -878,7 +888,7 @@
return
frame = _getframe(1)
- if frame is _get_top_level_frame():
+ if _is_top_level_frame(frame):
_stop_on_unhandled_exception(exc_info, py_db, thread)
return
@youtux
Copy link
Author

youtux commented Dec 18, 2025

Add O(1) _is_top_level_frame() check to avoid stack walking

Instead of walking the entire call stack on every exception to find
the top-level frame and comparing, directly check if the given frame
is a top-level entry point by examining its properties.

This eliminates ~250K stack walks that were taking ~7.7s total (in an internal project benchmark).

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