python / python/cpython

Improve traceability of assertion errors in common functions

未关闭
#130,454 24 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

interpreter-core type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Feature request

(By @picnizx)

While the C API docs explicitly state that functions should usually not be called with an exception set, else some assertion errors may occur and/or the thread state may be invalid, this means that assert(!PyErr_Occurred()) in common macros / functions such as _PyType_LookupRef would just crash. However, in a CI scenario, without a debugger, it's extremely hard to pinpoint the actual cause.

Related: https://github.com/python/cpython/pull/128159 would give the possibility to show the C stack trace with -X faulthandler.

A crude idea: add assert(!PyErr_Occurred()) inside public common C API functions to be sure that the assertion is checked as well, making debugging a bit easier.


Toy Scenario (original request):

I was working on freethread support for pygame-ce, and I finally need to use a python build with debug symbols, and our atexit-registered quit function was causing SIGABRT to be thrown. This took me a while to figure out. Here's all the code you need to run (or just run python -c "import pygame" since pygame.quit() is atexit-registered).

import pygame
pygame.quit()

Here's the guilty block of code in our codebase:

    funcobj = PyObject_GetAttrString(module, "_internal_mod_quit");

    /* If we could not load _internal_mod_quit, load quit function */
    if (!funcobj)
        funcobj = PyObject_GetAttrString(module, "quit");

    /* Silence errors */
    if (PyErr_Occurred())
        PyErr_Clear();

In the 3.12 docs for PyObject_GetAttrString and PyObject_GetAttr. there's no mention at all that there shouldn't be any exceptions set before calling this function, and it works on release versions of python, so nobody has ever questioned this structure. I'll be making a pull request on our end to clear any exceptions between the first call and second call if needed (or use PyObject_GetOptionalAttrString in 3.13+).

The reason for this issue is that I'm not sure throwing a SIGABRT is the best option here.

gdb backtrace on a debug python 3.13t
[gdb.txt](https://github.com/user-attachments/files/18922524/gdb.txt)
CPython versions tested on:

3.12, 3.13, 3.14

Operating systems tested on:

Linux

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先检查围绕 PyObject_GetAttrString、PyObject_GetAttr、PyErr_Occurred 和 _PyType_LookupRef 的 C API 行为,以及相关的 faulthandler pull request。将文档中记录的前置条件与 pygame 场景中显示的断言失败进行比较。当已确定一种经协商一致的方案,用于改进断言的可追溯性及其预期行为时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, python
领域
api
Issue 类型
功能
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。