Skip to content

Commit d11cd52

Browse files
committed
fix(ci): guard timing refit sampling and publication
1 parent fec385c commit d11cd52

4 files changed

Lines changed: 170 additions & 110 deletions

File tree

‎.github/workflows/ci-test-timings-refit.yml‎

Lines changed: 53 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,23 @@ jobs:
1717
runs-on: ubuntu-24.04
1818
timeout-minutes: 30
1919
permissions:
20-
contents: write
21-
pull-requests: write
20+
contents: read
2221
steps:
2322
- name: Checkout
2423
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
2524
with:
2625
ref: ${{ github.sha }}
26+
fetch-depth: 0
2727
persist-credentials: false
2828

29+
- name: Verify generated PR App permissions
30+
uses: ./.github/actions/create-generated-pr-tokens
31+
with:
32+
contents-client-id: Iv23liOECG0slfuhz093
33+
contents-private-key: ${{ secrets.CLAWSWEEPER_APP_PRIVATE_KEY }}
34+
pull-request-client-id: Iv23liPJCozR0uHm6P7G
35+
pull-request-private-key: ${{ secrets.MANTIS_GITHUB_APP_PRIVATE_KEY }}
36+
2937
- name: Setup Node environment
3038
uses: ./.github/actions/setup-node-env
3139
with:
@@ -42,48 +50,58 @@ jobs:
4250
pnpm --silent ci:timings:refit > "$RUNNER_TEMP/ci-test-timings-report.md"
4351
if ! git diff --quiet -- config/ci-test-timings.json; then
4452
echo "changed=true" >> "$GITHUB_OUTPUT"
53+
delimiter="$(node -p 'crypto.randomUUID()')"
54+
{
55+
echo "report<<${delimiter}"
56+
cat "$RUNNER_TEMP/ci-test-timings-report.md"
57+
echo "${delimiter}"
58+
} >> "$GITHUB_OUTPUT"
4559
fi
4660
4761
- name: Update standing refit pull request
4862
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
63+
uses: ./.github/actions/publish-generated-pr
64+
with:
65+
contents-client-id: Iv23liOECG0slfuhz093
66+
contents-private-key: ${{ secrets.CLAWSWEEPER_APP_PRIVATE_KEY }}
67+
pull-request-client-id: Iv23liPJCozR0uHm6P7G
68+
pull-request-private-key: ${{ secrets.MANTIS_GITHUB_APP_PRIVATE_KEY }}
69+
base-branch: main
70+
head-branch: ci/test-timings-refit
71+
commit-message: "ci: refresh measured test timings"
72+
pr-title: "ci: refresh measured test timings"
73+
generated-paths: config/ci-test-timings.json
74+
invalidation-paths: |
75+
config/ci-test-timings.json
76+
scripts/ci-refit-test-timings.mts
77+
scripts/ci-run-timings.mjs
78+
scripts/lib/ci-test-timings-refit.mts
79+
scripts/lib/ci-test-timings-schema.mts
80+
scripts/lib/direct-run.mjs
81+
scripts/lib/numeric-options.mjs
82+
scripts/lib/plain-gh.mjs
83+
scripts/tsx.mjs
84+
package.json
85+
pnpm-lock.yaml
86+
.github/actions/create-generated-pr-tokens/action.yml
87+
.github/actions/publish-generated-pr/action.yml
88+
.github/workflows/ci-test-timings-refit.yml
89+
.github/workflows/ci.yml
90+
pr-body: |
91+
## What Problem This Solves
5992
60-
Refresh stale CI shard weights from successful main CI runs.
93+
Refresh stale CI shard weights from successful main-push CI runs.
6194
62-
## Why This Change Was Made
95+
## Why This Change Was Made
6396
64-
The daily refit uses medians, rejects outliers and single samples, and keeps existing weights when the new median is within 15% of them. Keys absent from every contributing run are removed only when their profile has observations from at least three sampled runs; the table below lists each removal explicitly.
97+
The daily refit uses medians, rejects outliers and single samples, and keeps existing weights when the new median is within 15% of them. Keys absent from every contributing run are removed only when their profile has observations from at least three sampled runs; the table below lists each removal explicitly.
6598
66-
## User Impact
99+
## User Impact
67100
68-
Only shard balance changes; test discovery still determines the complete test inventory. This standing branch is updated automatically and never pushes to main.
101+
Only shard balance changes; test discovery still determines the complete test inventory. This standing branch is updated automatically and never pushes to main.
69102
70-
## Evidence
103+
## Evidence
71104
72-
Generated with `pnpm ci:timings:refit`:
105+
Generated with `pnpm ci:timings:refit`:
73106
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
107+
${{ steps.refit.outputs.report }}

