Skip to content

Commit 430c2f8

Browse files
committed
ci: use committed measurements for test sharding
Regenerate UI file and runner-specific compact weights from successful CI log medians, with outlier filtering and a 15% write threshold. Keep existing hints as cold-start fallbacks and account for per-file UI overhead without deriving membership from timing keys. Add a daily standing-PR refit workflow, strict cached loading, fixture coverage, and operator docs. Verify all 302 UI files form identical complete partitions across 22 fresh processes.
1 parent 629a47e commit 430c2f8

14 files changed

Lines changed: 1655 additions & 230 deletions
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
name: CI Test Timings Refit
2+
3+
on:
4+
schedule:
5+
- cron: "43 9 * * *"
6+
workflow_dispatch:
7+
8+
permissions: {}
9+
10+
concurrency:
11+
group: ci-test-timings-refit
12+
cancel-in-progress: false
13+
14+
jobs:
15+
refit:
16+
if: github.repository == 'openclaw/openclaw' && github.ref == 'refs/heads/main'
17+
runs-on: ubuntu-24.04
18+
timeout-minutes: 30
19+
permissions:
20+
contents: write
21+
pull-requests: write
22+
steps:
23+
- name: Checkout
24+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
25+
with:
26+
ref: ${{ github.sha }}
27+
persist-credentials: false
28+
29+
- name: Setup Node environment
30+
uses: ./.github/actions/setup-node-env
31+
with:
32+
cache-mode: restore
33+
install-bun: "false"
34+
35+
- name: Refit measured test timings
36+
id: refit
37+
env:
38+
GH_TOKEN: ${{ github.token }}
39+
shell: bash
40+
run: |
41+
set -euo pipefail
42+
pnpm --silent ci:timings:refit > "$RUNNER_TEMP/ci-test-timings-report.md"
43+
if ! git diff --quiet -- config/ci-test-timings.json; then
44+
echo "changed=true" >> "$GITHUB_OUTPUT"
45+
fi
46+
47+
- name: Update standing refit pull request
48+
if: steps.refit.outputs.changed == 'true'
49+
env:
50+
GH_TOKEN: ${{ github.token }}
51+
shell: bash
52+
run: |
53+
set -euo pipefail
54+
branch=ci/test-timings-refit
55+
title='ci: refresh measured test timings'
56+
body="$RUNNER_TEMP/ci-test-timings-pr.md"
57+
cat > "$body" <<'EOF'
58+
## What Problem This Solves
59+
60+
Refresh stale CI shard weights from successful main CI runs.
61+
62+
## Why This Change Was Made
63+
64+
The daily refit uses medians, rejects outliers and single samples, and keeps existing weights when the new median is within 15% of them.
65+
66+
## User Impact
67+
68+
Only shard balance changes; test discovery still determines the complete test inventory. This standing branch is updated automatically and never pushes to main.
69+
70+
## Evidence
71+
72+
Generated with `pnpm ci:timings:refit`:
73+
74+
EOF
75+
cat "$RUNNER_TEMP/ci-test-timings-report.md" >> "$body"
76+
gh auth setup-git
77+
previous=$(git ls-remote origin "refs/heads/$branch" | cut -f1)
78+
git switch -c "$branch"
79+
git config user.name 'github-actions[bot]'
80+
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
81+
git add -- config/ci-test-timings.json
82+
git -c core.hooksPath=/dev/null commit -m "$title"
83+
git push --force-with-lease="refs/heads/$branch:$previous" origin "HEAD:refs/heads/$branch"
84+
pr=$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --base main --state open --limit 1 --json number --jq '.[0].number // empty')
85+
if [ -n "$pr" ]; then
86+
gh pr edit "$pr" --repo "$GITHUB_REPOSITORY" --title "$title" --body-file "$body"
87+
else
88+
gh pr create --repo "$GITHUB_REPOSITORY" --base main --head "$branch" --title "$title" --body-file "$body"
89+
fi

‎config/ci-test-timings.json‎

Lines changed: 441 additions & 0 deletions
Large diffs are not rendered by default.

‎docs/ci.md‎

Lines changed: 45 additions & 6 deletions
Large diffs are not rendered by default.

