在 CI 流水线中如何并行测试 NEP 56 提出的新 DType API 兼容性
解读
NEP 56 把 NumPy 的 dtype 系统彻底 C 级重构:
- 引入 PyArray_DTypeMeta 对象,所有 dtype 必须显式注册;
- 统一 cast 与 ufunc 的 resolve-descriptor 流程;
- 移除旧版 PyArray_RegisterCastFunc 等 API。
CI 并行测试的核心矛盾是“新旧 ABI 同时存在”:
- 同一套源码在 WITH_NEP56=1 与 =0 两种编译宏下产出两套 .so;
- 测试进程必须隔离,否则先 import 的 .so 会污染全局符号表;
- 国内 GitLab CI / GitHub Actions runner 普遍 2×4 vCPU,并行粒度要兼顾速度与缓存。
因此题目考察:
- 编译矩阵设计;2) 进程级隔离;3) 缓存与制品管理;4) 失败速报与日志聚合。
知识点
- NEP56 宏开关:setup.py 里 –-with-nep56 会定义 NPY_ABI_VERSION=0x02000000,同时把旧 API 标记为 deprecated。
- Python 启动标志 -OO -E -s 可彻底隔离 PYTHONPATH 与 site-packages。
- pytest-xdist 的 –dist=loadgroup 能把用例按标记动态分组,配合 pytest-custom_exit_code 实现“允许预期失败”。
- Linux 下 LD_PRELOAD+dlmopen 可实现单进程多 ABI,但 glibc≤2.34 有 bug,CI 中退而求其次用容器。
- 国内镜像加速:清华 tuna 与华为云 PyPI 缓存,.ccache 对 Cython 生成的 .c 文件命中率可达 85%。
- GitLab CI 的 parallel:matrix 最多 200 维,GitHub Actions 的 strategy.matrix 上限 256,需要把“编译轴”与“测试轴”正交拆分。
答案
以下方案在 GitLab CI + k8s runner 上跑通,GitHub Actions 只需把语法换成 strategy.matrix 即可。
阶段 1:编译矩阵
build:
stage: build
parallel:
matrix:
- NEP_FLAG: ["0", "1"]
PYTHON: ["3.9", "3.11"]
script:
- pip install -r build-dep.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
- python setup.py build_ext --inplace --with-nep56=$NEP_FLAG
- ccache -s
- python -m build --wheel -o ./dist-nep${NEP_FLAG}/
artifacts:
paths:
- dist-nep${NEP_FLAG}/*.whl
expire_in: 2 hrs
阶段 2:并行测试
test:
stage: test
needs: ["build"]
parallel:
matrix:
- NEP_FLAG: ["0", "1"]
PYTHON: ["3.9", "3.11"]
GROUP: ["core", "dtype", "linalg", "fft"]
image: python:${PYTHON}-slim
script:
- pip install --no-index --find-links=dist-nep${NEP_FLAG} numpy
- pip install pytest-xdist hypothesis -i https://pypi.tuna.tsinghua.edu.cn/simple
- |
export PYTHONOPTIMIZE=0
export PYTHONDONTWRITEBYTECODE=1
export NUMPY_EXPERIMENTAL_DTYPE_API=$NEP_FLAG
- pytest -m "${GROUP}" -n auto --maxfail=5 --junitxml=result-${NEP_FLAG}-${PYTHON}-${GROUP}.xml
artifacts:
when: always
reports:
junit: result-*.xml
paths:
- .hypothesis/examples # 缓存后续复现
关键细节
- 进程隔离:每 job 起新容器,site-packages 唯一,杜绝旧 .so 残留。
- 标记分组:pytest 用例已打 @pytest.mark.dtype_nep56,core 组跑旧 API 回归,dtype 组跑新 API 正向,linalg/fft 跑混合。
- 失败速报:–maxfail=5 让 job 快速退出,节省队列;junit 报告自动上传到 MR 页面,国内网络 3 s 内可见。
- 缓存:.ccache 与 pip 目录挂载到 k8s hostPath,二次构建 C 扩展从 6 min 降到 45 s。
拓展思考
- 若要在单台国产 ARM 服务器上跑多 ABI,可用 bubblewrap 做轻量级 namespace,比 Docker 启动快 300 ms,适合高校机房无 root 场景。
- NEP 56 最终会把旧 ABI 彻底删除,届时矩阵可降为一维,但需保留“dtype 插件”动态加载测试:把第三方 dtype(如 quaternion)打成 wheel,在 CI 里用
pip install --no-binary :all:强制源码编译,验证新 API 是否打破插件生态。 - 国内合规要求日志留痕 6 个月,可把 junit xml 统一推送到 MinIO 对象存储,并用 loki+grafana 做实时聚合,面试时可提及“日志落盘与审计”体现工程化思维。