diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml index 3215401d0a..2b557568b7 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml @@ -6,11 +6,11 @@ en: 677b522817e84e2f zh: f8518a7033b0fd54 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/problem: - en: bcdd24f3c39d593c - zh: 3e576d09c8c3bfd4 + en: 52c1c7d73dea8807 + zh: 8ce9142d06cb4be6 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision: - en: 23fc560e2c12be5e - zh: 89071bd1735823ff + en: 072960364d4be488 + zh: 861a856b7a5a5bf0 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision/release-rehearsals-share-the-linux-switch: en: 01e74068e0a96375 zh: aa811861ce30cb47 @@ -21,8 +21,8 @@ en: f395af725d1deaf1 zh: 896cedbb36c13758 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision/switch-any-repository-writer-1-minute-no-merge: - en: 2e3829fd72d6b1b0 - zh: 563f0abade7974f9 + en: f5ec9b53f6fd483a + zh: f6a22f29bf13e66e /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/capacity-during-failover: en: 3dffe12ecf2356c2 zh: 7e2385fcabab1398 diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md index 360a39a640..df7ccd68e6 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md @@ -6,11 +6,11 @@ English | [中文](2026-07-26-ci-failover-runbook.zh.md) ## Problem -The three required Linux worker jobs in [CI](../../../../.github/workflows/ci.yml) (`node 24 / static`, `node 24 / coverage`, `node 24 / snapshots and artifacts`) run on the hosted enterprise 32-core pools; the required verdict job that aggregates them (`all checks passed`) runs on standard `ubuntu-latest`; the [native Windows jobs](2026-08-08-native-windows-pull-request-ci.md) in [CI Windows](../../../../.github/workflows/ci-windows.yml) run on the hosted `dsh-windows-2025-16core` larger runner. When the enterprise pools degrade — jobs queue indefinitely or the enterprise labels vanish — every open pull request becomes unmergeable, and the ordinary recovery of merging a fix is itself deadlocked behind the very required checks that cannot run. **Scope: two independent switches, one per platform.** `DSH_CI_FAILOVER_LINUX` recovers an enterprise Linux-pool outage (the three required Linux workers plus the `all checks passed`, `windows checks passed`, and `python checks passed` verdicts); `DSH_CI_FAILOVER_WINDOWS` recovers a hosted Windows-pool outage (the native Windows jobs). A Linux-pool outage need not retarget Windows jobs and vice versa. The [Node compatibility jobs](../../../../.github/workflows/ci.yml) also follow the Linux switch with isolated setup; the verdict's `node-24-bench`, `python-sdk`, and `python-runtime` dependencies stay on standard hosted runners, as does CI Python's `python-runtime`; in a broader GitHub-hosted capacity failure that also takes out the standard pools, those dependencies still block the verdicts that require them. An outage therefore needs a switch any responder with repository write access can throw without merging anything. +The required Linux worker jobs in [CI](../../../../.github/workflows/ci.yml) (`node 24 / static`, `node 24 / coverage 1/2` and `2/2`, `node 24 / coverage report`, `node 24 / build`, `node 24 / snapshots and artifacts`, `node 24 / web snapshots 1/2` and `2/2`) run on the hosted enterprise pools; the required verdict job that aggregates them (`all checks passed`) runs on standard `ubuntu-latest`; the [native Windows jobs](2026-08-08-native-windows-pull-request-ci.md) in [CI Windows](../../../../.github/workflows/ci-windows.yml) run on the hosted `dsh-windows-2025-16core` larger runner. When the enterprise pools degrade — jobs queue indefinitely or the enterprise labels vanish — every open pull request becomes unmergeable, and the ordinary recovery of merging a fix is itself deadlocked behind the very required checks that cannot run. **Scope: two independent switches, one per platform.** `DSH_CI_FAILOVER_LINUX` recovers an enterprise Linux-pool outage (the required Linux workers plus the `all checks passed`, `windows checks passed`, and `python checks passed` verdicts); `DSH_CI_FAILOVER_WINDOWS` recovers a hosted Windows-pool outage (the native Windows jobs). A Linux-pool outage need not retarget Windows jobs and vice versa. The [Node compatibility jobs](../../../../.github/workflows/ci.yml) also follow the Linux switch with isolated setup; the verdict's `node-24-bench`, `python-sdk`, and `python-runtime` dependencies stay on standard hosted runners, as does CI Python's `python-runtime`; in a broader GitHub-hosted capacity failure that also takes out the standard pools, those dependencies still block the verdicts that require them. An outage therefore needs a switch any responder with repository write access can throw without merging anything. ## Decision -The primary Linux jobs (`node-24`, `node-24-coverage`, `node-24-build`, `node-24-consumers`, which restores the `node-24-build` output, and both entries of the `node-24-web-snapshot` shard matrix), the two `node-compat` matrix entries, and the `all-checks-passed`, `windows-checks-passed`, and `python-checks-passed` verdicts resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The three verdict jobs follow the Linux switch so they do not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes. +The primary Linux jobs (`node-24`, both `node-24-coverage` shard matrix entries and the `node-24-coverage-report` job that merges them, `node-24-build`, `node-24-consumers`, which restores the `node-24-build` output, and both entries of the `node-24-web-snapshot` shard matrix), the two `node-compat` matrix entries, and the `all-checks-passed`, `windows-checks-passed`, and `python-checks-passed` verdicts resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The three verdict jobs follow the Linux switch so they do not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes. The [superseded-CI cancellation policy](../../../../.github/workflows/ci.yml) governs master pushes and manual runs in the same workflow/ref group, including standby drills. Rapid master updates can starve a drill before it reaches a verdict. Use the latest completed standby verdict and check its age and commit before treating it as readiness evidence; a cancelled or merely scheduled run is not proof of readiness. @@ -32,7 +32,7 @@ The two switches are independent: flip only the one whose platform is degraded. 1. Repository **Settings → Secrets and variables → Actions → Variables → New repository variable**: name `DSH_CI_FAILOVER_LINUX` (Linux pool outage) or `DSH_CI_FAILOVER_WINDOWS` (Windows pool outage), value `selfhosted`. 2. Retrigger the required jobs so they re-resolve their pool. Jobs already **queued** for the hosted labels do not retarget and cannot be re-run in place, so for the documented indefinite-queue outage, cancel the stuck run and re-run all jobs, or push a new commit; "Re-run failed jobs" only helps once a job has actually failed rather than queued. -3. That is the entire switch. Under the `selfhosted` Linux failover value the workflow also drops `DSH_SNAPSHOT_MAX_CONCURRENCY` to 12 for the shared VM and skips the hosted-path pnpm cache restores because the VM's persistent store serves warm installs. Self-hosted coverage uses four single-worker instrumented partitions and two exempt workers; isolated hosted runners derive worker defaults from available CPUs. The Windows switch selects the native Windows pool and retains explicit worker limits on shared self-hosted runners. +3. That is the entire switch. Under the `selfhosted` Linux failover value the workflow also drops `DSH_SNAPSHOT_MAX_CONCURRENCY` to 12 for the shared VM and skips the hosted-path pnpm cache restores because the VM's persistent store serves warm installs. Self-hosted coverage runs two shard lanes of four single-worker instrumented partitions each, and the first shard also runs the exempt suites with two workers; isolated hosted runners derive worker defaults from available CPUs. The Windows switch selects the native Windows pool and retains explicit worker limits on shared self-hosted runners. **Dependabot exception.** Both switches' `selfhosted` legs deliberately exclude `dependabot[bot]`: under self-hosted failover, Dependabot PRs stay queued for the hosted pool rather than executing dependency-supplied code on the persistent VMs. A Dependabot PR that remains queued during an outage is expected behavior, not a failed switch; it completes when the hosted pool recovers. The `blacksmith` value's branches carry no such exclusion, because Blacksmith runners are ephemeral (see the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md)). diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md index c89acf64ea..d17a434556 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md @@ -6,11 +6,11 @@ Status: implemented ## 问题 -[CI](../../../../.github/workflows/ci.yml) 中三个必需的 Linux 工作作业(`node 24 / static`、`node 24 / coverage`、`node 24 / snapshots and artifacts`)运行在托管的企业级 32 核池上;聚合它们的必需判定作业(`all checks passed`)运行在标准 `ubuntu-latest` 上;[原生 Windows 作业](2026-08-08-native-windows-pull-request-ci.zh.md)(位于 [CI Windows](../../../../.github/workflows/ci-windows.yml))运行在托管的 `dsh-windows-2025-16core` 大型运行器上。当企业池发生故障——作业无限排队或企业标签消失——所有开启的拉取请求都无法合并,而"合并一个修复"这一常规恢复手段本身正被那些无法运行的必需检查死锁。**适用范围:两个独立开关,每个平台一个。**`DSH_CI_FAILOVER_LINUX` 恢复企业级 Linux 池故障(三个必需的 Linux 工作作业加 `all checks passed`、`windows checks passed` 与 `python checks passed` 判定作业);`DSH_CI_FAILOVER_WINDOWS` 恢复托管 Windows 池故障(原生 Windows 作业)。Linux 池故障无需重定向 Windows 作业,反之亦然。[Node 兼容性作业](../../../../.github/workflows/ci.yml)也通过隔离设置跟随 Linux 开关;判定作业的 `node-24-bench`、`python-sdk` 和 `python-runtime` 依赖仍留在标准托管运行器上,CI Python 的 `python-runtime` 也是如此;若更大范围的 GitHub 托管容量故障连标准池一并击倒,这些依赖仍会阻塞要求它们的判定。因此故障需要一个任何具备仓库写权限的响应者都能在不合并任何代码的情况下触发的开关。 +[CI](../../../../.github/workflows/ci.yml) 中必需的 Linux 工作作业(`node 24 / static`、`node 24 / coverage 1/2` 与 `2/2`、`node 24 / coverage report`、`node 24 / build`、`node 24 / snapshots and artifacts`、`node 24 / web snapshots 1/2` 与 `2/2`)运行在托管的企业级池上;聚合它们的必需判定作业(`all checks passed`)运行在标准 `ubuntu-latest` 上;[原生 Windows 作业](2026-08-08-native-windows-pull-request-ci.zh.md)(位于 [CI Windows](../../../../.github/workflows/ci-windows.yml))运行在托管的 `dsh-windows-2025-16core` 大型运行器上。当企业池发生故障——作业无限排队或企业标签消失——所有开启的拉取请求都无法合并,而"合并一个修复"这一常规恢复手段本身正被那些无法运行的必需检查死锁。**适用范围:两个独立开关,每个平台一个。**`DSH_CI_FAILOVER_LINUX` 恢复企业级 Linux 池故障(必需的 Linux 工作作业加 `all checks passed`、`windows checks passed` 与 `python checks passed` 判定作业);`DSH_CI_FAILOVER_WINDOWS` 恢复托管 Windows 池故障(原生 Windows 作业)。Linux 池故障无需重定向 Windows 作业,反之亦然。[Node 兼容性作业](../../../../.github/workflows/ci.yml)也通过隔离设置跟随 Linux 开关;判定作业的 `node-24-bench`、`python-sdk` 和 `python-runtime` 依赖仍留在标准托管运行器上,CI Python 的 `python-runtime` 也是如此;若更大范围的 GitHub 托管容量故障连标准池一并击倒,这些依赖仍会阻塞要求它们的判定。因此故障需要一个任何具备仓库写权限的响应者都能在不合并任何代码的情况下触发的开关。 ## 决策 -主要 Linux 作业(`node-24`、`node-24-coverage`、`node-24-build`、恢复 `node-24-build` 产物的 `node-24-consumers`,以及 `node-24-web-snapshot` 分片矩阵的两个条目)、两个 `node-compat` 矩阵条目,以及 `all-checks-passed`、`windows-checks-passed`、`python-checks-passed` 三个判定作业通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。三个判定作业跟随 Linux 开关,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。 +主要 Linux 作业(`node-24`、`node-24-coverage` 分片矩阵的两个条目及合并它们的 `node-24-coverage-report`、`node-24-build`、恢复 `node-24-build` 产物的 `node-24-consumers`,以及 `node-24-web-snapshot` 分片矩阵的两个条目)、两个 `node-compat` 矩阵条目,以及 `all-checks-passed`、`windows-checks-passed`、`python-checks-passed` 三个判定作业通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。三个判定作业跟随 Linux 开关,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。 [被取代 CI 的取消策略](../../../../.github/workflows/ci.yml) 管理同一工作流/引用组内的 master 推送和手动运行,包括热备演练。master 快速更新可能让演练因反复被取消而始终无法得出结论。判断就绪状态时,使用最近一次已完成的热备结论,并核对其时间和提交;已取消或仅被调度的运行不构成就绪证据。 @@ -32,7 +32,7 @@ Status: implemented 1. 仓库 **Settings → Secrets and variables → Actions → Variables → New repository variable**:名称 `DSH_CI_FAILOVER_LINUX`(Linux 池故障)或 `DSH_CI_FAILOVER_WINDOWS`(Windows 池故障),值 `selfhosted`。 2. 重新触发必需作业,使其重新解析运行器池。已经为托管标签**排队**的作业不会重定向,也无法原地 re-run,因此对于本手册所述的无限排队故障,应取消卡住的运行并 re-run all jobs,或推送一个新提交;“Re-run failed jobs”只有在作业真正失败(而非仍在排队)时才有用。 -3. 切换到此完成。在 `selfhosted` 的 Linux 故障切换取值下,工作流还会把 `DSH_SNAPSHOT_MAX_CONCURRENCY` 降为 12,以限制共享虚拟机上的争抢,并跳过托管路径的 pnpm 缓存恢复,因为虚拟机的持久 store 会直接提供热安装。自托管覆盖率使用 4 个单 worker 插桩分区与 2 个豁免 worker;独占的托管运行器根据可用 CPU 计算默认 worker 数。Windows 开关选择原生 Windows 运行器池,并在共享的自托管运行器上保留显式 worker 限制。 +3. 切换到此完成。在 `selfhosted` 的 Linux 故障切换取值下,工作流还会把 `DSH_SNAPSHOT_MAX_CONCURRENCY` 降为 12,以限制共享虚拟机上的争抢,并跳过托管路径的 pnpm 缓存恢复,因为虚拟机的持久 store 会直接提供热安装。自托管覆盖率分两条分片车道,每条 4 个单 worker 插桩分区,第一片另用 2 个 worker 运行豁免套件;独占的托管运行器根据可用 CPU 计算默认 worker 数。Windows 开关选择原生 Windows 运行器池,并在共享的自托管运行器上保留显式 worker 限制。 **Dependabot 例外。**两个开关的 `selfhosted` 腿都刻意排除 `dependabot[bot]`:自托管故障切换期间,Dependabot 拉取请求继续在托管池排队,而不是把依赖项提供的代码放到持久化虚拟机上执行。故障期间 Dependabot PR 持续排队是预期行为而非切换失败;托管池恢复后它会自行完成。`blacksmith` 取值下的分支不带此类排除,因为 Blacksmith 运行器是临时的(见 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md))。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 146937a1bc..cba2a805fd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,8 +57,10 @@ jobs: # Enterprise jobs isolate coverage, static analysis, and the build-backed - # tail. The build job owns the only Linux artifact build; the consumer job - # and the two web snapshot shards restore its output instead of rebuilding. + # tail. Coverage runs two file shards on separate runners and merges them on + # one small report runner. The build job + # owns the only Linux artifact build; the consumer job and the two web + # snapshot shards restore its output instead of rebuilding. # # FAILOVER (Linux): each Linux enterprise job resolves its pool through the # DSH_CI_FAILOVER_LINUX repository variable. Unset (normal), the expressions @@ -149,8 +151,16 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'dsh-ubuntu-24-04-16core' }} - name: node 24 / coverage + # Two instrumented file shards run on separate runners; the first also + # runs the uninstrumented heavy suites. node-24-coverage-report merges the + # shard blobs and owns the thresholds and the duration history. + strategy: + fail-fast: false + matrix: + shard: [1, 2] + name: node 24 / coverage ${{ matrix.shard }}/2 env: + DSH_COVERAGE_SHARD: ${{ matrix.shard }}/2 # Shared hosts expose host CPUs, not an isolated allocation. DSH_COVERAGE_MAX_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }} DSH_COVERAGE_PARTITIONS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '4' || '' }} @@ -248,8 +258,92 @@ jobs: path: ~/.cache/dsh-ci/bubblewrap key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} - - name: Run exhaustive coverage - run: pnpm run check:ci:coverage + - name: Run coverage shard + run: pnpm run check:ci:coverage-shard + + - name: Upload coverage shard blobs + uses: actions/upload-artifact@v7.0.1 + with: + name: coverage-blobs-${{ matrix.shard }} + path: coverage/shard/ + # A re-run of this shard replaces the previous attempt's output. + overwrite: true + if-no-files-found: error + include-hidden-files: true + retention-days: 30 + + # Merging blobs and checking thresholds runs after both coverage shards + # succeed. The merge converts every shard's V8 coverage to per-file reports + # and needs several GB of heap: a 2-vCPU runner took 154s against ~30s on the + # former 16-vCPU lane (run 44667701311), so this job uses an 8-vCPU runner. + # A failed shard skips this job, and the skipped result fails all-checks-passed. + node-24-coverage-report: + needs: node-24-coverage + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-8vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'dsh-ubuntu-24-04-8core' }} + name: node 24 / coverage report + steps: + # Runner cleanup owns tool caches and fixtures, including cancelled runs. + - name: Use runner-owned temporary storage + run: | + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + + # Redirect the Node compile cache (enabled by pnpm and TypeScript) off + # the root partition's /tmp before the first pnpm call in this lane. + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v5.0.0 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v7.0.0 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # Self-hosted runners reuse the shared persistent pnpm store. + # Hosted runners restore the remote cache into their ephemeral store. + - uses: actions/cache/restore@v6.1.0 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Download coverage shard blobs + uses: actions/download-artifact@v8.0.1 + with: + pattern: coverage-blobs-* + path: ${{ runner.temp }}/coverage-shards + + # Node sizes its default heap from host memory; merging the whole + # inventory exceeded the ~2 GB default of a 2-vCPU runner (run + # 44664262449), so the merge states its heap instead of inheriting one. + - name: Merge coverage shards and check thresholds + env: + NODE_OPTIONS: --max-old-space-size=4096 + run: pnpm run test:coverage:merge-shards "$RUNNER_TEMP/coverage-shards" - name: Save coverage duration history if: ${{ !cancelled() }} @@ -402,10 +496,7 @@ jobs: env: # Shared hosts expose host CPUs, not an isolated allocation. DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }} - DSH_OXLINT_THREADS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} DSH_PUBLINT_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} - DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '' }} - DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' # A failing gate aborts its running siblings. DSH_GATE_FAIL_FAST: '1' steps: @@ -512,9 +603,6 @@ jobs: env: # Shared hosts expose host CPUs, not an isolated allocation. DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }} - DSH_OXLINT_THREADS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} - DSH_PUBLINT_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} - DSH_WEB_SNAPSHOT_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }} DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '' }} DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' # A failing gate aborts its running siblings. @@ -925,7 +1013,9 @@ jobs: # Single stable required check for branch protection: require "all checks # passed" instead of enumerating matrix legs whose names change as lanes and # node versions evolve. Every blocking job in THIS workflow must be listed in - # `needs`. `needs` cannot cross workflow files: native Windows jobs report + # `needs` or be needed by a listed job: a failed node-24-coverage shard skips + # node-24-coverage-report, and a skipped need fails this verdict. `needs` + # cannot cross workflow files: native Windows jobs report # the separate "windows checks passed" verdict from ci-windows.yml, Python # jobs report "python checks passed" from ci-python.yml, and Wine plus the # master-only runtime targets live in ci-master.yml. @@ -948,7 +1038,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-build, node-24-consumers, node-24-web-snapshot, node-compat] + needs: [publisher-isolated, node-24, node-24-coverage-report, node-24-lint, node-24-bench, node-24-build, node-24-consumers, node-24-web-snapshot, node-compat] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/package.json b/package.json index e433b1d4fd..aa2aa84244 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "test:coverage": "pnpm run build:native-system && vitest run --coverage", "build:native-system": "tsx native/system/scripts/build.ts --host-addon-only", "test:coverage:partitioned": "tsx scripts/run-coverage-partitions.ts", + "test:coverage:merge-shards": "tsx scripts/merge-coverage-shards.ts", "test:e2e": "vitest run --config vitest.e2e.config.ts", "test:bench": "npm run build:bench && npm run build:web && npm run test:bench:built", "test:bench:built": "tsx scripts/run-bench-suite.ts", @@ -92,6 +93,7 @@ "check:ci:static": "tsx scripts/run-gates.ts ci-static", "check:ci:lint:contracts-ready": "tsx scripts/run-gates.ts ci-lint-contracts-ready", "check:ci:coverage": "tsx scripts/run-gates.ts ci-coverage", + "check:ci:coverage-shard": "tsx scripts/run-gates.ts ci-coverage-shard", "check:ci:unit": "tsx scripts/run-gates.ts ci-unit", "check:ci:bench": "tsx scripts/run-gates.ts ci-bench", "check:ci:snapshot": "tsx scripts/run-gates.ts ci-snapshot", diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index 3b7cb0a347..0649ad7179 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -15,7 +15,7 @@ const runnerPrivatePnpmDestination = /^\$\{\{ runner\.temp \}\}\/setup-pnpm-\$\{ const nativeWindowsPnpmDestination = '${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}' describe('CI workflow', () => { - it('keeps at most fourteen worker jobs active across PR workflows while Python runtime targets follow the SDK suite', () => { + it('keeps at most fifteen worker jobs active across PR workflows while Python runtime targets follow the SDK suite', () => { const ci = loadWorkflow('.github/workflows/ci.yml') const ciWindows = loadWorkflow('.github/workflows/ci-windows.yml') const ciPython = loadWorkflow('.github/workflows/ci-python.yml') @@ -45,8 +45,21 @@ describe('CI workflow', () => { expect(webSnapshot.strategy).toEqual({ 'fail-fast': false, matrix: { shard: [1, 2] } }) const webSnapshotShards = isRecord(webSnapshot.strategy) && isRecord(webSnapshot.strategy.matrix) && Array.isArray(webSnapshot.strategy.matrix.shard) ? webSnapshot.strategy.matrix.shard.length : 0 + // Coverage runs two instrumented file shards as one matrix; its report job + // starts only after both finish. + const coverage = workflowJob(ci, 'node-24-coverage') + expect(coverage.strategy).toEqual({ 'fail-fast': false, matrix: { shard: [1, 2] } }) + expect(coverage.name).toBe('node 24 / coverage ${{ matrix.shard }}/2') + const coverageLanes = isRecord(coverage.strategy) && isRecord(coverage.strategy.matrix) + && Array.isArray(coverage.strategy.matrix.shard) ? coverage.strategy.matrix.shard.length : 0 + expect(coverageLanes).toBe(2) + expect(workflowJob(ci, 'node-24-coverage-report').needs).toBe('node-24-coverage') + // The merge is CPU- and heap-bound; it runs on 8-vCPU pools. + const reportRunner = String(workflowJob(ci, 'node-24-coverage-report')['runs-on']) + expect(reportRunner).toContain("'blacksmith-8vcpu-ubuntu-2404'") + expect(reportRunner).toContain("'dsh-ubuntu-24-04-8core'") const ordinaryJobs = Object.entries(ci.jobs) - .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated', 'node-24-web-snapshot'].includes(name)) + .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated', 'node-24-web-snapshot', 'node-24-coverage', 'node-24-coverage-report'].includes(name)) for (const [name, job] of ordinaryJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') @@ -100,12 +113,13 @@ describe('CI workflow', () => { // The lint lane owns its own runner, so it raises the ceiling by one; the // self-hosted failover pool is still admitted only up to its own limit. // The build job finishes before its downstream jobs start, so the - // static count overstates the peak by one. - const linuxActive = ordinaryJobs.length + webSnapshotShards + // static count overstates the peak by one. Coverage counts its two + // shards; the coverage report starts after them and is not counted. + const linuxActive = ordinaryJobs.length + webSnapshotShards + coverageLanes const beforeSdk = linuxActive + compatibilityLimit + windowsActive + 1 const afterSdk = linuxActive + compatibilityLimit + windowsActive + Math.max(1, targets.split(',').length) - expect(beforeSdk).toBeLessThanOrEqual(14) - expect(afterSdk).toBeLessThanOrEqual(14) + expect(beforeSdk).toBeLessThanOrEqual(15) + expect(afterSdk).toBeLessThanOrEqual(15) }) it('keeps required PR verdicts covering runtime and publisher jobs', () => { @@ -125,13 +139,29 @@ describe('CI workflow', () => { expect(verdict.needs.every(id => typeof id === 'string' && id in jobs)).toBe(true) blocking.push(...(verdict.needs as string[])) } + // A job the verdict does not list must be needed by one it lists: a failed + // coverage shard skips its report job, and the verdict fails on a skip. + const ci = loadWorkflow('.github/workflows/ci.yml') + if (!isRecord(ci.jobs)) throw new TypeError('ci.yml must define jobs') + const covered = new Set() + const visit = (id: string): void => { + if (covered.has(id)) return + covered.add(id) + const needs = workflowJob(ci, id).needs + for (const need of Array.isArray(needs) ? needs : typeof needs === 'string' ? [needs] : []) { + if (typeof need === 'string') visit(need) + } + } + for (const id of workflowJob(ci, 'all-checks-passed').needs as string[]) visit(id) + expect(Object.keys(ci.jobs).filter(id => id !== 'all-checks-passed' && !covered.has(id))).toEqual([]) + expect(blocking).not.toContain('node-24-coverage') // Every blocking lane must contribute to a branch-protection verdict. expect(blocking.sort()).toEqual([ 'node-24', 'node-24-bench', 'node-24-build', 'node-24-consumers', - 'node-24-coverage', + 'node-24-coverage-report', 'node-24-lint', 'node-24-web-snapshot', 'node-compat', @@ -301,8 +331,39 @@ describe('CI workflow', () => { expect(wine.steps).toContainEqual(expect.objectContaining({ name: 'Shut down wineserver', if: 'always()' })) }) + it('restores Linux coverage timings on the shards and saves the merged timings only from the report job', () => { + const ci = loadWorkflow('.github/workflows/ci.yml') + const prefix = "coverage-times-Linux-${{ runner.environment }}-${{ vars.DSH_CI_FAILOVER_LINUX || 'enterprise' }}-" + const key = prefix + '${{ github.run_id }}-${{ github.run_attempt }}' + const stepsOf = (jobName: string): Record[] => { + const job = workflowJob(ci, jobName) + if (!Array.isArray(job.steps)) throw new TypeError(`${jobName} must define steps`) + return job.steps.filter(isRecord) + } + const lanes = stepsOf('node-24-coverage') + const restore = lanes.findIndex(step => step.name === 'Restore coverage duration history') + expect(restore).toBeGreaterThan(lanes.findIndex(step => step.uses === 'actions/checkout@v7.0.1')) + expect(lanes.findIndex(step => step.run === 'pnpm run check:ci:coverage-shard')).toBeGreaterThan(restore) + expect(lanes[restore]).toMatchObject({ + uses: 'actions/cache/restore@v6.1.0', + with: { path: '.coverage-times.json', key, 'restore-keys': `${prefix}\n` }, + }) + expect(lanes.filter(step => isRecord(step.with) && step.with.path === '.coverage-times.json' && step.uses === 'actions/cache/save@v6.1.0')).toEqual([]) + const report = stepsOf('node-24-coverage-report') + const merge = report.findIndex(step => step.run === 'pnpm run test:coverage:merge-shards "$RUNNER_TEMP/coverage-shards"') + expect(report[merge]).toMatchObject({ env: { NODE_OPTIONS: '--max-old-space-size=4096' } }) + expect(lanes.find(step => step.name === 'Upload coverage shard blobs')).toMatchObject({ with: { overwrite: true } }) + const save = report.findIndex(step => step.name === 'Save coverage duration history') + expect(merge).toBeGreaterThan(report.findIndex(step => step.uses === 'actions/download-artifact@v8.0.1')) + expect(save).toBeGreaterThan(merge) + expect(report[save]).toMatchObject({ + uses: 'actions/cache/save@v6.1.0', + if: '${{ !cancelled() }}', + with: { path: '.coverage-times.json', key }, + }) + }) + it.each([ - ['node-24-coverage', 'ci.yml', 'Linux', 'LINUX', 'pnpm run check:ci:coverage'], ['windows-coverage', 'ci-windows.yml', 'Windows', 'WINDOWS', 'pnpm run check:ci:coverage'], ])('reuses %s coverage timings only within its platform and runner pool', (jobName, file, platform, variable, command) => { const job = workflowJob(loadWorkflow('.github/workflows/' + file), jobName) @@ -357,7 +418,7 @@ describe('CI workflow', () => { } }) - it.each(['node-24', 'node-24-coverage', 'node-24-build', 'node-24-consumers', 'node-24-web-snapshot'])( + it.each(['node-24', 'node-24-coverage', 'node-24-coverage-report', 'node-24-build', 'node-24-consumers', 'node-24-web-snapshot'])( '%s keeps tool and fixture temporary files under runner cleanup', (jobName) => { const job = workflowJob(loadWorkflow('.github/workflows/ci.yml'), jobName) @@ -936,6 +997,7 @@ describe('CI workflow', () => { const redirectLanes = [ [prWorkflow, 'node-24'], [prWorkflow, 'node-24-coverage'], + [prWorkflow, 'node-24-coverage-report'], [prWorkflow, 'node-24-build'], [prWorkflow, 'node-24-consumers'], [prWorkflow, 'node-24-web-snapshot'], diff --git a/scripts/coverage-partitions.spec.ts b/scripts/coverage-partitions.spec.ts index 2e5ebdb705..8241e0c775 100644 --- a/scripts/coverage-partitions.spec.ts +++ b/scripts/coverage-partitions.spec.ts @@ -9,8 +9,13 @@ import { COVERAGE_PARTITIONS_ENV, COVERAGE_TEST_TIMEOUT_ENV, CoveragePartitionCoordinator, + COVERAGE_SHARD_DIRECTORY, assignWeightedPartitions, collectPartitionDurations, + FailedTestCollector, + mergeCoverageShards, + parseCoverageShard, + selectCoverageShardFiles, coverageTestTimeoutOptions, forwardedCoverageArgs, parseCoveragePartitionCount, @@ -775,3 +780,183 @@ describe('coverage partition coordinator', () => { await expect(access(marker)).resolves.toBeUndefined() }) }) + +describe('coverage file shards', () => { + // An absolute checkout root on any platform, distinct from every temporary root. + const otherCheckout = join(tmpdir(), 'dsh-coverage-other-checkout') + + it.each([ + [undefined, undefined], + ['', undefined], + ['1/2', { index: 1, count: 2 }], + ['2/2', { index: 2, count: 2 }], + ])('parses %j', (raw, expected) => { + expect(parseCoverageShard(raw)).toEqual(expected) + }) + + it.each(['3/2', '0/2', '1/0', 'a/b', '1'])('rejects %j', (raw) => { + expect(() => parseCoverageShard(raw)).toThrow(/DSH_COVERAGE_SHARD must be \//) + }) + + const sizes = new Map([['a.spec.ts', 90], ['b.spec.ts', 60], ['c.spec.ts', 50], ['d.spec.ts', 30], ['e.spec.ts', 20], ['f.spec.ts', 20]]) + const sizeOf = (file: string): number => sizes.get(file) ?? 0 + const inventory = [...sizes.keys()] + + it('deals files largest first to the lighter shard, independent of input order', () => { + expect(selectCoverageShardFiles(inventory, { index: 1, count: 2 }, sizeOf)).toEqual(['a.spec.ts', 'd.spec.ts', 'f.spec.ts']) + expect(selectCoverageShardFiles(inventory, { index: 2, count: 2 }, sizeOf)).toEqual(['b.spec.ts', 'c.spec.ts', 'e.spec.ts']) + expect(selectCoverageShardFiles([...inventory].reverse(), { index: 1, count: 2 }, sizeOf)) + .toEqual(selectCoverageShardFiles(inventory, { index: 1, count: 2 }, sizeOf)) + }) + + it.each([2, 3])('assigns every file to exactly one of %i shards', (count) => { + const shards = Array.from({ length: count }, (_, index) => selectCoverageShardFiles(inventory, { index: index + 1, count }, sizeOf)) + expect(shards.flat().sort()).toEqual([...inventory].sort()) + }) + + it('collects Vitest failure lines across split chunks and color codes', () => { + const collector = new FailedTestCollector() + collector.add('stdout', ' ✓ passes\n \u001b[31m×\u001b[39m breaks the con') + collector.add('stdout', 'tract 12ms\n') + collector.add('stderr', ' FAIL |thread-safe| a.spec.ts > suite > breaks the contract\nAssertionError: x\n FAIL b.spec.ts') + + expect(collector.lines()).toEqual([ + '× breaks the contract 12ms', + 'FAIL |thread-safe| a.spec.ts > suite > breaks the contract', + 'FAIL b.spec.ts', + ]) + }) + + it('writes the shard manifest, blobs, and durations instead of merging', async () => { + const root = await temporaryRoot() + // Byte sizes 40, 30, 20, 10 deal a and d to shard 1, b and c to shard 2. + for (const [file, size] of [['a.spec.ts', 40], ['b.spec.ts', 30], ['c.spec.ts', 20], ['d.spec.ts', 10]] as const) { + await writeFile(join(root, file), 'x'.repeat(size)) + } + const commands: CoverageCommand[] = [] + const coordinator = new CoveragePartitionCoordinator({ + root, + partitions: 2, + pnpmEntrypoint: '/pnpm.cjs', + files: ['a.spec.ts', 'b.spec.ts', 'c.spec.ts', 'd.spec.ts'], + shard: { index: 2, count: 2 }, + runCommand: successfulCommandRecorder(commands), + }) + + await expect(coordinator.run()).resolves.toBe(0) + + expect(commands.map(command => command.label)).toEqual(['partition 1/2', 'partition 2/2']) + const directory = join(root, COVERAGE_SHARD_DIRECTORY) + const manifest = JSON.parse(await readFile(join(directory, 'shard.json'), 'utf8')) as { shard: string; files: string[]; blobs: string[] } + expect(manifest).toEqual({ + shard: '2/2', + root, + files: ['b.spec.ts', 'c.spec.ts'], + blobs: ['shard-2-partition-1.json', 'shard-2-partition-2.json'], + }) + for (const blob of manifest.blobs) await expect(access(join(directory, 'blobs', blob))).resolves.toBeUndefined() + const times = JSON.parse(await readFile(join(directory, 'times.json'), 'utf8')) as Array<{ file: string }> + expect(times.map(entry => entry.file).sort()).toEqual(['b.spec.ts', 'c.spec.ts']) + }) + + /** Write one shard output directory as the report job downloads it. */ + async function writeShardOutput( + input: string, + index: number, + files: readonly string[], + root: string, + blobs = [`shard-${index}-partition-1.json`], + ): Promise { + const directory = join(input, `coverage-blobs-${index}`) + await mkdir(join(directory, 'blobs'), { recursive: true }) + for (const blob of blobs) await writeFile(join(directory, 'blobs', blob), JSON.stringify([join(root, 'packages', 'a', 'src', 'index.ts')])) + await writeFile(join(directory, 'shard.json'), JSON.stringify({ shard: `${index}/2`, root, files, blobs })) + await writeFile(join(directory, 'times.json'), JSON.stringify(files.map(file => ({ file, duration: 7 })))) + } + + async function mergeFixture(first: readonly string[], second: readonly string[]) { + const root = await temporaryRoot() + const input = await temporaryRoot() + await writeShardOutput(input, 1, first, root) + await writeShardOutput(input, 2, second, otherCheckout) + const commands: CoverageCommand[] = [] + const merge = () => mergeCoverageShards({ + root, + pnpmEntrypoint: '/pnpm.cjs', + inputDirectory: input, + inventory: ['a.spec.ts', 'b.spec.ts', 'c.spec.ts'], + runCommand: vi.fn(async (command: CoverageCommand) => { + commands.push(command) + return passed + }), + }) + return { root, input, commands, merge } + } + + it('merges every shard blob once and records the shard durations', async () => { + const { root, commands, merge } = await mergeFixture(['a.spec.ts', 'c.spec.ts'], ['b.spec.ts']) + + await expect(merge()).resolves.toBe(0) + + expect(commands).toHaveLength(1) + expect(commands[0]!.label).toBe('merged coverage report') + expect(commands[0]!.args).toContain('--merge-reports=coverage/.merge/blobs') + expect([...readFileDurations(root).keys()].sort()).toEqual(['a.spec.ts', 'b.spec.ts', 'c.spec.ts']) + }) + + it('rewrites the blob paths of a shard that ran in another checkout to this checkout', async () => { + const root = await temporaryRoot() + const input = await temporaryRoot() + await writeShardOutput(input, 1, ['a.spec.ts', 'c.spec.ts'], root) + await writeShardOutput(input, 2, ['b.spec.ts'], otherCheckout) + const merged: string[] = [] + await expect(mergeCoverageShards({ + root, + pnpmEntrypoint: '/pnpm.cjs', + inputDirectory: input, + inventory: ['a.spec.ts', 'b.spec.ts', 'c.spec.ts'], + runCommand: vi.fn(async () => { + for (const blob of ['shard-1-partition-1.json', 'shard-2-partition-1.json']) { + merged.push(...JSON.parse(await readFile(join(root, 'coverage/.merge/blobs', blob), 'utf8')) as string[]) + } + return passed + }), + })).resolves.toBe(0) + + expect(merged).toEqual([join(root, 'packages', 'a', 'src', 'index.ts'), join(root, 'packages', 'a', 'src', 'index.ts')]) + }) + + it.each([ + ['overlapping', ['a.spec.ts', 'b.spec.ts'], ['b.spec.ts', 'c.spec.ts']], + ['incomplete', ['a.spec.ts'], ['b.spec.ts']], + ['unexpected', ['a.spec.ts', 'c.spec.ts'], ['b.spec.ts', 'z.spec.ts']], + ])('refuses %s shard file lists before merging', async (_case, first, second) => { + const { commands, merge } = await mergeFixture(first, second) + + await expect(merge()).rejects.toThrow(/must partition the instrumented inventory/) + expect(commands).toEqual([]) + }) + + it('refuses a listed blob that the shard did not upload', async () => { + const { input, commands, merge } = await mergeFixture(['a.spec.ts', 'c.spec.ts'], ['b.spec.ts']) + await rm(join(input, 'coverage-blobs-2', 'blobs', 'shard-2-partition-1.json')) + + await expect(merge()).rejects.toThrow(/blob shard-2-partition-1.json is missing or empty/) + expect(commands).toEqual([]) + }) + + it('refuses a missing shard', async () => { + const { input, commands, merge } = await mergeFixture(['a.spec.ts', 'c.spec.ts'], ['b.spec.ts']) + await rm(join(input, 'coverage-blobs-2'), { recursive: true }) + + await expect(merge()).rejects.toThrow(/expected shards 1..n of one count/) + expect(commands).toEqual([]) + }) + + it('refuses shard input inside the coverage directory it replaces', async () => { + const root = await temporaryRoot() + await expect(mergeCoverageShards({ + root, pnpmEntrypoint: '/pnpm.cjs', inputDirectory: join(root, 'coverage', 'shards'), inventory: [], + })).rejects.toThrow(/must lie outside/) + }) +}) diff --git a/scripts/coverage-partitions.ts b/scripts/coverage-partitions.ts index b0cccc5338..35c13d6e41 100644 --- a/scripts/coverage-partitions.ts +++ b/scripts/coverage-partitions.ts @@ -1,12 +1,13 @@ /** * Coordinate single-worker Vitest coverage partitions and one merged report. * Separate processes preserve worker isolation; only the complete merged - * inventory can enforce per-file coverage thresholds. + * inventory can enforce per-file coverage thresholds. CI splits the inventory + * into file shards on separate runners and merges their blobs on one report job. */ import { spawn } from 'node:child_process' -import { globSync, readFileSync, writeFileSync } from 'node:fs' -import { lstat, mkdir, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises' -import { join, relative, sep } from 'node:path' +import { globSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { copyFile, lstat, mkdir, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises' +import { basename, isAbsolute, join, relative, sep } from 'node:path' import type { TestUserConfig } from 'vitest/config' import { coverageExemptHeavySuites } from './coverage-exempt.ts' import { pnpmInvocation } from './pnpm-invocation.ts' @@ -20,6 +21,79 @@ export const COVERAGE_PARTITION_MODE_ENV = 'DSH_COVERAGE_PARTITION_MODE' /** Environment variable carrying a lane's per-test, hook, and `expect.poll` budget in milliseconds. */ export const COVERAGE_TEST_TIMEOUT_ENV = 'DSH_COVERAGE_TEST_TIMEOUT_MS' +/** + * Environment variable selecting one file shard of the instrumented inventory, + * as `/`. A shard run writes {@link COVERAGE_SHARD_DIRECTORY} + * and leaves merging and thresholds to {@link mergeCoverageShards}. + */ +export const COVERAGE_SHARD_ENV = 'DSH_COVERAGE_SHARD' + +/** Root-relative directory where a shard run writes its manifest, blobs, and durations. */ +export const COVERAGE_SHARD_DIRECTORY = 'coverage/shard' + +/** One selected file shard: 1-based `index` of `count`. */ +export interface CoverageShard { + index: number + count: number +} + +/** + * Parse an optional coverage file shard. + * @param raw - the `DSH_COVERAGE_SHARD` value. + * @returns the shard, or undefined when unset or empty. + * @throws when the value is not `/` with 1 <= index <= count. + */ +export function parseCoverageShard(raw: string | undefined): CoverageShard | undefined { + if (raw === undefined || raw === '') return undefined + const match = /^([1-9]\d*)\/([1-9]\d*)$/.exec(raw) + if (match === null || Number(match[1]) > Number(match[2])) { + throw new Error(`${COVERAGE_SHARD_ENV} must be / with 1 <= index <= count, got ${JSON.stringify(raw)}.`) + } + return { index: Number(match[1]), count: Number(match[2]) } +} + +/** + * Select one shard's files by byte size: files are taken largest first (ties by + * repository-relative path) and each goes to the shard with the smallest total + * size so far (ties to the lower index). Byte size stands in for test cost; the + * split reads only the checkout, so every shard computes the same assignment. + * @param files - the instrumented inventory. + * @param shard - the shard to keep. + * @param sizeOf - byte size of one repository-relative file. + * @returns the shard's files in path order. + */ +export function selectCoverageShardFiles( + files: readonly string[], + shard: CoverageShard, + sizeOf: (file: string) => number, +): string[] { + const loads = Array.from({ length: shard.count }, () => 0) + const selected: string[] = [] + const ordered = [...files].map(file => ({ file, size: sizeOf(file) })) + .sort((left, right) => right.size - left.size || (left.file < right.file ? -1 : left.file > right.file ? 1 : 0)) + for (const { file, size } of ordered) { + let owner = 0 + for (let index = 1; index < loads.length; index++) { + if ((loads[index] ?? 0) < (loads[owner] ?? 0)) owner = index + } + loads[owner] = (loads[owner] ?? 0) + size + if (owner === shard.index - 1) selected.push(file) + } + return selected.sort() +} + +/** Manifest a shard run writes beside its blobs, read back by {@link mergeCoverageShards}. */ +export interface CoverageShardManifest { + /** The shard as `/`. */ + shard: string + /** Absolute checkout root of the shard run, the prefix of every path its blobs record. */ + root: string + /** Test files the shard ran, in path order. */ + files: string[] + /** Blob file names under the shard's `blobs/` directory. */ + blobs: string[] +} + /** * Reporter that canonicalizes a partition's coverage locations before its blob * is serialized (see scripts/coverage-canonical-locations.ts). Root-relative in @@ -55,6 +129,8 @@ export interface CoverageCommandResult { error?: string /** Bounded combined stdout/stderr tail repeated when the command fails. */ outputTail?: string + /** Vitest `FAIL` and `×` lines from the whole output, bounded, repeated in the run summary. */ + failedTests?: string[] } /** Execute one coordinator command with inherited output. */ @@ -78,6 +154,8 @@ export interface CoveragePartitionCoordinatorOptions { weights?: ReadonlyMap /** Project ownership paired with `files`; collected from `vitest list` when absent. */ projectOf?: ReadonlyMap + /** File shard to run; its manifest, blobs, and durations replace the merge and thresholds. */ + shard?: CoverageShard } /** Parse an optional coverage partition count. */ @@ -151,6 +229,11 @@ const UNKNOWN_FILE_WEIGHT = 1 */ const FILE_TIMES_NAME = '.coverage-times.json' +/** File names inside a shard directory. */ +const SHARD_MANIFEST_NAME = 'shard.json' +const SHARD_TIMES_NAME = 'times.json' +const SHARD_BLOBS_NAME = 'blobs' + /** * The instrumented inventory: every file plus the Vitest project it belongs * to (`thread-safe` or `process-bound`). Preserving the per-project split @@ -467,8 +550,10 @@ export class CoveragePartitionCoordinator { private readonly files: readonly string[] private readonly weights: ReadonlyMap | undefined private projectOf = new Map() + private readonly shard: CoverageShard | undefined private readonly temporaryRoot: string private readonly blobsRoot: string + private readonly blobPrefix: string /** Create a coordinator from validated process-independent inputs. */ public constructor(options: CoveragePartitionCoordinatorOptions) { @@ -483,17 +568,23 @@ export class CoveragePartitionCoordinator { this.files = options.files ?? [] this.weights = options.weights this.projectOf = new Map(options.projectOf ?? []) + this.shard = options.shard this.temporaryRoot = join(this.root, 'coverage', '.partitioned') - this.blobsRoot = join(this.temporaryRoot, 'blobs') + // Shard blobs carry the shard index so the report job can merge every + // shard's blobs from one directory. + this.blobsRoot = this.shard === undefined ? join(this.temporaryRoot, 'blobs') : join(this.root, COVERAGE_SHARD_DIRECTORY, SHARD_BLOBS_NAME) + this.blobPrefix = this.shard === undefined ? '' : `shard-${this.shard.index}-` } /** * Run every partition and verify its test-file inventory before one merged threshold check. + * A shard run instead writes its manifest, blobs, and durations under `coverage/shard/`. * Failed runs retain inventories, partition configs, and test reports in coverage/.partitioned. * @returns zero only when every partition and the merge command succeed. */ public async run(): Promise { await removeOwnedTree(join(this.root, 'coverage')) + await mkdir(this.temporaryRoot, { recursive: true }) await mkdir(this.blobsRoot, { recursive: true }) let succeeded = false @@ -513,6 +604,14 @@ export class CoveragePartitionCoordinator { } return result })) + reportFailedPartitions(commands, results) + if (this.shard !== undefined) { + await this.assertCompleteBlobSet(commands) + await this.assertCompleteTestFiles(assignments) + await this.writeShardOutput(this.shard, assignments, commands) + succeeded = !results.some(commandFailed) + return succeeded ? 0 : 1 + } // Persist durations before blob validation: a missing blob aborts the // run, but the completed partitions' timings are still worth keeping. this.persistDurations(this.partitions) @@ -555,6 +654,25 @@ export class CoveragePartitionCoordinator { writeFileDurations(this.root, collectPartitionDurations(reportFiles), currentFiles) } + /** Write the shard manifest and measured durations beside the shard's blobs. */ + private async writeShardOutput( + shard: CoverageShard, + assignments: readonly (readonly string[])[], + commands: readonly CoverageCommand[], + ): Promise { + const directory = join(this.root, COVERAGE_SHARD_DIRECTORY) + const manifest: CoverageShardManifest = { + shard: `${shard.index}/${shard.count}`, + root: this.root, + files: assignments.flat().sort(), + blobs: commands.map(command => basename(command.blobPath ?? '')).sort(), + } + const reportFiles = assignments.map((_, index) => join(this.temporaryRoot, `partition-${index + 1}.times.json`)) + await writeFile(join(directory, SHARD_MANIFEST_NAME), `${JSON.stringify(manifest, null, 1)}\n`, 'utf8') + const durations = [...collectPartitionDurations(reportFiles)].map(([file, duration]) => ({ file, duration })) + await writeFile(join(directory, SHARD_TIMES_NAME), `${JSON.stringify(durations, null, 1)}\n`, 'utf8') + } + /** * Distribute the instrumented inventory across partitions by recorded * duration, heaviest partition first so the longest child starts earliest @@ -578,6 +696,9 @@ export class CoveragePartitionCoordinator { this.projectOf = inventory.projectOf weights = readFileDurations(this.root) } + if (this.shard !== undefined) { + files = selectCoverageShardFiles(files, this.shard, file => statSync(join(this.root, file)).size) + } const buckets = assignWeightedPartitions(files, weights, this.partitions) buckets.sort((left, right) => partitionWeight(right, weights) - partitionWeight(left, weights)) return buckets @@ -599,7 +720,7 @@ export class CoveragePartitionCoordinator { } private partitionCommand(index: number, configPath: string): CoverageCommand { - const blobPath = join(this.blobsRoot, `partition-${index}.json`) + const blobPath = join(this.blobsRoot, `${this.blobPrefix}partition-${index}.json`) const reportsDirectory = join(this.temporaryRoot, `coverage-${index}`) const timingReportPath = join(this.temporaryRoot, `partition-${index}.times.json`) const invocation = pnpmInvocation([ @@ -632,21 +753,7 @@ export class CoveragePartitionCoordinator { } private mergeCommand(): CoverageCommand { - const invocation = pnpmInvocation([ - 'exec', - 'vitest', - `--merge-reports=${this.relativePath(this.blobsRoot)}`, - '--coverage', - ], { npm_execpath: this.pnpmEntrypoint }) - return { - label: 'merged coverage report', - ...invocation, - env: { - [COVERAGE_PARTITIONS_ENV]: undefined, - [COVERAGE_PARTITION_MODE_ENV]: undefined, - }, - cwd: this.root, - } + return mergeReportsCommand(this.root, this.pnpmEntrypoint, this.blobsRoot) } private relativePath(path: string): string { @@ -691,10 +798,167 @@ export class CoveragePartitionCoordinator { } } +/** Construction inputs for {@link mergeCoverageShards}. */ +export interface CoverageShardMergeOptions { + /** Repository root that owns coverage output. */ + root: string + /** pnpm JavaScript or executable entrypoint from `npm_execpath`. */ + pnpmEntrypoint: string + /** Directory outside `coverage/` whose immediate subdirectories each hold one shard's `coverage/shard/` output. */ + inputDirectory: string + /** Child executor, injectable for tests. */ + runCommand?: CoverageCommandRunner + /** Instrumented inventory; collected from the workspace when absent. */ + inventory?: readonly string[] +} + +/** One shard's validated output directory. */ +interface ShardOutput { + directory: string + shard: CoverageShard + root: string + files: string[] + blobs: string[] +} + +/** + * Merge the blobs of every file shard into one report with thresholds. Before + * merging, the shard file lists must be disjoint, their union must equal the + * re-listed instrumented inventory, and every listed blob must be present; + * the shards' measured durations replace `.coverage-times.json`. + * @param options - the repository, shard outputs, and optional injected executor and inventory. + * @returns zero only when the merged report and its thresholds pass. + * @throws when a shard output is malformed or the shards do not cover the inventory exactly once. + */ +export async function mergeCoverageShards(options: CoverageShardMergeOptions): Promise { + const coverageRoot = join(options.root, 'coverage') + const input = relative(coverageRoot, options.inputDirectory) + if (input === '' || (!input.startsWith('..') && !isAbsolute(input))) { + throw new Error(`coverage shard merge: input ${options.inputDirectory} must lie outside ${coverageRoot}, which the merge replaces.`) + } + await removeOwnedTree(coverageRoot) + const mergeRoot = join(coverageRoot, '.merge') + const blobsRoot = join(mergeRoot, SHARD_BLOBS_NAME) + await mkdir(blobsRoot, { recursive: true }) + const shards = await readShardOutputs(options.inputDirectory) + const inventory = options.inventory + ?? (await collectInstrumentedFiles(options.root, options.pnpmEntrypoint, join(mergeRoot, 'inventory.json'))).files + assertShardsCoverInventory(shards, inventory) + const blobNames = new Set() + for (const output of shards) { + for (const blob of output.blobs) { + if (blobNames.has(blob)) throw new Error(`coverage shard merge: blob ${blob} appears in more than one shard.`) + blobNames.add(blob) + await copyShardBlob(join(output.directory, SHARD_BLOBS_NAME, blob), join(blobsRoot, blob), output.root, options.root) + } + } + writeFileDurations(options.root, collectPartitionDurations(shards.map(output => join(output.directory, SHARD_TIMES_NAME))), inventory) + const command = mergeReportsCommand(options.root, options.pnpmEntrypoint, blobsRoot) + console.log(`coverage-partitions: start ${command.label} of ${shards.length} shards`) + const result = await (options.runCommand ?? runCoverageCommand)(command) + if (commandFailed(result)) { + console.error(`coverage-partitions: FAIL ${command.label} (${commandFailureReason(result)})`) + return 1 + } + await removeOwnedTree(mergeRoot) + return 0 +} + +/** + * Copy one shard blob into the merge directory. A blob records absolute source + * paths under its shard's checkout, and the merge keys coverage by those + * paths, so a shard whose checkout differs from this one has its root prefix + * rewritten in the serialized JSON strings to the merging checkout. + */ +async function copyShardBlob(source: string, target: string, shardRoot: string, mergeRoot: string): Promise { + if (shardRoot === mergeRoot) { + await copyFile(source, target) + return + } + const quoted = (path: string): string => JSON.stringify(`${path}${sep}`).slice(1, -1) + const content = await readFile(source, 'utf8') + await writeFile(target, content.split(quoted(shardRoot)).join(quoted(mergeRoot)), 'utf8') +} + +/** Read and validate every shard directory, requiring shards 1..count exactly once. */ +async function readShardOutputs(inputDirectory: string): Promise { + const entries = (await readdir(inputDirectory, { withFileTypes: true })).filter(entry => entry.isDirectory()) + const outputs = await Promise.all(entries.map(async (entry) => { + const directory = join(inputDirectory, entry.name) + const manifest: unknown = JSON.parse(await readFile(join(directory, SHARD_MANIFEST_NAME), 'utf8')) + if (manifest === null || typeof manifest !== 'object' || !('shard' in manifest) || typeof manifest.shard !== 'string' + || !('root' in manifest) || typeof manifest.root !== 'string' || !isAbsolute(manifest.root) + || !('files' in manifest) || !isStringArray(manifest.files) + || !('blobs' in manifest) || !isStringArray(manifest.blobs) || manifest.blobs.length === 0) { + throw new Error(`coverage shard merge: ${directory} needs a ${SHARD_MANIFEST_NAME} with shard, absolute root, files, and at least one blob.`) + } + const shard = parseCoverageShard(manifest.shard) + if (shard === undefined) throw new Error(`coverage shard merge: ${directory} names no shard.`) + for (const blob of manifest.blobs) { + const path = join(directory, SHARD_BLOBS_NAME, blob) + const metadata = basename(blob) === blob ? await lstatIfPresent(path) : undefined + if (metadata === undefined || !metadata.isFile() || metadata.size === 0) { + throw new Error(`coverage shard merge: shard ${manifest.shard} blob ${blob} is missing or empty at ${path}.`) + } + } + return { directory, shard, root: manifest.root, files: manifest.files, blobs: manifest.blobs } + })) + const count = outputs[0]?.shard.count + const indices = outputs.map(output => output.shard.index).sort((left, right) => left - right) + if (count === undefined || outputs.some(output => output.shard.count !== count) + || indices.length !== count || indices.some((index, position) => index !== position + 1)) { + throw new Error(`coverage shard merge: expected shards 1..n of one count under ${inputDirectory}, got ${JSON.stringify(outputs.map(output => `${output.shard.index}/${output.shard.count}`))}.`) + } + return outputs +} + +/** Require disjoint shard file lists whose union is exactly the instrumented inventory. */ +function assertShardsCoverInventory(shards: readonly ShardOutput[], inventory: readonly string[]): void { + const owner = new Map() + const overlapping: string[] = [] + for (const output of shards) { + for (const file of output.files) { + if (owner.has(file)) overlapping.push(file) + else owner.set(file, output.shard.index) + } + } + const expected = new Set(inventory) + const missing = inventory.filter(file => !owner.has(file)) + const unexpected = [...owner.keys()].filter(file => !expected.has(file)) + if (overlapping.length > 0 || missing.length > 0 || unexpected.length > 0) { + const sample = (files: readonly string[]): string => `${files.length} ${JSON.stringify(files.slice(0, 20))}` + throw new Error(`coverage shard merge: shard file lists must partition the instrumented inventory; overlapping ${sample(overlapping)}; missing ${sample(missing)}; unexpected ${sample(unexpected)}.`) + } +} + +function isStringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every(item => typeof item === 'string') +} + +/** The single `vitest --merge-reports` command that applies thresholds to a blob directory. */ +function mergeReportsCommand(root: string, pnpmEntrypoint: string, blobsRoot: string): CoverageCommand { + const invocation = pnpmInvocation([ + 'exec', + 'vitest', + `--merge-reports=${relative(root, blobsRoot).split(sep).join('/')}`, + '--coverage', + ], { npm_execpath: pnpmEntrypoint }) + return { + label: 'merged coverage report', + ...invocation, + env: { + [COVERAGE_PARTITIONS_ENV]: undefined, + [COVERAGE_PARTITION_MODE_ENV]: undefined, + }, + cwd: root, + } +} + /** Spawn one pnpm-backed command without a platform shell. */ function runCoverageCommand(command: CoverageCommand): Promise { return new Promise((resolveCommand) => { let outputTail = '' + const failures = new FailedTestCollector() const env = { ...process.env } for (const [name, value] of Object.entries(command.env)) { if (value === undefined) Reflect.deleteProperty(env, name) @@ -710,20 +974,84 @@ function runCoverageCommand(command: CoverageCommand): Promise { process.stdout.write(chunk) outputTail = appendOutputTail(outputTail, chunk) + failures.add('stdout', chunk) }) child.stderr.on('data', (chunk: string) => { process.stderr.write(chunk) outputTail = appendOutputTail(outputTail, chunk) + failures.add('stderr', chunk) }) child.once('error', (error: Error) => { - resolveCommand({ exitCode: null, signalCode: null, error: error.message, outputTail }) + resolveCommand({ exitCode: null, signalCode: null, error: error.message, outputTail, failedTests: failures.lines() }) }) child.once('close', (exitCode, signalCode) => { - resolveCommand({ exitCode, signalCode, outputTail }) + resolveCommand({ exitCode, signalCode, outputTail, failedTests: failures.lines() }) }) }) } +/** ANSI color sequences Vitest writes around status markers. */ +const ANSI_COLOR = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g') + +/** Maximum failed-test lines one command keeps for the run summary. */ +const FAILED_TEST_LINE_LIMIT = 50 + +/** + * Collect Vitest failure lines (`FAIL > ` and `× `) across + * output chunks, which can split a line, so a failure stays visible after a + * long interleaved log. + */ +export class FailedTestCollector { + private readonly partial = new Map() + private readonly found: string[] = [] + + /** + * Add one output chunk. + * @param stream - the chunk's stream; partial lines are joined per stream. + * @param chunk - decoded output. + */ + public add(stream: string, chunk: string): void { + const text = (this.partial.get(stream) ?? '') + chunk + const lines = text.split('\n') + this.partial.set(stream, lines.pop() ?? '') + for (const line of lines) this.consider(line) + } + + /** @returns the collected lines, including a trailing unterminated line. */ + public lines(): string[] { + for (const [stream, rest] of this.partial) { + this.consider(rest) + this.partial.set(stream, '') + } + return [...this.found] + } + + private consider(line: string): void { + const plain = line.replace(ANSI_COLOR, '').trim() + if (!/^(FAIL|×)\s/.test(plain) || this.found.length >= FAILED_TEST_LINE_LIMIT) return + if (!this.found.includes(plain)) this.found.push(plain) + } +} + +/** + * Repeat each failed partition and its failed tests after every partition has + * finished, so the cause is at the end of an interleaved multi-partition log. + */ +function reportFailedPartitions(commands: readonly CoverageCommand[], results: readonly CoverageCommandResult[]): void { + const failed = commands.flatMap((command, index) => { + const result = results[index] + return result !== undefined && commandFailed(result) ? [{ command, result }] : [] + }) + if (failed.length === 0) return + console.error(`coverage-partitions: ${String(failed.length)} of ${String(commands.length)} partition(s) failed:`) + for (const { command, result } of failed) { + console.error(` ${command.label} (${commandFailureReason(result)})`) + const tests = result.failedTests ?? [] + if (tests.length === 0) console.error(' no Vitest FAIL line; see the output tail above') + for (const test of tests) console.error(` ${test}`) + } +} + function appendOutputTail(previous: string, chunk: string): string { const combined = previous + chunk return combined.length <= 65_536 ? combined : combined.slice(-65_536) @@ -742,11 +1070,15 @@ function commandFailureReason(result: CoverageCommandResult): string { return facts.join(', ') || 'no exit code or signal' } -async function removeOwnedTree(path: string): Promise { - const metadata = await lstat(path).catch((error: unknown) => { +async function lstatIfPresent(path: string): Promise> | undefined> { + return await lstat(path).catch((error: unknown) => { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined throw error }) +} + +async function removeOwnedTree(path: string): Promise { + const metadata = await lstatIfPresent(path) if (metadata === undefined) return if (metadata.isSymbolicLink() || !metadata.isDirectory()) { await unlink(path) diff --git a/scripts/merge-coverage-shards.ts b/scripts/merge-coverage-shards.ts new file mode 100644 index 0000000000..7001bc0b10 --- /dev/null +++ b/scripts/merge-coverage-shards.ts @@ -0,0 +1,26 @@ +/** + * CLI entry that merges downloaded coverage shard outputs into one thresholded + * report. The single argument names a directory outside `coverage/` whose + * subdirectories each hold one shard's `coverage/shard/` output. + */ +import { resolve } from 'node:path' +import { COVERAGE_EXEMPT_ENV } from './coverage-exempt.ts' +import { forwardedCoverageArgs, mergeCoverageShards } from './coverage-partitions.ts' + +const [inputDirectory, ...extra] = forwardedCoverageArgs(process.argv.slice(2)) +if (inputDirectory === undefined || extra.length > 0) { + throw new Error('usage: pnpm run test:coverage:merge-shards ') +} +const pnpmEntrypoint = process.env.npm_execpath +if (pnpmEntrypoint === undefined || pnpmEntrypoint === '') { + throw new Error('coverage shard merge must be invoked through a pnpm package script.') +} +// The shards ran with the exempt heavy suites excluded; the inventory +// listing and the merged report read the same configuration. +process.env[COVERAGE_EXEMPT_ENV] = '1' + +process.exitCode = await mergeCoverageShards({ + root: resolve(import.meta.dirname, '..'), + pnpmEntrypoint, + inputDirectory: resolve(inputDirectory), +}) diff --git a/scripts/run-coverage-partitions.ts b/scripts/run-coverage-partitions.ts index 4b2293c148..027efc78a6 100644 --- a/scripts/run-coverage-partitions.ts +++ b/scripts/run-coverage-partitions.ts @@ -1,10 +1,12 @@ -/** CLI entry for partitioned Vitest coverage. */ +/** CLI entry for partitioned Vitest coverage, optionally limited to one `DSH_COVERAGE_SHARD` file shard. */ import { resolve } from 'node:path' import { COVERAGE_PARTITIONS_ENV, + COVERAGE_SHARD_ENV, CoveragePartitionCoordinator, forwardedCoverageArgs, parseCoveragePartitionCount, + parseCoverageShard, } from './coverage-partitions.ts' const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV]) @@ -16,10 +18,12 @@ if (pnpmEntrypoint === undefined || pnpmEntrypoint === '') { throw new Error('partitioned coverage must be invoked through a pnpm package script.') } +const shard = parseCoverageShard(process.env[COVERAGE_SHARD_ENV]) const coordinator = new CoveragePartitionCoordinator({ root: resolve(import.meta.dirname, '..'), partitions, pnpmEntrypoint, vitestArgs: forwardedCoverageArgs(process.argv.slice(2)), + ...shard === undefined ? {} : { shard }, }) process.exitCode = await coordinator.run() diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index 4ac9318145..80736e7bfd 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -25,6 +25,7 @@ import { // DSH_COVERAGE_PARTITIONS to every child). beforeEach(() => { vi.stubEnv('DSH_WEB_SNAPSHOT_WORKERS', undefined) + vi.stubEnv('DSH_COVERAGE_SHARD', undefined) vi.stubEnv('DSH_COVERAGE_MAX_WORKERS', undefined) vi.stubEnv('DSH_COVERAGE_PARTITIONS', undefined) vi.stubEnv('DSH_CLI_HELP_CONCURRENCY', undefined) @@ -757,6 +758,37 @@ describe('gate graph validation', () => { }) }) + it.each([ + ['1/2', true], + ['2/2', false], + ] as const)('runs coverage file shard %s with the exempt heavy suites only on the first shard', (shard, ownsExempt) => { + const subject = withEnv('DSH_COVERAGE_SHARD', shard, () => withEnv('DSH_COVERAGE_PARTITIONS', '4', () => + withPnpmEntrypoint(() => gatesForMode('ci-coverage-shard')))) + + expect(subject.map(item => [item.id, item.needs ?? []])).toEqual([ + ['native-system', []], + ['coverage', ['native-system']], + ...ownsExempt ? [['coverage-exempt-heavy', ['native-system']]] : [], + ]) + expect(subject[1]).toMatchObject({ + args: ['/private/pnpm.cjs', 'run', 'test:coverage:partitioned'], + env: { DSH_COVERAGE_EXEMPT_HEAVY: '1' }, + }) + }) + + it('refuses a coverage shard lane without a shard', () => { + expect(() => withEnv('DSH_COVERAGE_PARTITIONS', '4', () => + withPnpmEntrypoint(() => gatesForMode('ci-coverage-shard')))) + .toThrow('ci-coverage-shard requires DSH_COVERAGE_SHARD') + }) + + it('leaves the exempt share of the coverage budget only on the first shard', () => { + expect(ciWorkerEnvironment('ci-coverage-shard', { DSH_COVERAGE_MAX_WORKERS: '6', DSH_COVERAGE_SHARD: '1/2' }, 16)) + .toHaveProperty('DSH_COVERAGE_PARTITIONS', '4') + expect(ciWorkerEnvironment('ci-coverage-shard', { DSH_COVERAGE_MAX_WORKERS: '6', DSH_COVERAGE_SHARD: '2/2' }, 16)) + .toHaveProperty('DSH_COVERAGE_PARTITIONS', '6') + }) + it('rejects an invalid coverage partition count before starting a gate', () => { expect(() => withEnv('DSH_COVERAGE_PARTITIONS', '1', () => withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))) diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 9a3fe3e627..79992b49d6 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -11,7 +11,7 @@ import { resolve } from 'node:path' import { performance } from 'node:perf_hooks' import { CLIENT_BUILD_PROFILE_SELECTOR } from './client-build-environment.ts' import { COVERAGE_EXEMPT_ENV, coverageExemptHeavySuites } from './coverage-exempt.ts' -import { COVERAGE_PARTITIONS_ENV, parseCoveragePartitionCount } from './coverage-partitions.ts' +import { COVERAGE_PARTITIONS_ENV, COVERAGE_SHARD_ENV, parseCoveragePartitionCount, parseCoverageShard } from './coverage-partitions.ts' import { LOCAL_TEST_PARALLELISM_CAP, defaultParallelism, describeDefaultParallelism } from './parallelism.ts' import { pnpmInvocation } from './pnpm-invocation.ts' @@ -22,6 +22,7 @@ export type Mode = | 'ci-static' | 'ci-lint-contracts-ready' | 'ci-coverage' + | 'ci-coverage-shard' | 'ci-unit' | 'ci-bench' | 'ci-snapshot' @@ -165,6 +166,7 @@ function parseMode(raw: string | undefined): Mode { case 'ci-static': case 'ci-lint-contracts-ready': case 'ci-coverage': + case 'ci-coverage-shard': case 'ci-unit': case 'ci-bench': case 'ci-snapshot': @@ -185,7 +187,7 @@ function parseMode(raw: string | undefined): Mode { return raw default: throw new Error( - `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-unit | ci-bench | ci-snapshot | ci-artifacts | ci-consumers | ci-build | ci-consumers-prebuilt | ci-web-snapshot-prebuilt | ci-windows-blocking | ci-windows-complete | ci-windows-observational-ready | node-compat | check-all | hygiene | doc-sync | doc-quick | i18n, got ${JSON.stringify(raw)}.`, + `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-coverage-shard | ci-unit | ci-bench | ci-snapshot | ci-artifacts | ci-consumers | ci-build | ci-consumers-prebuilt | ci-web-snapshot-prebuilt | ci-windows-blocking | ci-windows-complete | ci-windows-observational-ready | node-compat | check-all | hygiene | doc-sync | doc-quick | i18n, got ${JSON.stringify(raw)}.`, ) } } @@ -256,7 +258,10 @@ export function ciWorkerEnvironment( if (!Number.isSafeInteger(total) || total < 1) { throw new Error(`run-gates: DSH_COVERAGE_MAX_WORKERS must be a positive integer, got ${JSON.stringify(coverageBudget)}.`) } - const instrumented = Math.max(1, total - Math.max(1, Math.floor(total / 3))) + // Only the first coverage shard runs the exempt sibling; the others give + // their partitions the whole budget. + const ownsExempt = mode !== 'ci-coverage-shard' || parseCoverageShard(env[COVERAGE_SHARD_ENV])?.index === 1 + const instrumented = ownsExempt ? Math.max(1, total - Math.max(1, Math.floor(total / 3))) : total if (instrumented > 1) setDefault(COVERAGE_PARTITIONS_ENV, instrumented) return additions } @@ -330,6 +335,8 @@ export function gatesForMode(selected: Mode): Gate[] { ] case 'ci-coverage': return coverageGates() + case 'ci-coverage-shard': + return coverageShardGates() case 'ci-unit': return ciUnitGates() case 'ci-bench': @@ -824,25 +831,55 @@ function coverageGates(platform: NodeJS.Platform = process.platform): Gate[] { label: 'test:coverage', env: { [COVERAGE_EXEMPT_ENV]: '1' }, }) - : pnpmScript('coverage', 'test:coverage:partitioned', { - label: 'test:coverage', - displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`, - env: { [COVERAGE_EXEMPT_ENV]: '1' }, - streamOutput: true, - }) + : partitionedCoverageGate(partitions) return [ pnpmScript('native-system', 'build:native-system'), ...electron, { ...instrumented, needs: ['native-system', ...electron.map(gate => gate.id)] }, - pnpmExec('coverage-exempt-heavy', [ - 'vitest', - 'run', - ...coverageExemptHeavySuites.map(suite => suite.filter), - ...workers.exempt, - ], { - label: 'test:coverage-exempt-heavy', - needs: ['native-system'], - }), + coverageExemptHeavyGate(workers.exempt), + ] +} + +function partitionedCoverageGate(partitions: number): Gate { + return pnpmScript('coverage', 'test:coverage:partitioned', { + label: 'test:coverage', + displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`, + env: { [COVERAGE_EXEMPT_ENV]: '1' }, + streamOutput: true, + }) +} + +function coverageExemptHeavyGate(workerArgs: readonly string[]): Gate { + return pnpmExec('coverage-exempt-heavy', [ + 'vitest', + 'run', + ...coverageExemptHeavySuites.map(suite => suite.filter), + ...workerArgs, + ], { + label: 'test:coverage-exempt-heavy', + needs: ['native-system'], + }) +} + +// One CI file shard of the instrumented inventory (DSH_COVERAGE_SHARD); the +// coordinator writes coverage/shard/ and the report job merges and applies +// thresholds. The first shard also runs the uninstrumented heavy suites with +// the coverage lane's usual worker split. Sharding needs the partition +// coordinator, so a missing count is a misconfiguration rather than a +// whole-inventory fallback. +function coverageShardGates(): Gate[] { + const shard = parseCoverageShard(process.env[COVERAGE_SHARD_ENV]) + if (shard === undefined) { + throw new Error(`run-gates: ci-coverage-shard requires ${COVERAGE_SHARD_ENV}.`) + } + const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV]) + if (partitions === undefined) { + throw new Error(`run-gates: ci-coverage-shard requires ${COVERAGE_PARTITIONS_ENV} or a coverage worker budget of at least 2.`) + } + return [ + pnpmScript('native-system', 'build:native-system'), + { ...partitionedCoverageGate(partitions), needs: ['native-system'] }, + ...shard.index === 1 ? [coverageExemptHeavyGate(coverageWorkerArgs().exempt)] : [], ] }