‎docs/ci.md‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,9 @@ invalid timing files, or `OPENCLAW_CI_TEST_TIMINGS=0`, use the cold-start estima
183183
for the entire file; stale keys cannot change the discovered test inventory.
184184

185185
With an authenticated `gh` CLI, run `pnpm ci:timings:refit` to regenerate the file
186-
from all attempts of the last five successful `ci.yml` runs on `main`. Use `--runs <n>` to change
186+
from all attempts of the last five successful `ci.yml` push runs on `main`. The
187+
refit validates each run's event, branch, and head SHA before reading job logs;
188+
manual dispatches are rejected even when launched from `main`. Use `--runs <n>` to change
187189
the sample window, `--repo <owner/repo>` to select a repository, `--out <path>` to
188190
write elsewhere, or `--dry-run` to print changed entries without writing.
189191
Measurements come only from successful UI E2E and compact jobs; compact groups
@@ -215,10 +217,13 @@ update. The gitignored `.artifacts/vitest-shard-timings.json` remains a separate
215217
whole-config timing cache for the local test-project runner, not an input to
216218
these CI packers.
217219

218-
This workflow uses only the repository's `GITHUB_TOKEN`. GitHub puts PR runs
219-
created by that token in an approval-required state; a maintainer must select
220-
**Approve workflows to run** and verify green CI on the current PR head before
221-
merging. Push events from this token do not start workflows. See
220+
The shared generated-PR publisher refreshes `main` and rejects stale generator
221+
inputs or overlapping timing-file changes before its leased branch push. It
222+
uses separate repository-scoped GitHub App tokens for branch and PR writes;
223+
the workflow's `GITHUB_TOKEN` has only contents-read permission. App-created
224+
events trigger CI without the `GITHUB_TOKEN`-specific workflow approval step.
225+
Normal repository review and required checks still apply; this workflow does
226+
not enable auto-merge. See
222227
[GitHub's workflow-trigger rules](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow#triggering-a-workflow-from-a-workflow).
223228

224229
## ClawSweeper activity forwarding

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ async function main() {
6868
created_at: z.iso.datetime(),
6969
status: z.literal("completed"),
7070
conclusion: z.literal("success"),
71+
// A dispatch from main can check out target_ref; only push runs prove the measured ref.
72+
event: z.literal("push"),
73+
head_branch: z.literal("main"),
74+
head_sha: z.string().regex(/^[a-f0-9]{40}$/u),
7175
}),
7276
);
7377
const listed: z.infer<typeof runPageSchema> = [];
@@ -80,9 +84,9 @@ async function main() {
8084
JSON.parse(
8185
await readGh([
8286
"api",
83-
`repos/${repo}/actions/workflows/ci.yml/runs?branch=main&status=success&per_page=${pageSize}&page=${page}`,
87+
`repos/${repo}/actions/workflows/ci.yml/runs?branch=main&event=push&status=success&per_page=${pageSize}&page=${page}`,
8488
"--jq",
85-
"[.workflow_runs[] | {id, created_at, status, conclusion}]",
89+
"[.workflow_runs[] | {id, created_at, status, conclusion, event, head_branch, head_sha}]",
8690
]),
8791
),
8892
);

‎test/scripts/ci-test-timings.test.ts‎

Lines changed: 101 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -295,22 +295,39 @@ describe("CI test timing refit", () => {
295295
).toEqual(first.timings);
296296
});
297297

