如何在 CI 中设置性能回归阈值,当格式化耗时增长 10% 即失败

解读

面试官真正想考察的是“把 Prettier 当黑盒也能量化其性能”的工程化能力。国内一线厂对 CI 的稳定性极其敏感,10% 的波动就可能把整条流水线拖成瓶颈。因此,候选人必须给出:

  1. 可重复、可横向对比的耗时采集方案;
  2. 把“10%”翻译成可执行断言的阈值模型;
  3. 在 GitHub Actions / GitLab CI / Jenkins 等国内主流平台落地的完整脚本,且兼顾缓存、并发、网络抖动等中国网络环境下的特有干扰。

知识点

  • Prettier 性能瓶颈:二次解析、大文件全量打印、插件同步调用。
  • 基准测试方法论:warm-up、多次采样取 P90、稳定机器规格(CPU 主频固定、关闭超线程、同一 Runner 规格)。
  • 阈值模型:滑动窗口基线(最近 N 次主分支均值) vs 固定基线(release 分支锁定)。
  • 统计显著性:z-test 或 t-test,避免单次抖动误杀。
  • CI 平台差异:
    • GitHub Actions:自带 cache action,但国内下载 action 常超时,需走 npmmirror 镜像。
    • GitLab CI:可指定 runner tag 绑定固定裸金属,减少虚拟化噪音。
    • Jenkins:pipeline 里用 lockable resource 独占节点,避免并发抢占。
  • 数据持久化:把基准值 json 存到 git LFS 或阿里云 OSS,并设置 CDN 回源,防止 git 仓库膨胀。
  • 失败策略:PR 阶段仅 comment 告警,合并主干时才 hard fail,兼顾开发体验。

答案

下面给出一条可直接拷贝到 .github/workflows/benchmark.yml 的完整链路,其他 CI 只需替换语法糖即可。

  1. 准备基准脚本 bench.js
#!/usr/bin/env node
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

const REPO = 'https://registry.npmmirror.com';
const SAMPLE = 'src'; // 待格式化目录
const ITER = 5; // 采样次数

function fmt() {
  const t0 = process.hrtime.bigint();
  execSync(`npx --registry=${REPO} prettier --write ${SAMPLE}`, { stdio: 'inherit' });
  return Number(process.hrtime.bigint() - t0) / 1e6; // ms
}

const samples = Array.from({ length: ITER }, fmt);
const p90 = samples.sort((a, b) => a - b)[Math.floor(ITER * 0.9)];
console.log(JSON.stringify({ p90, unit: 'ms', commit: process.env.GITHUB_SHA }));
  1. 存储基线 把 baseline.json 提交到 main 分支:
{ "p90": 2350, "unit": "ms", "commit": "abc123" }
  1. CI 任务
name: Perf Gate
on:
  pull_request:
    paths:
      - '**.js'
      - '.github/workflows/benchmark.yml'

jobs:
  benchmark:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'
      - run: npm ci --registry=https://registry.npmmirror.com
      - name: run bench
        run: node bench.js > current.json
      - name: fetch baseline
        run: |
          git show origin/main:baseline.json > baseline.json
      - name: assert threshold
        run: |
          node -e '
          const c = require("./current.json");
          const b = require("./baseline.json");
          const ratio = c.p90 / b.p90;
          console.log(`Current P90: ${c.p90}ms, Baseline: ${b.p90}ms, Ratio: ${(ratio*100).toFixed(2)}%`);
          if (ratio > 1.10) {
            console.error("❌ Performance regression exceeds 10%");
            process.exit(1);
          }
          console.log("✅ Performance check passed");
          '
      - name: update baseline on main
        if: github.event.pull_request.merged == true && success()
        run: |
          mv current.json baseline.json
          git config user.name "github-actions[bot]"
          git add baseline.json
          git commit -m "chore: update perf baseline"
          git push origin main
  1. 干扰项治理
  • Runner 规格锁定:runs-on: ubuntu-latest-4core(自建 Runner 打标签)。
  • 关闭频率缩放:echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor。
  • 网络缓存:npm config set cache ~/.npm --global 并挂载 actions/cache。
  • 大文件拆分:对超过 500 KiB 的 fixture 走 .gitattributes filter=lfs diff=lfs merge=lfs。
  1. 阈值动态调整 若仓库体积自然增长导致基线漂移,可在每月 release 窗口手动提升基线并打 tag,保证 10% 相对值始终对准“上一次发布”而非“上一次提交”。

拓展思考

  1. 插件性能分摊:Prettier 插件同步钩子会阻塞主线程,可把 --debug-benchmark 输出解析成火焰图,定位是哪颗语法树节点拖慢整体,再决定是否将插件异步化或裁剪。
  2. 分布式采样:国内多地域 Runner 延迟差异大,可在华北、华南、华东各跑 3 次,用 ANOVA 剔除地域因子,再合并 P90,降低误报。
  3. 预算制替代阈值:对 monorepo 内不同子包设置“格式化预算”,例如 core 包 2 s、docs 包 500 ms,超预算即 fail,实现更细粒度治理。
  4. 与 Bundle Analyzer 联动:把格式化耗时写进 metrics.json,一并上传到内部观测平台(如阿里 SLS、腾讯 CLS),通过 Grafana 配置告警,当七日移动平均斜率 > 0 即提前预警,避免等到 PR 阶段才发现。
  5. 反向优化:若 10% 回归由正当业务需求(新增语法支持)引起,可同步开启 --cache 持久化及 prettier-v3 的并行 worker,用绝对耗时抵消回归,保持开发者体验不变。