ci: balance test shards and reuse package download caches

This commit is contained in:
morluto
2026-10-11 16:40:17 +08:00
parent e8528cedcd
commit 40b37aeee1
5 changed files with 335 additions and 0 deletions
@@ -0,0 +1,155 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { fc, it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
allocateByDuration,
parseTestDurations,
readTestDurations,
} from "../../ciTestSequencer.js";
describe("CI test history", () => {
it("uses only successful in-root file durations", () => {
const root = resolve("/workspace/rea");
const durations = parseTestDurations(
JSON.stringify({
success: true,
numFailedTests: 0,
testResults: [
{
name: join(root, "tests/slow.test.ts"),
startTime: 10,
endTime: 110,
},
{
name: join(root, "tests/slow.test.ts"),
startTime: 20,
endTime: 80,
},
{
name: resolve(root, "../outside.test.ts"),
startTime: 10,
endTime: 1000,
},
null,
],
}),
root,
);
expect(durations).toEqual(new Map([["tests/slow.test.ts", 100]]));
expect(
parseTestDurations('{"success": false, "numFailedTests": 1}', root),
).toBeUndefined();
expect(parseTestDurations("not json", root)).toBeUndefined();
expect(parseTestDurations("null", root)).toBeUndefined();
});
it("falls back for missing history while preserving real filesystem errors", async () => {
const temporaryRoot = await createTestTempDirectory("rea-ci-sequencer-");
const missing = await readTestDurations(
join(temporaryRoot, "missing.json"),
temporaryRoot,
);
expect(missing).toBeUndefined();
const directory = join(temporaryRoot, "directory");
await mkdir(directory);
const reportPath = join(temporaryRoot, "report.json");
await writeFile(reportPath, "{");
expect(await readTestDurations(reportPath, temporaryRoot)).toBeUndefined();
await expect(
readTestDurations(directory, temporaryRoot),
).rejects.toMatchObject({
code: "EISDIR",
});
});
});
describe("duration shard allocation", () => {
it.prop([
fc.uniqueArray(fc.integer({ min: 0, max: 10_000 }), {
minLength: 1,
maxLength: 80,
}),
fc.integer({ min: 3, max: 8 }),
])(
"is complete, disjoint, reference-preserving, and input-order independent",
(ids, shardCount) => {
const items = ids.map((id, index) => ({
id,
path: `tests/${id}.test.ts`,
project: `project-${id % 3}`,
pool: id % 2 === 0 ? "forks" : "threads",
duration: index > 0 && id % 5 === 0 ? undefined : (id % 17) + 1,
}));
const specifications = items.map((item) => ({
item,
key: `${item.path}\0${item.project}\0${item.pool}`,
duration: item.duration,
}));
const shards = allocateByDuration(specifications, shardCount);
const reversedShards = allocateByDuration(
[...specifications].reverse(),
shardCount,
);
expect(shards).toBeDefined();
expect(reversedShards).toEqual(shards);
const assigned = shards!.flat();
expect(assigned).toHaveLength(items.length);
expect(new Set(assigned).size).toBe(items.length);
expect(assigned.every((item) => items.includes(item))).toBe(true);
},
);
it("keeps tied path, project, pool, and new-file entries deterministic", () => {
const items = [
{
id: "a",
path: "tests/shared.test.ts",
project: "alpha",
pool: "forks",
duration: 10,
},
{
id: "b",
path: "tests/shared.test.ts",
project: "beta",
pool: "forks",
duration: 10,
},
{
id: "c",
path: "tests/shared.test.ts",
project: "beta",
pool: "threads",
duration: 10,
},
{
id: "new",
path: "tests/new.test.ts",
project: "alpha",
pool: "forks",
duration: undefined,
},
];
const specifications = items.map((item) => ({
item,
key: `${item.path}\0${item.project}\0${item.pool}`,
duration: item.duration,
}));
const shards = allocateByDuration(specifications, 3);
const reversedShards = allocateByDuration([...specifications].reverse(), 3);
expect(shards).toBeDefined();
expect(reversedShards).toEqual(shards);
expect(shards!.flat()).toHaveLength(items.length);
expect(new Set(shards!.flat()).size).toBe(items.length);
});
});
+125
View File
@@ -0,0 +1,125 @@
import { readFile } from "node:fs/promises";
import { isAbsolute, relative, resolve, sep } from "node:path";
import { BaseSequencer, type TestSpecification } from "vitest/node";
import { z } from "zod";
const reportSchema = z.object({
success: z.literal(true),
numFailedTests: z.literal(0),
testResults: z.array(z.unknown()),
});
const fileSchema = z.object({
name: z.string(),
startTime: z.number(),
endTime: z.number(),
});
export function parseTestDurations(
contents: string,
root: string,
): Map<string, number> | undefined {
let value: unknown;
try {
value = JSON.parse(contents);
} catch (error) {
if (error instanceof SyntaxError) return undefined;
throw error;
}
const report = reportSchema.safeParse(value);
if (!report.success) return undefined;
const durations = new Map<string, number>();
for (const value of report.data.testResults) {
const result = fileSchema.safeParse(value);
if (!result.success) continue;
const { name, startTime, endTime } = result.data;
const duration = endTime - startTime;
const path = relative(root, resolve(root, name));
if (
!Number.isFinite(duration) ||
duration <= 0 ||
path === "" ||
path === ".." ||
path.startsWith(".." + sep) ||
isAbsolute(path)
)
continue;
const key = path.split(sep).join("/");
durations.set(key, Math.max(durations.get(key) ?? 0, duration));
}
return durations.size ? durations : undefined;
}
export async function readTestDurations(
historyPath: string,
root: string,
): Promise<Map<string, number> | undefined> {
try {
return parseTestDurations(await readFile(historyPath, "utf8"), root);
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT")
return undefined;
throw error;
}
}
type TimedItem<T> = { item: T; key: string; duration: number | undefined };
/** Distribute the longest files first, retaining every discovered specification. */
export function allocateByDuration<T>(
items: readonly TimedItem<T>[],
shardCount: number,
): T[][] | undefined {
if (!Number.isInteger(shardCount) || shardCount < 1)
throw new RangeError("shardCount must be a positive integer");
const known = items
.flatMap(({ duration }) => (duration === undefined ? [] : [duration]))
.sort((left, right) => left - right);
if (!known.length) return undefined;
const lower = known[Math.floor((known.length - 1) / 2)]!;
const median = lower + (known[Math.floor(known.length / 2)]! - lower) / 2;
const ordered = items.toSorted(
(left, right) =>
(right.duration ?? median) - (left.duration ?? median) ||
(left.key < right.key ? -1 : left.key > right.key ? 1 : 0),
);
const shards = Array.from({ length: shardCount }, () => ({
duration: 0,
items: [] as T[],
}));
for (const entry of ordered) {
const lightest = shards.reduce((left, right) =>
right.duration < left.duration ? right : left,
);
lightest.items.push(entry.item);
lightest.duration += entry.duration ?? median;
}
return shards.map(({ items }) => items);
}
export class CiTestSequencer extends BaseSequencer {
override async shard(
files: TestSpecification[],
): Promise<TestSpecification[]> {
const historyPath = process.env.REA_CI_TEST_HISTORY;
const shard = this.ctx.config.shard;
if (!historyPath || !shard) return super.shard(files);
const root = this.ctx.config.root;
const durations = await readTestDurations(historyPath, root);
if (!durations) return super.shard(files);
const weighted = files.map((item) => {
const path = relative(root, resolve(root, item.moduleId))
.split(sep)
.join("/");
return {
item,
key: path + "\0" + item.project.name + "\0" + item.pool,
duration: durations.get(path),
};
});
const shards = allocateByDuration(weighted, shard.count);
return shards ? shards[shard.index - 1]! : super.shard(files);
}
}