如何在矩阵中根据 requirements.txt 哈希创建 venv 缓存?

解读

国内中大型 Python 项目普遍采用 GitLab CI、GitHub Actions 或自托管 Jenkins 做矩阵(matrix)并行测试,例如同时跑 Python 3.8/3.9/3.10 × Linux/macOS/Windows 的 9 个 Job。
每个 Job 都要安装依赖,如果每次都重新 pip install,既耗时又容易受 PyPI 网络波动影响。
面试官想知道你是否能把“依赖文件变更”作为缓存键,把虚拟环境(venv)整体缓存下来,实现“一次安装、多次复用”,同时保证矩阵维度之间互不污染。
考点集中在:

  1. 如何生成稳定的哈希键;
  2. 如何与矩阵维度拼接成唯一键;
  3. 如何让缓存失效策略与 Python 版本、操作系统、requirements.txt 内容三者联动;
  4. 如何兼容国内镜像源与 CI 平台缓存上限(GitHub Actions 单缓存 10 GB、GitLab 默认 5 GB)。

知识点

  1. requirements.txt 哈希生成:
    • 必须对“锁定后”的文本做哈希,避免注释、空行、顺序差异造成抖动;
    • 推荐 cat requirements.txt | sort | sha256sum | cut -d' ' -f1 生成 64 位小写 hex。
  2. 矩阵维度变量:
    • GitHub Actions 的 matrix.python-version 与 matrix.os;
    • GitLab 的 parallel:matrix 变量。
  3. 缓存键拼接范式:
    venv-{os}-{python-version}-{requirements-hash}
    恢复键(restore-keys)用前缀匹配实现“部分命中”回退。
  4. 虚拟环境路径:
    • Linux/macOS 推荐 $RUNNER_TEMP/venv;
    • Windows 推荐 $RUNNER_TEMP\venv,避免路径过长。
  5. 缓存动作:
    • GitHub Actions 用 actions/cache@v4;
    • GitLab 用 cache:key:files 与 cache:policy:pull-push。
  6. 国内加速:
    • 在 pip install 前注入 -i https://pypi.tuna.tsinghua.edu.cn/simple;
    • 缓存键中可追加镜像域名片段,防止换源后哈希一致但二进制包不兼容。
  7. 缓存失效触发:
    • 手动提升版本号前缀 venv-v1-;
    • 每周定时任务清缓存。

答案

以 GitHub Actions 为例,给出一份可直接落地的 YAML 片段,并解释每一步如何与 requirements.txt 哈希联动。

name: Matrix CI with venv cache

on: [push, pull_request]

jobs:
  test:
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-22.04, windows-2022, macos-13]
        python: ['3.8', '3.9', '3.10']
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4

      # 1. 生成 requirements.txt 哈希
      - name: Generate requirements hash
        id: req
        shell: bash
        run: |
          if [[ "${{ runner.os }}" == "Windows" ]]; then
            certutil -hashfile requirements.txt SHA256 | head -2 | tail -1 | tr -d ' ' > req.hash
          else
            sha256sum requirements.txt | awk '{print $1}' > req.hash
          fi
          echo "hash=$(cat req.hash)" >> $GITHUB_OUTPUT

      # 2. 拼接缓存键
      - name: Cache venv
        uses: actions/cache@v4
        id: venv-cache
        with:
          path: ${{ runner.temp }}/venv
          key: venv-${{ runner.os }}-${{ matrix.python }}-${{ steps.req.outputs.hash }}
          restore-keys: |
            venv-${{ runner.os }}-${{ matrix.python }}-

      # 3. 创建并激活虚拟环境
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: ${{ matrix.python }}

      - name: Create venv if cache miss
        if: steps.venv-cache.outputs.cache-hit != 'true'
        run: |
          python -m venv ${{ runner.temp }}/venv
          ${{ runner.temp }}/venv/bin/python -m pip install -U pip setuptools wheel -i https://pypi.tuna.tsinghua.edu.cn/simple
          ${{ runner.temp }}/venv/bin/python -m pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

      # 4. 运行测试
      - name: Test with pytest
        run: |
          source ${{ runner.temp }}/venv/bin/activate
          pytest -q --cov=src

关键点说明

  1. 哈希生成使用原生 shell 命令,保证三大系统兼容;
  2. 缓存键包含 OS、Python 版本、requirements 哈希,确保矩阵之间隔离;
  3. restore-keys 允许“Python 小版本升级”时复用旧缓存,减少首次空跑;
  4. 整个 venv 目录被缓存,后续 Job 直接激活即可,平均节省 40~60 秒;
  5. 若 requirements.txt 变更,哈希变化,缓存未命中,自动重新安装,实现“内容寻址”。

GitLab 对应写法

.cache_template: &cache_def
  cache:
    key:
      files:
        - requirements.txt
      prefix: $CI_JOB_NAME-$PY_VERSION
    paths:
      - venv/
    policy: pull-push

test:
  parallel:
    matrix:
      - PY_VERSION: ["3.8", "3.9", "3.10"]
  image: python:${PY_VERSION}-slim
  <<: *cache_def
  before_script:
    - python -m venv venv
    - source venv/bin/activate
    - pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
    - pip install -r requirements.txt
  script:
    - pytest

GitLab 的 key:files 会自动对 requirements.txt 做 SHA1 哈希,并拼接 prefix,实现与 GitHub Actions 相同的失效逻辑。

拓展思考

  1. 多文件依赖:如果项目使用 requirements/base.txt + requirements/test.txt,可以把 key:files 写成列表,或先把多文件 cat 后哈希,确保任一文件变动都触发重建。
  2. 二进制依赖缓存:Pillow、lxml 等带 so/dll 的包在不同 OS 不兼容,必须把 runner.os 加入键;若使用 docker 镜像测试,可把镜像 tag 也作为维度,避免 glibc 差异。
  3. 缓存瘦身:venv 目录常超过 1 GB,可安装后执行 pip cache purge && find venv -name "*.pyc" -delete 再上传,减少 30% 体积。
  4. 分布式缓存:国内公司常用自托管 Runner,可把缓存桶放到 MinIO 或阿里云 OSS,通过 actions/cache 的 lookup-only: true 配合自定义脚本实现跨机房共享。
  5. 锁文件策略:如果团队已采用 pip-tools 生成 requirements.lock,可直接对 lock 文件哈希,避免手动排序;若迁移到 Poetry,则对 poetry.lock 哈希,并用 poetry install --no-root 创建 venv。
  6. 缓存命中率监控:在 CI 最后一步打印 Cache hit: ${{ steps.venv-cache.outputs.cache-hit }},通过 Prometheus Exporter 收集,观察命中率低于 80% 时及时优化键策略。