‎docs/reference/test.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ If `pnpm test` flakes on a loaded host, rerun once before treating it as a regre
229229
- `pnpm test:perf:profile:main` writes a CPU profile for the Vitest main thread (`.artifacts/vitest-main-profile`); `pnpm test:perf:profile:runner` writes CPU + heap profiles for the unit runner (`.artifacts/vitest-runner-profile`).
230230
- `pnpm test:perf:groups --full-suite --allow-failures --output .artifacts/test-perf/baseline-before.json`: runs every full-suite Vitest leaf config serially and writes grouped duration data plus per-config JSON/log artifacts. Full-suite reports isolate files by default so retained module graphs and GC pauses from earlier files are not charged to later assertions; pass `-- --no-isolate` only when intentionally profiling shared-worker accumulation. `pnpm test:perf:groups:compare .artifacts/test-perf/baseline-before.json .artifacts/test-perf/after-agent.json` compares grouped reports after a performance-focused change.
231231
- Full, extension, and include-pattern shard runs update local timing data in `.artifacts/vitest-shard-timings.json`; later whole-config runs use those timings to balance slow and fast shards. Include-pattern CI shards append the shard name to the timing key, which keeps filtered shard timings visible without replacing whole-config timing data. Set `OPENCLAW_TEST_PROJECTS_TIMINGS=0` to ignore the local timing artifact.
232+
- `pnpm ci:timings:refit`: regenerate committed `config/ci-test-timings.json` from the last five successful main CI runs; add `--dry-run` to preview the changed-entry table. This file owns per-file UI E2E and per-profile compact-group weights, unlike the gitignored `.artifacts/vitest-shard-timings.json` whole-config timing cache. Independent CI shards use only the committed weights, never that cache. See [CI timing refits](/ci#measured-shard-weights) for the daily refresh and sampling rules.
232233

233234
## Benchmarks
234235

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1572,6 +1572,7 @@
15721572
"check:workflows": "node --import ./scripts/tsx.mjs scripts/check-workflows.mts",
15731573
"ci:full-release": "node scripts/full-release-validation-at-sha.mjs",
15741574
"ci:timings": "node scripts/ci-run-timings.mjs --latest-main",
1575+
"ci:timings:refit": "node --import ./scripts/tsx.mjs scripts/ci-refit-test-timings.mts",
15751576
"ci:timings:recent": "node scripts/ci-run-timings.mjs --recent 10",
15761577
"ci:timings:trend": "node scripts/ci-run-timings.mjs --trend-hours 72 --compare-hours 12",
15771578
"clean:dist": "node -e \"require('fs').rmSync('dist', {recursive: true, force: true})\"",

‎scripts/ci-refit-test-timings.mts‎

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
#!/usr/bin/env -S node --import tsx
2+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3+
import path from "node:path";
4+
import { setTimeout } from "node:timers/promises";
5+
import { fileURLToPath } from "node:url";
6+
import { parseArgs } from "node:util";
7+
import { z } from "zod";
8+
import { isRetryableGhJsonErrorMessage } from "./ci-run-timings.mjs";
9+
import { refitTestTimings, type CiTimingRun } from "./lib/ci-test-timings-refit.mts";
10+
import { ciTestTimingsSchema } from "./lib/ci-test-timings-schema.mts";
11+
import { parsePositiveInt } from "./lib/numeric-options.mjs";
12+
import { execPlainGh } from "./lib/plain-gh.mjs";
13+
14+
const jobPageSchema = z.object({
15+
total_count: z.number().int().nonnegative(),
16+
jobs: z.array(
17+
z.object({
18+
id: z.number().int().positive(),
19+
name: z.string(),
20+
conclusion: z.string().nullable(),
21+
}),
22+
),
23+
});
24+
25+
async function readGh(args: string[]): Promise<string> {
26+
const retryDelays = [1000, 3000, 6000];
27+
for (let attempt = 0; ; attempt += 1) {
28+
try {
29+
return execPlainGh(args, {
30+
encoding: "utf8",
31+
timeout: 120_000,
32+
stdio: ["ignore", "pipe", "pipe"],
33+
});
34+
} catch (error) {
35+
if (
36+
attempt === retryDelays.length ||
37+
!isRetryableGhJsonErrorMessage(error instanceof Error ? error.message : String(error))
38+
) {
39+
throw error;
40+
}
41+
await setTimeout(retryDelays[attempt]);
42+
}
43+
}
44+
}
45+
46+
async function main() {
47+
const { values } = parseArgs({
48+
args: process.argv.slice(2).filter((arg) => arg !== "--"),
49+
options: {
50+
runs: { type: "string", default: "5" },
51+
repo: { type: "string", default: "openclaw/openclaw" },
52+
"dry-run": { type: "boolean", default: false },
53+
out: {
54+
type: "string",
55+
default: fileURLToPath(new URL("../config/ci-test-timings.json", import.meta.url)),
56+
},
57+
},
58+
});
59+
const count = parsePositiveInt(values.runs, "--runs");
60+
const repo = z
61+
.string()
62+
.regex(/^[\w.-]+\/[\w.-]+$/u)
63+
.parse(values.repo);
64+
const runPageSchema = z.array(
65+
z.object({
66+
id: z.number().int().positive(),
67+
created_at: z.iso.datetime(),
68+
status: z.literal("completed"),
69+
conclusion: z.literal("success"),
70+
}),
71+
);
72+
const listed: z.infer<typeof runPageSchema> = [];
73+
const pageSize = Math.min(count, 100);
74+
for (let page = 1; listed.length < count; page += 1) {
75+
if (page > 25) {
76+
throw new Error("Run pagination limit exceeded; reduce --runs");
77+
}
78+
const runs = runPageSchema.parse(
79+
JSON.parse(
80+
await readGh([
81+
"api",
82+
`repos/${repo}/actions/workflows/ci.yml/runs?branch=main&status=success&per_page=${pageSize}&page=${page}`,
83+
"--jq",
84+
"[.workflow_runs[] | {id, created_at, status, conclusion}]",
85+
]),
86+
),
87+
);
88+
listed.push(...runs);
89+
if (runs.length < pageSize) {
90+
break;
91+
}
92+
}
93+
if (listed.length === 0) {
94+
throw new Error("No successful main CI runs found");
95+
}
96+
// New gh versions reject reporter ANSI unless opted in; logs are parsed, never printed.
97+
const logFlags = (await readGh(["api", "--help"])).includes("--allow-escape-sequences")
98+
? ["--allow-escape-sequences"]
99+
: [];
100+
const runs: CiTimingRun[] = [];
101+
for (const run of listed.slice(0, count)) {
102+
const logs: CiTimingRun["logs"] = [];
103+
let seenJobs = 0;
104+
for (let page = 1; page <= 25; page += 1) {
105+
const payload = jobPageSchema.parse(
106+
JSON.parse(
107+
await readGh([
108+
"api",
109+
`repos/${repo}/actions/runs/${run.id}/jobs?filter=latest&per_page=100&page=${page}`,
110+
"--jq",
111+
"{total_count, jobs: [.jobs[] | {id, name, conclusion}]}",
112+
]),
113+
),
114+
);
115+
for (const job of payload.jobs) {
116+
if (job.conclusion !== "success") {
117+
continue;
118+
}
119+
const kind = job.name.startsWith("checks-ui-e2e (")
120+
? "uiE2e"
121+
: job.name.startsWith("checks-node-compact-")
122+
? "compact"
123+
: undefined;
124+
if (kind) {
125+
console.error(`[ci-timings] ${run.id}: ${job.name}`);
126+
logs.push({
127+
kind,
128+
text: await readGh(["api", `repos/${repo}/actions/jobs/${job.id}/logs`, ...logFlags]),
129+
});
130+
}
131+
}
132+
seenJobs += payload.jobs.length;
133+
if (seenJobs >= payload.total_count) {
134+
break;
135+
}
136+
if (payload.jobs.length === 0 || page === 25) {
137+
throw new Error(`Job pagination incomplete for CI run ${run.id}`);
138+
}
139+
}
140+
runs.push({ id: run.id, createdAt: run.created_at, logs });
141+
}
142+
let previous;
143+
try {
144+
previous = ciTestTimingsSchema.parse(JSON.parse(readFileSync(values.out, "utf8")));
145+
} catch {
146+
// A missing or invalid baseline has no measurements worth preserving.
147+
}
148+
const { timings, changes, runIds } = refitTestTimings(runs, previous);
149+
if (
150+
Object.keys(timings.uiE2e.fileSeconds).length +
151+
Object.keys(timings.compactGroupSeconds.blacksmith).length +
152+
Object.keys(timings.compactGroupSeconds.github).length ===
153+
0
154+
) {
155+
throw new Error("No test timings have at least two successful run samples");
156+
}
157+
ciTestTimingsSchema.parse(timings);
158+
console.log(`Sampled successful main CI runs: ${runIds.join(", ")}\n`);
159+
console.log("| Key | Old seconds | New seconds | Delta |\n| --- | ---: | ---: | ---: |");
160+
for (const change of changes) {
161+
const delta =
162+
change.old === undefined || change.old === 0
163+
? "new"
164+
: `${(((change.next - change.old) / change.old) * 100).toFixed(1)}%`;
165+
console.log(`| ${change.key} | ${change.old ?? "—"} | ${change.next} | ${delta} |`);
166+
}
167+
if (changes.length === 0) {
168+
console.log("\nNo timing changes exceed the 15% write threshold.");
169+
} else if (!values["dry-run"]) {
170+
mkdirSync(path.dirname(values.out), { recursive: true });
171+
writeFileSync(values.out, `${JSON.stringify(timings, null, 2)}\n`);
172+
}
173+
}
174+
175+
try {
176+
await main();
177+
} catch (error) {
178+
console.error(error instanceof Error ? error.message : String(error));
179+
console.error("[ci-timings] FAILED (exit 1)");
180+
process.exitCode = 1;
181+
}

‎scripts/lib/ci-node-test-plan.mts‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
getUnitFastTimerTestFiles,
2222
} from "../../test/vitest/vitest.unit-fast-paths.mjs";
2323
import { boundaryTestFiles, isUnitConfigTestFile } from "../../test/vitest/vitest.unit-paths.mjs";
24+
import { readCompactGroupTimings } from "./ci-test-timings.mts";
2425
import { listTrackedTestFiles } from "./list-test-files.mts";
2526
import {
2627
resolveVitestPretestBuildMode,
@@ -206,14 +207,8 @@ const AGENTIC_GATEWAY_CORE_STRIPES = 3;
206207
const CORE_RUNTIME_MEDIA_UI_STRIPES = 3;
207208
const CORE_UNIT_SRC_SECURITY_STRIPES = 3;
208209
const UNIT_FAST_NODE_TEST_STRIPES = 2;
209-
// Advisory runtime estimates (seconds) per split shard: median [shard:*]
210-
// begin->end wall across nine successful hosted compact runs (31684307744,
211-
// 31683213137, 31682494259, 31682258389, 31681118857, 31680010311,
212-
// 31678309660, 31678086868, 31677305067). Admission and 4-vCPU striping
213-
// retain these weights so the bounded job count and runner advisory stay fixed.
214-
// agentic-commands-agent-channel uses the sole post-#122955 sample from run
215-
// 31684307744 because that landing removed a 79.5s test. Unknown shards fall
216-
// back to a per-file estimate.
210+
// Cold-start fallback when committed CI measurements are missing. Refresh
211+
// config/ci-test-timings.json with pnpm ci:timings:refit, not these literals.
217212
const COMPACT_GROUP_SECONDS_HINTS = new Map<string, number>([
218213
["agentic-agents-core-auth", 30],
219214
["agentic-agents-core-isolated", 18],
@@ -665,7 +660,9 @@ function applyCompactGroupWorkerPins(group: NodeTestShardGroup): NodeTestShardGr
665660
}
666661

667662
function estimateDefaultCompactGroupSeconds(group: NodeTestShardGroup): number {
668-
const hint = COMPACT_GROUP_SECONDS_HINTS.get(group.shard_name);
663+
const hint =
664+
readCompactGroupTimings("blacksmith")[group.shard_name] ??
665+
COMPACT_GROUP_SECONDS_HINTS.get(group.shard_name);
669666
if (hint !== undefined) {
670667
return hint;
671668
}
@@ -705,6 +702,7 @@ function estimateCompactGroupSeconds(
705702
return defaultSeconds;
706703
}
707704
return (
705+
readCompactGroupTimings("github")[group.shard_name] ??
708706
COMPACT_GITHUB_GROUP_SECONDS_HINTS.get(group.shard_name) ??
709707
Math.round(defaultSeconds * COMPACT_GITHUB_GROUP_SECONDS_SCALE)
710708
);

0 commit comments

Comments
 (0)