fix(profiling): memalloc obj domain module finalizer #20608
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #20608"
general
weight: 0.35
gyuheon0h
Description
While looking at crash reports, I saw a series of crash reports that look like such: https://app.datadoghq.com/error-tracking/issue/4fe0aa66-5607-11f1-b89e-da7ad0900002?query=version%3A4.15.2&et-issue__error-sample-viz=sample&refresh_mode=sliding&from_ts=1789393982142&to_ts=1790603582142&live=true
The crashes are in the memalloc profiler's allocator hook lifecycle caused SIGSEGV crashes in gunicorn/gevent workers (observed as SI_KERNEL at
alloc.malloc(alloc.ctx, ...)inmemalloc_alloc).From looking at the code, I saw that there was no module finalizer so hooks outlive the interpreter
PyModuleDefhad nom_freecallback. When a process such as a gevent worker exits without the Python-level collector callingstop()explicitly, the OBJ and MEM hooks remain installed throughPy_Finalize(). CPython then tears down its internal allocator state, and any allocation that reaches the hook callsalloc.malloc(alloc.ctx, ...)with a stale context which will fault.I added
g_saved_alloc_pub.store(nullptr)instop()to match the MEM domain, and registermemalloc_module_freeasm_freeinPyModuleDefto always uninstall hooks during module deallocation.Testing
Its hard to write a deterministic test for this as waiting on GC to do what it does with module unload is not deterministic.I added a test-only helper
_test_invoke_module_freethat exposes them_freepath directly to Python and added this regression test:test_m_free_uninstalls_hooks_deterministicNot the biggest fan of writing API just for testing but 🤷
Risks
Low IMO
PyMem_SetAllocatoris a plain struct copy with no heap allocation, safe to call at any shutdown stage.memalloc_heap_tracker_deinit_no_cpythonfrees C++ objects without calling any CPython API.Additional Notes
I used AI to write the test following my directions.