如何在Jenkins中集成Jupyter Notebook的测试?

解读

面试官想知道三件事:

  1. 你是否理解 Jupyter Notebook 的“可执行文档”本质,以及它在国内企业里常被当作“可交付脚本”或“模型验收报告”使用;
  2. 你是否能把 Notebook 的“交互式”特征无缝嫁接到 Jenkins 的“无人值守流水线”里,解决版本管理、依赖隔离、结果断言、制品归档四大痛点;
  3. 你是否熟悉国内常见合规要求(内网离线、信创环境、镜像源加速、审计留痕),并给出可落地的工程化方案,而不是简单贴一段官方文档命令。

知识点

  1. .ipynb 文件结构:cell 类型、execution_count、outputs、metadata。
  2. Notebook 执行引擎:jupyter nbconvert、papermill、nbval、testbook 的优劣对比。
  3. Jenkins Pipeline 语法:Declarative vs Scripted,agent 标签、docker 代理、stash/unstash、post always 归档。
  4. 国内镜像加速:清华 tuna、中科大、华为云、阿里云,以及 pip.conf、conda 离线 bundle。
  5. 依赖隔离:conda-pack、docker multi-stage、repo2docker、JupyterHub 的 kernel 镜像。
  6. 断言策略:cell 输出正则匹配、papermill 注入参数后返回值断言、nbval 逐 cell diff、testbook 单元测试风格。
  7. 制品合规:nbconvert 生成的 HTML/PDF 必须带水印、时间戳、git-commit-id,存入 Nexus 或 Artifactory 并做签名。
  8. 安全与审计:Jenkins 凭据插件存储 kerberos keytab、kubernetes serviceAccount,禁止 notebook 中明文密码;流水线日志脱敏。
  9. 性能调优:提前把 kernel 容器镜像拉到内网 Harbor,挂载 /tmp 为 emptyDir 内存盘,减少 IO;对超大 pandas.DataFrame 用 pyarrow 零拷贝。
  10. 失败回滚:notebook 执行失败后,自动发企业微信/飞书告警,并触发 rollback pipeline 把上一次成功的 HTML 报告重命名为 latest。

答案

给出一套可直接落地的 Jenkinsfile(Declarative),兼顾国内离线场景与审计要求:

