当测试用例导致 worker 内存超限被杀时,如何自动重试并降低并发?

解读

在国内 CI(如 GitLab-CI、Jenkins、阿里云效、腾讯云 CODING)里,pytest-xdist 的 worker 进程常因内存泄漏或单条用例占用过大而被 Linux OOM Killer 直接杀掉。此时仅 rerunfailures 无法感知“进程被杀”这一异常退出码,必须结合“进程级保活 + 自适应降并发”策略,才能在无人值守的流水线里既保证成功率又控制资源成本。面试官想考察的是:

  1. 对 pytest 插件生态的熟悉程度(xdist、rerunfailures、custom hooks)
  2. 对 Linux 信号与退出码的理解(-9 vs 1 vs 2)
  3. 对并发与资源之间权衡的工程思维(动态降线程/进程数)
  4. 对 CI 预算与速度的平衡(不能无脑重试 10 次,也不能一次性把并发降到 1)

知识点

  1. pytest-xdist 的 --max-worker-restart 与 worker 异常退出码
  2. pytest-custom_exit_code 插件:把被信号杀掉的 exit code 127/137 映射成 pytest 可识别的非 0 码
  3. pytest-rerunfailures 的 condition 参数:可写函数判断“是否属于 OOM”
  4. pytest_configure / pytest_runtest_logreport 钩子:在 master 节点收集 worker 的 crash 信息
  5. 动态生成 xdist 的 worker 数:利用 --tx 的“乘法语法”+ 环境变量 PYTEST_XDIST_WORKER_COUNT
  6. Linux cgroup 或 CI 提供的内存上限文件(/sys/fs/cgroup/memory/memory.limit_in_bytes)读取
  7. 自适应算法:指数退避并发数,最小不低于 CPU 核数的一半,防止重试拖垮流水线时长
  8. 国内云厂商 CI 的缓存策略:把上一次成功的并发数写入缓存(如 ~/.pytest_worker_count),下次流水线直接读取,减少冷启动探测时间

答案

给出一套可直接落地的“插件级”方案,兼顾轻量与可维护性,适合国内主流 CI 场景。

步骤 1:统一退出码
在 requirements-ci.txt 里引入 pytest-custom_exit_code,并在 tox.ini 或 pytest.ini 中配置
[tool:pytest]
addopts = -p custom_exit_code --custom-exit-code-137=99
这样 worker 被 OOM Kill(137)后,master 收到 99,pytest 主进程不会直接挂掉,而是标记为“失败”。

步骤 2:编写自适应并发插件 adaptive_xdist.py

import os, json, math, subprocess
from pathlib import Path

def pytest_addoption(parser):
    parser.addoption("--adaptive-max-workers", type=int, default=os.cpu_count(),
                     help="初始最大并发")
    parser.addoption("--adaptive-memory-limit-mb", type=int,
                     help="内存上限,单位 MB;CI 里通过环境变量传入")

def pytest_sessionstart(session):
    # 读取缓存的“上次成功并发数”
    cache_file = Path(".pytest_adaptive_cache.json")
    if cache_file.exists():
        cached = json.loads(cache_file.read_text())
        session.config.option.adaptive_max_workers = cached["workers"]

def pytest_runtest_logreport(report):
    # 只在 master 节点执行
    if not hasattr(report, "workerid"):
        return
    # 判断 worker 是否因 OOM 崩溃
    if report.outcome == "failed" and report.longrepr and "137" in str(report.longrepr):
        # 指数退避
        old = report.config.option.adaptive_max_workers
        new = max(old // 2, max(1, os.cpu_count() // 2))
        report.config.option.adaptive_max_workers = new
        # 写入缓存
        Path(".pytest_adaptive_cache.json").write_text(json.dumps({"workers": new}))

def pytest_cmdline_preparse(config, args):
    # 把计算后的并发数注入到 -n 参数
    w = config.option.adaptive_max_workers
    if "-n" not in args and "--dist" not in args:
        args[:] = ["-n", str(w)] + args

步骤 3:在 CI 里组合重试与降并发
.gitlab-ci.yml(以 GitLab 为例,Jenkins 同理)

variables:
  PYTEST_ADDOPTS: "--adaptive-memory-limit-mb=4096"
  # 国内镜像加速
  PIP_INDEX_URL: "https://pypi.tuna.tsinghua.edu.cn/simple"

pytest:
  stage: test
  image: python:3.11
  script:
    - pip install -r requirements-ci.txt
    - |
      for i in 1 2 3; do
        pytest --adaptive-max-workers=8 \
               --reruns 2 --reruns-delay 5 \
               --only-rerun="137|OOM" && break
        echo "第 $i 次尝试失败,继续降并发重试"
      done
  artifacts:
    reports:
      junit: report.xml
    paths:
      - .pytest_adaptive_cache.json
    expire_in: 1 week

关键点解释

  1. 被 OOM 杀掉的 worker 返回 137,被 custom_exit_code 映射成 99,pytest 主进程继续运行,adaptive_xdist.py 在 master 端捕获到失败日志里包含 137,立即把并发数减半并落盘缓存。
  2. 外层 shell 循环最多重试 3 轮,每轮内部再用 rerunfailures 对单条用例重试 2 次;若连续 3 轮仍失败,则整体 job 失败,人工介入。
  3. 下一轮 CI 直接读取 .pytest_adaptive_cache.json,避免再次从 8 进程起步,节省探测时间。
  4. 内存上限通过变量注入,方便在不同规格 Runner 间复用同一套代码。

拓展思考

  1. 如果项目里存在“必泄”的 C 扩展模块,上述方案只能缓解,不能根治。可引入 pytest-split 插件,把用例按内存占用历史数据拆成多份,分别放到独立 job 里执行,彻底隔离泄漏。
  2. 国内部分私有云 CI 支持“内存弹性限额”,可在 job 里调用 OpenAPI 临时扩容,再缩容,结合 adaptive_xdist 实现“先降并发,再升内存”的双轴策略,进一步缩短反馈时间。
  3. 对于超大 Django 项目,可用 pytest-django 的 --reuse-db 配合 xdist 的 --dist=loadscope,把模型层测试按 app 粒度分组,降低每个 worker 的内存峰值,再叠加本方案,实现“双层限流”。
  4. 若公司采用 K8s 型 Runner,可把 adaptive_xdist.py 扩展为 Sidecar 模式:Sidecar 定时读取容器内存使用率,一旦逼近 limit,主动发送 SIGUSR1 给 pytest master,触发 graceful worker 回收,比等 OOM Kill 更优雅。