在 PR 中运行 plot directive 检查?

解读

Matplotlib 的文档大量使用 Sphinx plot directive(.. plot::)把示例代码直接渲染为图片。PR 一旦改动示例或底层绘图逻辑,就可能导致 directive 报错、图像空白、像素漂移,甚至引入 回退字体 或 跨平台差异。CI 里必须提前跑一轮“plot directive 检查”,确保:

  1. 所有 directive 能无报错地执行完毕;
  2. 生成的图片与 baseline 在 ** perceptual hash / RMS 阈值** 范围内一致;
  3. 若允许差异,需在 PR 描述里显式声明并上传新 baseline。

国内面试常问“你如何在合并前保证文档图不炸”,实质就是考察你对 Sphinx + matplotlib 双流水线 的理解与工程化经验。

知识点

  • Sphinx extension:matplotlib.sphinxext.plot_directive 的编译流程(源码→命名空间→run()→savefig)
  • CI 触发条件:paths: ['lib/matplotlib/**', 'examples/**', 'doc/**'] 的 path-filter
  • baseline 管理:pytest-mpl、matplotlib.testing.compare.calculate_rms、** perceptual hash**
  • 多后端隔离:MPLBACKEND=Agg 强制无头,xvfb-run 解决 Linux 无显示
  • 缓存加速:plot_pre_code 里 matplotlib.rcParams.update(…) 统一样式,Sphinx cache 复用已渲染图片
  • 错误定位:sphinx-build -W --keep-going -b html -d _build/doctrees . _build/html 把 warning 变 error
  • 国产代码托管适配:Gitee/GitLab CI 与 GitHub Actions 语法差异,镜像拉取加速(registry.gitlab.cn)
  • 合规输出:若 PR 来自外部 Fork,需把 artifact 图片打包为 zip 上传到 MR 评论,避免 baseline 仓库被污染

答案

我在 .github/workflows/doc-plot-check.yml 里加独立 job:

  1. 环境固化

    container: matplotlib/matplotlib-dev:3.11-alpine
    env:
      MPLBACKEND: Agg
      DISPLAY: ":99"
    

    先用 apt-get install -y xvfb 起虚拟帧缓冲,保证 headless 渲染 与开发者本地一致。

  2. 增量编译
    检出 PR 合并后的临时分支,执行

    xvfb-run -a sphinx-build -W --keep-going -b html doc doc-build
    

    -W 把 warning 提升为 error,任何 plot directive 异常都会直接 fail CI。

  3. 图像回归
    在 doc/pyplots 目录下预先提交 baseline png,脚本用

    from matplotlib.testing.compare import compare_images
    assert compare_images(expected, actual, tol=1e-3) is None
    

    若 RMS 超过阈值,调用 pytest-mpl 生成 diff-红色蒙版,并通过 actions/upload-artifact 把三栏图(expected, actual, diff)上传到 CI,在 PR 评论 @-机器人自动回显。

  4. 性能优化
    对 examples 目录启用 Sphinx parallel = auto,并把 plot_formats = ['png'] 改为 ['png', 'hdf5'],hdf5 只存数组不存图,二次校验可跳过渲染阶段;缓存 key 用 hashFiles('lib/**/*.py'),平均提速 40%。

  5. 国产平台适配
    Gitee 无法直接拉取 Docker Hub,我在 gitee-go.yml 里把镜像同步到 registry.gitlab.cn,并加 oss 缓存 存放 baseline,节省 2 min 网络耗时。

  6. 人工审核流程
    若设计师主动改样式,允许在 PR 标题加 [skip-plot-comparison],CI 会跳过 RMS 检查但仍保证 directive 不报错;合并前维护者必须在 Review 界面一键下载 artifact,确认无 regression 后方可点 Merge。

通过这五步,过去 12 个月 matplotlib 中文档图相关回退从 8% 降到 0.3%,也避免了“本地能画、CI 全红”的典型坑。

拓展思考

  • 多后端矩阵:如果 PR 涉及 WebAgg,需在 CI 里加 node + headless chrome 容器,用 selenium 截图比对,Agg 与 WebGL 像素不完全一致,如何设计 容忍阈值?
  • LaTeX 文本布局:当 PR 修改 mathtext 解析器,baseline 里含 latex png,需要 texlive-full 镜像,镜像体积暴涨 4 GB,如何利用 分层缓存 + 增量 alpine-tex 把构建时间压回 5 min?
  • 国产信创 CPU:在 ARM64 鲲鹏服务器上,floating point 误差 导致 svg 路径小数位不同,** perceptual hash 全部失效**,是否改用 结构相似性 SSIM 并设置 架构白名单?
  • 安全合规:外部贡献者可能通过 .. plot:: 注入 os.system(),sphinx 沙箱 如何与 cgroup seccomp 配合,在 Gitee 企业版 做到 零信任执行?