pipeline {
    agent {
        docker {
            // 内网 Harbor 提前缓存的镜像,已预装 python=3.9、jupyter、papermill、nbval、conda-pack
            image 'harbor.local/cicd/jupyter-runner:2024Q2'
            args '-v /etc/pip.conf:/root/.pip/pip.conf:ro ' +
                 '-v /etc/conda/condarc:/root/.condarc:ro ' +
                 '--memory=4g --cpu-quota=200000'
        }
    }
    environment {
        GIT_COMMIT_SHORT = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
        REPORT_DIR = "reports/${env.BUILD_NUMBER}-${GIT_COMMIT_SHORT}"
        CONDA_ENV = 'notebook-ci'
    }
    options {
        buildDiscarder(logRotator(numToKeepStr: '30'))
        timeout(time: 30, unit: 'MINUTES')
    }
    stages {
        stage('Prepare') {
            steps {
                sh 'mkdir -p ${REPORT_DIR}'
                // 国内离线场景:把项目里打包好的 conda-env.tar.gz 解压,避免每次在线创建
                sh 'tar -xzf env-bundles/conda-env-notebook-ci.tar.gz -p'
                sh 'conda-unpack'
            }
        }
        stage('Lint Notebook') {
            steps {
                sh 'jupyter nbconvert --to notebook --inplace --ClearMetadataPreprocessor.enabled=True *.ipynb'
                sh 'nbstripout --keep-output'   // 清除 git diff 噪声,保留 output 用于后续比对
            }
        }
        stage('Execute & Test') {
            parallel {
                stage('Smoke') {
                    steps {
                        sh 'papermill smoke.ipynb ${REPORT_DIR}/smoke-executed.ipynb ' +
                           '-p data_path data/input.parquet ' +
                           '-p epochs 1 ' +
                           '--request-save-notebook True ' +
                           '--log-level INFO'
                        // 关键指标断言:返回最后一个 cell 的 JSON 中 loss<0.05
                        sh '''python - <<PY
import json, sys
nb = json.load(open("${REPORT_DIR}/smoke-executed.ipynb"))
last_out = nb["cells"][-1]["outputs"][0]["data"]["text/plain"]
assert float(last_out) < 0.05, "loss too high"
PY'''
                    }
                }
                stage('Regression') {
                    steps {
                        sh 'pytest --nbval-lax -v regression/*.ipynb --html=${REPORT_DIR}/regression.html --self-contained-html'
                    }
                }
            }
        }
        stage('Package') {
            steps {
                sh 'jupyter nbconvert --to html_toc --template=company ${REPORT_DIR}/*-executed.ipynb --output-dir ${REPORT_DIR}'
                // 加入合规水印
                sh 'sed -i "s|</body>|<div class=watermark>CONFIDENTIAL-${GIT_COMMIT_SHORT}-${BUILD_NUMBER}</div></body>|g" ${REPORT_DIR}/*.html'
                // 数字签名,内网 CA
                sh 'gpg --batch --yes --detach-sign ${REPORT_DIR}/*.html'
            }
        }
    }
    post {
        always {
            archiveArtifacts artifacts: "${REPORT_DIR}/**", fingerprint: true
            publishHTML([allowMissing: false,
                         alwaysLinkToLastBuild: true,
                         keepAll: true,
                         reportDir: "${REPORT_DIR}",
                         reportFiles: 'smoke-executed.html',
                         reportName: 'Notebook 测试报告'])
            sh 'conda-pack -n ${CONDA_ENV} -o env-bundles/conda-env-notebook-ci.tar.gz --force'
            stash includes: 'env-bundles/*.tar.gz', name: 'env-cache'
        }
        failure {
            qyWechatNotification mentionedId: 'all',
                                  mentionedMobile: '',
                                  webhookUrl: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/xxxxx'
        }
    }
}

关键解释

  1. 镜像 harbor.local/cicd/jupyter-runner:2024Q2 已在内网 CI 机房,解决无法拉取 Docker Hub 的问题。
  2. conda-pack 把环境固化成 tar.gz,每次构建先解压,保证离线可重复;构建结束再 stash 新包,实现“环境滚动更新”。
  3. 使用 papermall 注入参数,避免把测试数据路径写死;用 Python 脚本直接读取 notebook 输出做断言,比 grep 更稳定。
  4. nbval-lax 只比对 cell 输出类型,不比对随机值,适合回归测试。
  5. HTML 报告加水印+GPG 签名,满足金融、运营商客户审计要求。
  6. 流水线 30 min 超时,防止研发写出死循环 notebook 耗尽资源。

拓展思考

  1. 多语言内核:若团队同时用 R 和 Python,可在同一镜像里装 IRkernel,通过 papermill 的 --kernel 参数切换;Jenkins 并行 stage 分别跑 R 和 Python notebook,实现“双语对照”报告。
  2. 大模型微调场景:Notebook 里训练 10 GB 文本,Jenkins 节点挂载 CephFS 只读数据集,训练产出 onnx 模型 push 到内网 ModelArts;流水线增加“模型卡”生成 stage,用 jupyter-book 聚合 notebook、模型卡、数据集指纹,一键发布内部知识库。
  3. 策略回测合规:券商要求“同一版本 notebook + 同一版本数据 + 同一容器镜像”才能作为交易依据;可把上述三者的 digest 写进 JSON 并做国密 SM2 签名,存入区块链存证平台,Jenkins 调用 SDK 自动上链。
  4. 反向触发:JupyterHub 里用户 push 到 GitLab 后,通过 WebHook 触发 Jenkins,PR 阶段只跑冒烟测试;合并到 master 后再跑全量回归并生成可交付 HTML,实现“像写代码一样写报告,像测代码一样测报告”。