Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

weightedShardSequencer.ts

44 lines2.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - vitest loads this sequencer from the config,
2// outside any Effect runtime, and only needs path.relative.
3import * as NodePath from "node:path";
4​
5import { BaseSequencer, type TestSpecification } from "vite-plus/test/node";
6​
7import shardWeights from "./shardWeights.json" with { type: "json" };
8​
9// The median recorded file, for files added since the weights were recorded.
10const UNRECORDED_FILE_SECONDS = 0.6;
11​
12const recordedSeconds: Readonly<Record<string, number>> = shardWeights;
13​
14/**
15 * Splits server test files across `--shard` runs by recorded duration. Vitest's
16 * default split hashes file paths into equal-count shards, which can put the
17 * slowest files on one runner. Here the longest file goes to the lightest shard
18 * first. Every shard derives the same split from the same file list, so each
19 * file still runs in exactly one shard. Weights are each file's wall time in a
20 * CI shard, imports included: the gaps between consecutive file results in the
21 * `Test Server` logs. Imports are about a third of a shard, so test time alone
22 * leaves the shards with many small files slowest.
23 */
24export class WeightedShardSequencer extends BaseSequencer {
25 override async shard(files: TestSpecification[]) {
26 const { index, count } = this.ctx.config.shard ?? { index: 1, count: 1 };
27 const weighted = files
28 .map((spec) => {
29 const key = NodePath.relative(this.ctx.config.root, spec.moduleId).replaceAll("\\", "/");
30 return { spec, key, seconds: recordedSeconds[key] ?? UNRECORDED_FILE_SECONDS };
31 })
32 .toSorted((a, b) => b.seconds - a.seconds || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
33​
34 const loads = Array.from({ length: count }, () => 0);
35 const picked: TestSpecification[] = [];
36 for (const file of weighted) {
37 const least = Math.min(...loads);
38 const lightest = loads.indexOf(least);
39 loads[lightest] = least + file.seconds;
40 if (lightest === index - 1) picked.push(file.spec);
41 }
42 return picked;
43 }