Repository navigation
gh-140815: Fix faulthandler for invalid/freed frame - #140921
Conversation
faulthandler now detects if a frame or a code object is invalid or freed. Add helper functions: * _PyCode_SafeAddr2Line() * _PyFrame_SafeGetCode() * _PyFrame_SafeGetBytecode() * _PyFrame_SafeGetLasti() _PyMem_IsPtrFreed() now also considers the pointer 0x1 as freed.
|
I believe this PR minimizes the chances of getting a segfault. However, I have a feeling that it does not eliminate the possibility entirely. Unfortunately, I don't have a better solution. |
|
Perhaps we could add a new function that attempts to attach the thread state with a timeout. If successful, we will have a more reliable solution. WDYT? |
I don't think that it's worth it. Another faulthandler feature is faulthandler is a debugger, it's not designed to be 100% accurate, but to "just work" in any case (GIL or not, in a signal handler or not, etc.) without taking any lock. |
|
@sergey-miryanov @picnixz: I pushed a change to address your reviews. |
|
LGTM, but I have very little expertise here, so I'll not push approve button :-). |
faulthandler is implemented with multiple heuristics and best effort. It's ok if it does crash, since it should only be triggered when something already goes wrong. Only |
sergey-miryanov
left a comment
There was a problem hiding this comment.
From point of my little experience, it looks good to me.
|
Thanks! |
| if (_PyMem_IsPtrFreed(ptr)) { | ||
| return NULL; | ||
| } | ||
| PyObject *executable = PyStackRef_AsPyObjectBorrow(f->f_executable); | ||
| if (_PyObject_IsFreed(executable)) { |
There was a problem hiding this comment.
Does this patch work on release builds? I thought _PyMem_IsPtrFreed and _PyObject_IsFreed only worked if debug allocators are enabled.
There was a problem hiding this comment.
Oh. I didn't try on a release build! _PyMem_IsPtrFreed() and _PyObject_IsFreed() work better with debug allocators, you're correct. But they detect freed (reused) memory in some cases in a release build as well. They are just less reliable in release mode.
I pushed more changes to make the heuristics stricter.
|
@picnixz @ZeroIntensity: Do these changes look reasonable to you? Even if they are not perfect, they allow dumping the traceback in more cases. I wrote a script to run the reproducer in a loop (see below). I ran the stress test 3 times.
Stress test: import subprocess, sys
cmd=[sys.executable, 'reproducer.py']
success = 0
while True:
proc = subprocess.run(cmd)
if proc.returncode != 1:
print()
print(f"Exitcode {proc.returncode}")
break
success += 1
print(success)
import faulthandler
import sys
faulthandler.dump_traceback_later(10 * 1e-308, exit=True, file=sys.__stderr__)
assert False |
ZeroIntensity
left a comment
There was a problem hiding this comment.
I think this is a good idea anyway, yeah. We might want to document that faulthandler.dump_traceback_later can sometimes crash during interpreter finalization.
| // Similar to _PyFrame_GetCode(), but return NULL if the frame is invalid or | ||
| // freed. Used by dump_frame() in Python/traceback.c. |
There was a problem hiding this comment.
It might be worth adding a comment that this isn't completely reliable.
There was a problem hiding this comment.
Good idea. I added a sentence for that in the 3 added functions.
|
Merged, thanks for your reviews! |
|
Thanks @vstinner for the PR 🌮🎉.. I'm working now to backport this PR to: 3.14. |
…40921) faulthandler now detects if a frame or a code object is invalid or freed. Add helper functions: * _PyCode_SafeAddr2Line() * _PyFrame_SafeGetCode() * _PyFrame_SafeGetLasti() _PyMem_IsPtrFreed() now detects pointers in [-0xff, 0xff] range as freed. (cherry picked from commit a84181c) Co-authored-by: Victor Stinner <vstinner@python.org>
|
GH-140981 is a backport of this pull request to the 3.14 branch. |
|
GH-140985 is a backport of this pull request to the 3.13 branch. |
) faulthandler now detects if a frame or a code object is invalid or freed. Add helper functions: * _PyCode_SafeAddr2Line() * _PyFrame_SafeGetCode() * _PyFrame_SafeGetLasti() _PyMem_IsPtrFreed() now detects pointers in [-0xff, 0xff] range as freed. (cherry picked from commit a84181c)
#140981) gh-140815: Fix faulthandler for invalid/freed frame (GH-140921) faulthandler now detects if a frame or a code object is invalid or freed. Add helper functions: * _PyCode_SafeAddr2Line() * _PyFrame_SafeGetCode() * _PyFrame_SafeGetLasti() _PyMem_IsPtrFreed() now detects pointers in [-0xff, 0xff] range as freed. (cherry picked from commit a84181c) Co-authored-by: Victor Stinner <vstinner@python.org>
…140985) gh-140815: Fix faulthandler for invalid/freed frame (#140921) faulthandler now detects if a frame or a code object is invalid or freed. Add helper functions: * _PyCode_SafeAddr2Line() * _PyFrame_SafeGetCode() * _PyFrame_SafeGetLasti() _PyMem_IsPtrFreed() now detects pointers in [-0xff, 0xff] range as freed. (cherry picked from commit a84181c)
Summary: This diff adds a patch to the `third-party/python/3.12` Meta-internal fork. It backports the trampoline-frame part of the upstream gh-140815 fix to fix a crash in `faulthandler`'s traceback dump. Upstream fixed this in main, 3.14 and 3.13, but not in 3.12, which only takes security fixes. Upstream: - 3.13 backport: python/cpython#140985 - 3.14 backport: python/cpython#140981 (shipped in 3.14.1, already in `third-party/python/3.14`) - main: python/cpython#140921 - issue: python/cpython#140815 The hunks were checked against the 3.14 backport in `third-party/python/3.14/pristine/Python/traceback.c` rather than the 3.13 PR diff. **Problem** A `__del__` that runs while a frame called from C (e.g. by `map()`) is being popped sees two `FRAME_OWNED_BY_CSTACK` shim frames in a row, because a frame is unlinked before it is cleared (GH-99729). `dump_traceback()` skips only one shim and passes the second to `dump_frame()`: - Debug builds fail `assert(frame->owner != FRAME_OWNED_BY_CSTACK)`. - Release builds call `PyUnstable_InterpreterFrame_GetLine()` on the shim. Meta's `_PyFrame_EnsureFrameFullyInitialized()` then reads the shim's `f_funcobj`, which release builds leave uninitialized, and crashes with SIGSEGV. This killed rank 90 of f1134899418. The stuck-job detector's stack-dump signal arrived while a finalizer was in this state, and the dump died right after printing `File "<shim>"`. **Fix** Same as upstream: `dump_frame()` ignores trampoline frames, and the one-shim skip in the `dump_traceback()` loop is removed along with its assert. Adapted to 3.12: - the owner is still `FRAME_OWNED_BY_CSTACK` (3.14 renamed it `FRAME_OWNED_BY_INTERPRETER`); - `dump_frame()` stays `void`, so the early return is `return;` instead of `return 0;`. As upstream, shims now count toward `MAX_FRAME_DEPTH`. The rest of gh-140815 (`_PyFrame_SafeGetCode()`, `_PyFrame_SafeGetLasti()`, `_PyCode_SafeAddr2Line()`, `<freed frame>` / `<invalid frame>`) is not backported. Its frame validation needed a CinderX JIT-frame adaptation in 3.14 (`third-party/python/3.14/patches/21-jit-frame-safe-get-code`) and would need a separate one for 3.12. Upstream added no test for this, so `test_dump_traceback_consecutive_shims` is Meta-local. Reviewed By: itamaro Differential Revision: D121622997 fbshipit-source-id: 7315ccecef7e3432116334db435a0c62a201b332
…publication ## Summary Address all 35 grouped findings from the explicitly authorized additional targeted review of PR #1545, together with the independently reproduced CI diagnostic crash. Preserve public defaults and the unchanged OSS ROUGE test. This maintains the existing consolidation PR; no new feature task is created. The PR retains its python and github_actions labels. ## Prompting Intent The engineer requested another review-code review, fixes for verified issues, and continued work toward human merge approval. The engineer explicitly authorized one additional targeted cycle, increasing the same High run's follow-up limit from one to two. Preserve earlier evidence, keep new review reports out of commits, retain optional Fabric behavior and public installs, and do not claim a clean review when required evidence is missing. ## Linked Sources - Consolidation requirements and review context: #1545 - Reviewed public head: 630f30c - Reviewed public base: f2427d8 - Previous hosted validation: https://github.com/microsoft/FLAML/actions/runs/45697958897 - Original Windows diagnostic crash: https://github.com/microsoft/FLAML/actions/runs/45697958897/job/139500224772 - Upstream traceback-dumper race: python/cpython#140815 - Upstream frame-validation fix: python/cpython#140921 - Driving instructions and session-only review evidence: Copilot session b0e4942d-f489-4b42-8a90-097ede4e88f7 ## Rationale Associate Tune results and MLflow runs by trial identity instead of timestamps or compacted positions. Preserve explicit driver lineage above unrelated worker runs, handle returned and report-style results, finalize adoption once, and preserve original errors. Register each model version from its own nested run. Refused final publication stays a visible failure, and completed model futures are observed and released once. Store forecast training boundaries in new log records and avoid unused CV splits during full-data replay. Preserve panel group keys and custom integer index names, normalize validation and serving timestamps, propagate detached feature-refit metadata, and learn replacement target decoders. TFT itself is excluded from generic AutoFE; its predictor validates future coordinates and uses backend keys to restore caller order rather than relabeling horizons. Revisit the previously retained near-integer heuristic after reproducing actual measurement loss. Require exact source integrality and decimal round trips, including tiny and ordinary-magnitude fractions. Widen sampled integer candidates safely, retaining malformed-value and signed-range behavior. Distributed label counts remain distributed without importing Spark locally. Use ordered v4 publication archives and revision-aware cached module aliases. Code reverts and unordered late-worker archive lists now select the correct implementation while old pickles retain immutable revision identities. Cache writes publish atomically, tests use owned cache paths, and genuine network unavailability is skipped explicitly instead of hiding corruption. The notebook smoke is bounded and still performs real fitting and reload. Standalone controls on the CI Python/pandas/Arrow versions reproduced native access violations only when the timed traceback dumper was enabled, without importing FLAML. Disable that watchdog only for Windows Python 3.11; retain fatal-error reporting, every test, and the existing 180-minute CI limit. The frozen candidate passed 895 affected tests and 20 subtests with 12 skips, 56 offline NLP tests, all four isolated installed profiles, 33 real Spark dtype cases, distributed-label checks, real TFT training/prediction, and real Ray returned/report-style trials in manual/autolog modes. Wheel and sdist contain the exact 99 library Python files and no review outputs. All-file pre-commit and actionlint passed. Fresh hosted container/platform checks are still required; the additional review retained four issues_found responses and one failed empty-response lens, not a clean independent sign-off. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b0e4942d-f489-4b42-8a90-097ede4e88f7
faulthandler now detects if a frame or a code object is invalid or freed.
Add helper functions:
_PyMem_IsPtrFreed() now also considers the pointer 0x1 as freed.
faulthandler.dump_traceback_later#140815