如何结合 pytest-leaks 检测 C 扩展模块的引用计数泄漏?

解读

在国内一线互联网与量化公司面试中,面试官提出此题,核心想验证三件事:

  1. 你是否真的在“带 C 扩展”的 Python 项目里做过内存质量保障;
  2. 是否理解 Python 的引用计数机制与循环 GC 的边界;
  3. 能否把 pytest 插件生态与底层调试工具串成一条自动化流水线,而不是只会写纯 Python 层的用例。

题目限定“C 扩展模块”,意味着泄漏往往发生在 Py_INCREF / Py_DECREF 配对错误、 borrowed reference 被误用、或者 tp_dealloc 未正确清理成员。pytest-leaks 本身只是“探针”,真正的难点在于:

  • 让解释器在单线程、无并发干扰的环境下反复创建-销毁被测对象;
  • 把 pytest-leaks 输出的 “reachable / non-zero refcnt” 差异翻译成 C 扩展里的具体行号;
  • 在 CI 里稳定复现,避免因为测试顺序、缓存或全局状态导致误报。

知识点

  1. pytest-leaks 原理:通过 --leaks 钩子,在每次测试前后调用 sys.gettotalrefcount()(debug build)或 gc.get_objects() + 引用计数快照,统计差值;大于 0 即判定泄漏。
  2. 必须使用 Python debug build(国内源可用 pyenv install 3.11.4 -g 或 conda-forge 的 python-dbg),否则 gettotalrefcount 不存在,灵敏度骤降。
  3. 为了让差异可信,需满足:
    • 单进程、单线程执行(-n0 禁用 xdist);
    • 关闭 faulthandler、gc.disable() 的干扰;
    • 每个用例跑 “warmup + loops” 轮次,取稳态差值;
    • 在 conftest.py 里对 C 扩展的全局缓存做 teardown 强制清理。
  4. 定位到 C 行:把 pytest-leaks 输出的 “leaked object list” 导出到文本,结合 gdb -p $(pgrep python) + py-bt 或 python3-dbg 的 py-print 命令,打印对象 ob_refcnt 与 ob_type->tp_name,回溯到 C 扩展的 Py_INCREF 位置。
  5. 自动化门禁:在 GitLab CI(国内私有部署极多)里,使用官方 python:3.11-debug 镜像,跑 pytest --leaks --leaks-loops=10 --leaks-error=1 tests/test_c_ext/;若返回码非 0,直接阻断 MR。

答案

步骤化落地方案(可直接写进面试白板):

  1. 准备 debug Python

    pyenv install 3.11.4 -g
    pyenv local 3.11.4-debug
    
  2. 安装组件

    pip install pytest pytest-leaks
    
  3. 为 C 扩展写最小可复现用例
    假设泄漏模块叫 fastcrc,测试文件 tests/test_leak.py:

    import fastcrc
    import pytest
    
    @pytest.mark.leaks
    def test_crc32_leak():
        # 触发 C 扩展内部 Py_INCREF 忘记 DECREF 的路径
        for _ in range(1000):
            _ = fastcrc.crc32(b"x" * 1024)
    
  4. 在 conftest.py 中隔离状态

    @pytest.fixture(scope="function", autouse=True)
    def isolate_fastcrc_cache():
        yield
        # 强制清空 C 级全局缓存,避免误报
        fastcrc._clear_cache()
    
  5. 运行泄漏检测

    python-dbg -m pytest tests/test_leak.py -k leaks \
               --leaks --leaks-loops=10 --leaks-error=1 -v
    

    若输出 REFCNT NOT ZERO: 4,即存在 4 个引用泄漏。

  6. 定位 C 代码

    gdb -p $(pgrep -f pytest)
    (gdb) py-list
    (gdb) py-print * leaked_obj
    

    根据 tp_name 找到 fastcrc_CRC32Type,回溯到 fastcrc.c 里 Py_INCREF(self) 未配对的行,修复后重新跑检测,直到 --leaks-error=1 通过。

  7. 接入内部 CI
    .gitlab-ci.yml 片段:

    leak_gate:
      stage: test
      image: registry.xxx.com/base/python:3.11-debug
      script:
        - pip install -r requirements-dev.txt
        - python-dbg -m pytest --leaks --leaks-error=1
      allow_failure: false
    

拓展思考

  1. 如果 C 扩展使用第三方共享库(如 OpenSSL)内部缓存,pytest-leaks 可能误报“稳定泄漏”。此时可在 conftest.py 里通过 pytest.exit("skip leak check", returncode=0) 对特定标记跳过,或编写 cleanup() 接口在 teardown 中调用 OPENSSL_cleanup。
  2. 对于多线程场景(C 扩展释放 GIL),pytest-leaks 的统计会失真;可改用 pytest-valgrind 插件,在 CI 里跑 valgrind --tool=memcheck --leak-check=full --suppressions=python.supp python-dbg -m pytest,把引用计数泄漏转化为“definitely lost”字节数,门槛更高但更精确。
  3. 在量化公司实盘环境中,C 扩展泄漏往往伴随长时间运行才暴露。可以在 nightly 定时任务中跑 pytest --leaks --leaks-loops=100000,结合 perf top 观察 Py_INCREF 热点,提前发现慢泄漏。
  4. 若项目已接入 Bazel 构建(国内部分大厂采用),可自定义 py_test rule,把 python-dbg 与 --leaks 作为 exec_properties,让泄漏检测成为编译目标的一部分,实现“一次构建,全链路内存门禁”。