298-
it("fetches only successful matching job logs, paginates, and keeps dry-run and unchanged refits byte-stable", () => {
299-
const directory = realpathSync(mkdtempSync(path.join(tmpdir(), "openclaw-ci-refit-")));
300-
const fakeGh = path.join(directory, "gh");
301-
const output = path.join(directory, "timings.json");
302-
const root = fileURLToPath(new URL("../../", import.meta.url));
303-
const log = uiLog({ [measuredFile]: 130 });
304-
writeFileSync(
305-
fakeGh,
306-
`#!/usr/bin/env node
298+
it.each([
299+
{ label: "main push retries", metadata: {}, invalidField: undefined },
300+
{
301+
label: "manual dispatch from main",
302+
metadata: { event: "workflow_dispatch" },
303+
invalidField: "event",
304+
},
305+
{
306+
label: "push to another branch",
307+
metadata: { head_branch: "feature" },
308+
invalidField: "head_branch",
309+
},
310+
{ label: "missing head commit", metadata: { head_sha: null }, invalidField: "head_sha" },
311+
])(
312+
"validates $label before fetching samples and preserves dry-run/unchanged bytes",
313+
({ metadata, invalidField }) => {
314+
const directory = realpathSync(mkdtempSync(path.join(tmpdir(), "openclaw-ci-refit-")));
315+
const fakeGh = path.join(directory, "gh");
316+
const output = path.join(directory, "timings.json");
317+
const requests = path.join(directory, "requests.json");
318+
const root = fileURLToPath(new URL("../../", import.meta.url));
319+
const log = uiLog({ [measuredFile]: 130 });
320+
writeFileSync(
321+
fakeGh,
322+
`#!/usr/bin/env node
307323
const args = process.argv.slice(2);
308324
const endpoint = args[1];
309325
if (args[0] === "api" && args[1] === "--help") {
310326
console.log("--allow-escape-sequences");
311-
} else if (endpoint === "repos/fixture/repo/actions/workflows/ci.yml/runs?branch=main&status=success&per_page=3&page=1") {
327+
} else if (endpoint.replace("&event=push", "") === "repos/fixture/repo/actions/workflows/ci.yml/runs?branch=main&status=success&per_page=3&page=1") {
312328
if (!args.includes("--jq")) process.exit(2);
313-
console.log(JSON.stringify([1, 2, 3].map(id => ({id, created_at: "2026-08-27T23:00:00Z", status: "completed", conclusion: "success"}))));
329+
require("node:fs").writeFileSync(${JSON.stringify(requests)}, JSON.stringify(args));
330+
console.log(JSON.stringify([1, 2, 3].map(id => ({id, created_at: "2026-08-27T23:00:00Z", status: "completed", conclusion: "success", event: "push", head_branch: "main", head_sha: "a".repeat(40), run_attempt: 2, ...${JSON.stringify(metadata)}}))));
314331
} else if (endpoint.includes("actions/runs/") && endpoint.includes("/jobs?filter=all&")) {
315332
if (!args.at(-1).includes("labels")) process.exit(2);
316333
const jobs = endpoint.endsWith("page=1")
@@ -334,65 +351,81 @@ if (args[0] === "api" && args[1] === "--help") {
334351
process.exit(2);
335352
}
336353
`,
337-
);
338-
chmodSync(fakeGh, 0o755);
339-
const original = `${JSON.stringify(
340-
{
341-
...baseline,
342-
compactGroupSeconds: { blacksmith: { deleted: 30 }, github: {} },
343-
},
344-
null,
345-
2,
346-
)}\n`;
347-
writeFileSync(output, original);
348-
const invoke = (dryRun: boolean) =>
349-
spawnSync(
350-
process.execPath,
351-
[
352-
"--import",
353-
"tsx",
354-
"scripts/ci-refit-test-timings.mts",
355-
"--runs",
356-
"3",
357-
"--repo",
358-
"fixture/repo",
359-
"--out",
360-
output,
361-
...(dryRun ? ["--dry-run"] : []),
362-
],
354+
);
355+
chmodSync(fakeGh, 0o755);
356+
const original = `${JSON.stringify(
363357
{
364-
cwd: root,
365-
encoding: "utf8",
366-
env: { ...process.env, OPENCLAW_GH_BIN: fakeGh, GH_TOKEN: "fixture-token" },
358+
...baseline,
359+
compactGroupSeconds: { blacksmith: { deleted: 30 }, github: {} },
367360
},
368-
);
369-
try {
370-
const dryRun = invoke(true);
371-
expect(dryRun.status, dryRun.stderr).toBe(0);
372-
expect(dryRun.stdout).toContain(`| uiE2e.fileSeconds.${measuredFile} | 100 | 130 | 30.0% |`);
373-
expect(dryRun.stdout).toContain(
374-
"| compactGroupSeconds.blacksmith.deleted | 30 | — | removed |",
375-
);
376-
expect(dryRun.stdout).toContain("Sampled successful main CI runs: 1, 2, 3");
377-
expect(readFileSync(output, "utf8")).toBe(original);
378-
const write = invoke(false);
379-
expect(write.status, write.stderr).toBe(0);
380-
const updated = readFileSync(output, "utf8");
381-
const timings = ciTestTimingsSchema.parse(JSON.parse(updated));
382-
expect(timings.uiE2e.fileSeconds[measuredFile]).toBe(130);
383-
expect(timings.compactGroupSeconds).toEqual({
384-
blacksmith: { "core-unit-src-security-2": 20 },
385-
github: { "core-unit-src-security-2": 50 },
386-
});
387-
expect(updated.endsWith("\n")).toBe(true);
388-
const unchanged = invoke(false);
389-
expect(unchanged.status, unchanged.stderr).toBe(0);
390-
expect(unchanged.stdout).toContain("No timing changes");
391-
expect(readFileSync(output, "utf8")).toBe(updated);
392-
} finally {
393-
rmSync(directory, { recursive: true, force: true });
394-
}
395-
});
361+
null,
362+
2,
363+
)}\n`;
364+
writeFileSync(output, original);
365+
const invoke = (dryRun: boolean) =>
366+
spawnSync(
367+
process.execPath,
368+
[
369+
"--import",
370+
"tsx",
371+
"scripts/ci-refit-test-timings.mts",
372+
"--runs",
373+
"3",
374+
"--repo",
375+
"fixture/repo",
376+
"--out",
377+
output,
378+
...(dryRun ? ["--dry-run"] : []),
379+
],
380+
{
381+
cwd: root,
382+
encoding: "utf8",
383+
env: { ...process.env, OPENCLAW_GH_BIN: fakeGh, GH_TOKEN: "fixture-token" },
384+
},
385+
);
386+
try {
387+
const dryRun = invoke(true);
388+
if (invalidField) {
389+
expect(dryRun.status, dryRun.stderr).toBe(1);
390+
expect(dryRun.stderr).toContain(invalidField);
391+
expect(dryRun.stdout).not.toContain("Sampled successful main CI runs");
392+
expect(readFileSync(output, "utf8")).toBe(original);
393+
return;
394+
}
395+
expect(dryRun.status, dryRun.stderr).toBe(0);
396+
expect(JSON.parse(readFileSync(requests, "utf8"))).toEqual([
397+
"api",
398+
"repos/fixture/repo/actions/workflows/ci.yml/runs?branch=main&event=push&status=success&per_page=3&page=1",
399+
"--jq",
400+
"[.workflow_runs[] | {id, created_at, status, conclusion, event, head_branch, head_sha}]",
401+
]);
402+
expect(dryRun.stdout).toContain(
403+
`| uiE2e.fileSeconds.${measuredFile} | 100 | 130 | 30.0% |`,
404+
);
405+
expect(dryRun.stdout).toContain(
406+
"| compactGroupSeconds.blacksmith.deleted | 30 | — | removed |",
407+
);
408+
expect(dryRun.stdout).toContain("Sampled successful main CI runs: 1, 2, 3");
409+
expect(readFileSync(output, "utf8")).toBe(original);
410+
const write = invoke(false);
411+
expect(write.status, write.stderr).toBe(0);
412+
const updated = readFileSync(output, "utf8");
413+
const timings = ciTestTimingsSchema.parse(JSON.parse(updated));
414+
expect(timings.uiE2e.fileSeconds[measuredFile]).toBe(130);
415+
expect(timings.compactGroupSeconds).toEqual({
416+
blacksmith: { "core-unit-src-security-2": 20 },
417+
github: { "core-unit-src-security-2": 50 },
418+
});
419+
expect(updated.endsWith("\n")).toBe(true);
420+
const unchanged = invoke(false);
421+
expect(unchanged.status, unchanged.stderr).toBe(0);
422+
expect(unchanged.stdout).toContain("No timing changes");
423+
expect(readFileSync(output, "utf8")).toBe(updated);
424+
} finally {
425+
rmSync(directory, { recursive: true, force: true });
426+
}
427+
},
428+
);
396429
});
397430

398431
describe("committed CI timing loader", () => {

0 commit comments

Comments
 (0)