Repository navigation
ci(macos): run macOS jobs on a self-hosted Mac runner while it is free (needs owner OK) #2835
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
devswha
wants to merge
2
commits into
main
Choose a base branch
from
ci/eamac-mac-runner
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+457
−14
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| #!/usr/bin/env bash | ||
| # Picks the runner for the macOS jobs (ci.yml's Native macOS session identity, remote-bundles.yml's | ||
| # macos-15 bundle) and prints `macos=<json>` for $GITHUB_OUTPUT: the maintainer's Mac runner | ||
| # (scripts/self-hosted-runner/README.md "Mac runner", label self-hosted-ovis-mac) while it looks | ||
| # online and free, GitHub's macos-15 otherwise. | ||
| # | ||
| # Only a same-repository pull request and a push to main may go to the Mac; a fork pull request, | ||
| # a tag, a dispatch or a release run always gets macos-15. The workflow token cannot list runners, | ||
| # so "online" comes from the repository variable CI_MAC_RUNNER_SEEN: the epoch seconds at which | ||
| # scripts/self-hosted-runner/mac-heartbeat.sh, run every minute with an admin token, last saw the | ||
| # runner online. Unset or older than MAC_SEEN_SECONDS (default 300) keeps the job hosted, so a job | ||
| # is never sent to a Mac that is already offline. The Actions API then guards the rest: a job that | ||
| # has waited for that label longer than MAC_STALE_MINUTES (default 10) means the Mac is stuck, and | ||
| # MAC_MAX_JOBS (default 2) unfinished jobs on it means it is busy; either keeps the job hosted, as | ||
| # does an API failure. The | ||
| # repository variable CI_MAC_SELF_HOSTED_LABELS set to "macos-15" keeps every macOS job hosted. | ||
| # This script runs from the checked-out revision, which a fork pull request controls; the runner | ||
| # itself refuses fork code (scripts/self-hosted-runner/job-started.sh). | ||
| set -euo pipefail | ||
|
|
||
| hosted='"macos-15"' | ||
| mac_labels='["self-hosted","self-hosted-ovis-mac"]' | ||
| event="${EVENT_NAME:-}" | ||
| configured="${CONFIGURED_LABELS:-}" | ||
| stale_minutes="${MAC_STALE_MINUTES:-10}" | ||
| max_jobs="${MAC_MAX_JOBS:-2}" | ||
| seen_seconds="${MAC_SEEN_SECONDS:-300}" | ||
| seen="${RUNNER_SEEN:-}" | ||
|
|
||
| hosted_because() { | ||
| echo "Runner: macos-15 ($1)" >&2 | ||
| echo "macos=$hosted" | ||
| exit 0 | ||
| } | ||
|
|
||
| # Prints "<unfinished> <stale>": the unfinished jobs of queued or running workflow runs that ask for | ||
| # the Mac's label, and how many of them have been queued longer than $stale_minutes; fails when the | ||
| # API does. | ||
| mac_jobs() { | ||
| local ids id jobs counts unfinished=0 stale=0 now | ||
| now="${ROUTE_NOW:-$(date +%s)}" | ||
| ids=$(for status in in_progress queued; do | ||
| gh api --paginate "repos/$REPOSITORY/actions/runs?status=$status&per_page=100" | jq '.workflow_runs[].id' || exit 1 | ||
| done) || return 1 | ||
| for id in $ids; do | ||
| jobs=$(gh api --paginate "repos/$REPOSITORY/actions/runs/$id/jobs?filter=latest&per_page=100") || return 1 | ||
| counts=$(jq -s -e -r --argjson now "$now" --argjson stale "$((stale_minutes * 60))" ' | ||
| [.[].jobs[] | select(.status != "completed") | ||
| | select([.labels[] | ascii_downcase] | index("self-hosted-ovis-mac") != null)] | ||
| | "\(length) \([.[] | select(.status == "queued" and ($now - (.created_at | fromdateiso8601)) > $stale)] | length)"' <<<"$jobs") || return 1 | ||
| unfinished=$((unfinished + ${counts% *})) | ||
| stale=$((stale + ${counts#* })) | ||
| done | ||
| echo "$unfinished $stale" | ||
| } | ||
|
|
||
| if [[ ("$event" == "pull_request" || "$event" == "pull_request_target") && "${HEAD_REPO:-}" != "${REPOSITORY:-}" ]]; then | ||
| hosted_because "pull request from fork ${HEAD_REPO:-unknown}" | ||
| fi | ||
| if [[ -n "${configured//[[:space:]]/}" ]]; then | ||
| [[ "${configured//[[:space:]]/}" == "$hosted" ]] || | ||
| { echo "::error::repository variable CI_MAC_SELF_HOSTED_LABELS must be \"macos-15\" or unset, got: $configured" >&2; exit 1; } | ||
| hosted_because "from repository variable CI_MAC_SELF_HOSTED_LABELS" | ||
| fi | ||
| if ! [[ "$event" == pull_request || ("$event" == push && "${REF:-}" == refs/heads/main) ]]; then | ||
| hosted_because "${event:-unknown event} ${REF:-}" | ||
| fi | ||
| for value in "$stale_minutes" "$max_jobs" "$seen_seconds"; do | ||
| [[ "$value" =~ ^[0-9]{1,4}$ ]] || { echo "::error::MAC_STALE_MINUTES, MAC_MAX_JOBS and MAC_SEEN_SECONDS must be whole numbers, got: $value" >&2; exit 1; } | ||
| done | ||
| stale_minutes=$((10#$stale_minutes)) | ||
| max_jobs=$((10#$max_jobs)) | ||
| seen_seconds=$((10#$seen_seconds)) | ||
|
|
||
| seen="${seen//[[:space:]]/}" | ||
| if ! [[ "$seen" =~ ^[0-9]{1,12}$ ]]; then | ||
| hosted_because "Mac runner heartbeat CI_MAC_RUNNER_SEEN unset or not a number" | ||
| fi | ||
| age=$(( ${ROUTE_NOW:-$(date +%s)} - 10#$seen )) | ||
| if (( age > seen_seconds || age < -60 )); then | ||
| hosted_because "Mac runner last seen online ${age}s ago" | ||
| fi | ||
|
|
||
| if ! counts=$(mac_jobs); then | ||
| echo "::warning::could not count the Mac runner's jobs; using macos-15" >&2 | ||
| hosted_because "Actions API failed" | ||
| fi | ||
| unfinished=${counts% *} | ||
| stale=${counts#* } | ||
| if (( stale > 0 )); then | ||
| hosted_because "a job has waited over $stale_minutes minutes for the Mac runner: offline?" | ||
| elif (( unfinished >= max_jobs )); then | ||
| hosted_because "$unfinished jobs already on the Mac runner" | ||
| fi | ||
| echo "Runner: self-hosted $mac_labels ($unfinished jobs on the Mac runner)" >&2 | ||
| echo "macos=$mac_labels" | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| import { afterAll, describe, expect, it } from "bun:test"; | ||
| import { spawnSync } from "node:child_process"; | ||
| import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | ||
| import { tmpdir } from "node:os"; | ||
| import { join } from "node:path"; | ||
| import { fileURLToPath } from "node:url"; | ||
|
|
||
| const script = fileURLToPath(new URL("./ci-mac-runner-route.sh", import.meta.url)); | ||
| const repo = "devswha/ovis"; | ||
| const mac = ["self-hosted", "self-hosted-ovis-mac"]; | ||
| const now = Date.parse("2026-11-05T12:00:00Z") / 1000; | ||
|
|
||
| const created: string[] = []; | ||
| function tempDir(): string { | ||
| const dir = mkdtempSync(join(tmpdir(), "ci-mac-runner-route-")); | ||
| created.push(dir); | ||
| return dir; | ||
| } | ||
| afterAll(() => { | ||
| for (const dir of created) rmSync(dir, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| // A fake `gh` that answers the Actions API from the JSON files in $FAKE_GH and logs each call; a | ||
| // missing file makes it fail like an API error. | ||
| const bin = tempDir(); | ||
| writeFileSync(join(bin, "gh"), `#!/bin/sh | ||
| echo "$*" >> "$FAKE_GH/calls" | ||
| [ "$1" = api ] && [ "$2" = --paginate ] || exit 1 | ||
| case "$3" in | ||
| */jobs*) id=\${3#*/runs/}; f=jobs-\${id%%/*} ;; | ||
| *status=in_progress*) f=in_progress ;; | ||
| *status=queued*) f=queued ;; | ||
| *) exit 1 ;; | ||
| esac | ||
| cat "$FAKE_GH/$f.json" | ||
| `); | ||
| chmodSync(join(bin, "gh"), 0o755); | ||
|
|
||
| type Job = { status: string; labels: string[]; created_at: string }; | ||
| const minutesAgo = (minutes: number) => new Date((now - minutes * 60) * 1000).toISOString().replace(/\.\d+Z$/, "Z"); | ||
| const job = (status: string, minutes = 1, labels = mac): Job => ({ status, labels, created_at: minutesAgo(minutes) }); | ||
|
|
||
| /** Writes the API state: runs by status, each run's id mapped to its jobs. */ | ||
| function actions(state: { in_progress?: Record<number, Job[]>; queued?: Record<number, Job[]> }): string { | ||
| const dir = tempDir(); | ||
| for (const status of ["in_progress", "queued"] as const) { | ||
| const runs = state[status] ?? {}; | ||
| writeFileSync(join(dir, `${status}.json`), JSON.stringify({ workflow_runs: Object.keys(runs).map((id) => ({ id: Number(id) })) })); | ||
| for (const [id, jobs] of Object.entries(runs)) writeFileSync(join(dir, `jobs-${id}.json`), JSON.stringify({ jobs })); | ||
| } | ||
| return dir; | ||
| } | ||
|
|
||
| function route(env: Record<string, string>) { | ||
| const result = spawnSync("bash", [script], { | ||
| encoding: "utf8", | ||
| timeout: 5_000, | ||
| env: { PATH: `${bin}:${process.env.PATH ?? ""}`, FAKE_GH: tempDir(), REPOSITORY: repo, ROUTE_NOW: String(now), RUNNER_SEEN: String(now - 60), ...env }, | ||
| }); | ||
| expect(result.error).toBeUndefined(); | ||
| return result; | ||
| } | ||
|
|
||
| function routed(env: Record<string, string>): unknown { | ||
| const result = route(env); | ||
| expect(result.status).toBe(0); | ||
| const lines = result.stdout.trimEnd().split("\n"); | ||
| expect(lines.length).toBe(1); | ||
| expect(lines[0]).toStartWith("macos="); | ||
| return JSON.parse(lines[0]!.slice("macos=".length)); | ||
| } | ||
|
|
||
| const apiCalled = (dir: string) => existsSync(join(dir, "calls")) && readFileSync(join(dir, "calls"), "utf8").length > 0; | ||
|
|
||
| describe.skipIf(process.platform === "win32")("CI Mac runner route", () => { | ||
| const pr = { EVENT_NAME: "pull_request", HEAD_REPO: repo }; | ||
| const main = { EVENT_NAME: "push", REF: "refs/heads/main" }; | ||
|
|
||
| it("sends a same-repository pull request and a push to main to an idle Mac runner", () => { | ||
| expect(routed({ ...pr, FAKE_GH: actions({}) })).toEqual(mac); | ||
| expect(routed({ ...main, FAKE_GH: actions({}) })).toEqual(mac); | ||
| }); | ||
|
|
||
| it("lets one job wait behind a running one, and goes hosted from the second", () => { | ||
| expect(routed({ ...pr, FAKE_GH: actions({ in_progress: { 1: [job("in_progress")] } }) })).toEqual(mac); | ||
| expect(routed({ ...pr, FAKE_GH: actions({ in_progress: { 1: [job("in_progress")] }, queued: { 2: [job("queued")] } }) })).toBe("macos-15"); | ||
| expect(routed({ ...pr, MAC_MAX_JOBS: "3", FAKE_GH: actions({ in_progress: { 1: [job("in_progress")] }, queued: { 2: [job("queued")] } }) })).toEqual(mac); | ||
| }); | ||
|
|
||
| it("goes hosted when a job has waited too long for the Mac runner (offline)", () => { | ||
| expect(routed({ ...pr, FAKE_GH: actions({ queued: { 1: [job("queued", 11)] } }) })).toBe("macos-15"); | ||
| expect(routed({ ...pr, MAC_STALE_MINUTES: "15", FAKE_GH: actions({ queued: { 1: [job("queued", 11)] } }) })).toEqual(mac); | ||
| // a long-running job is busy, not offline | ||
| expect(routed({ ...pr, FAKE_GH: actions({ in_progress: { 1: [job("in_progress", 30)] } }) })).toEqual(mac); | ||
| }); | ||
|
|
||
| it("goes hosted unless the heartbeat saw the Mac runner online in the last five minutes", () => { | ||
| for (const seen of ["", " ", "soon", String(now - 301), String(now + 3600)]) { | ||
| const dir = actions({}); | ||
| expect(routed({ ...pr, RUNNER_SEEN: seen, FAKE_GH: dir })).toBe("macos-15"); | ||
| expect(apiCalled(dir)).toBe(false); | ||
| } | ||
| expect(routed({ ...pr, RUNNER_SEEN: String(now - 300), FAKE_GH: actions({}) })).toEqual(mac); | ||
| expect(routed({ ...pr, RUNNER_SEEN: String(now - 600), MAC_SEEN_SECONDS: "900", FAKE_GH: actions({}) })).toEqual(mac); | ||
| }); | ||
|
|
||
| it("ignores finished jobs and jobs for other runners", () => { | ||
| const others = [job("completed", 30), job("queued", 30, ["self-hosted", "self-hosted-ovis"]), job("queued", 30, ["macos-15"])]; | ||
| expect(routed({ ...pr, FAKE_GH: actions({ in_progress: { 1: others }, queued: { 2: others } }) })).toEqual(mac); | ||
| expect(routed({ ...pr, FAKE_GH: actions({ queued: { 1: [job("queued", 30, ["Self-Hosted", "SELF-HOSTED-OVIS-MAC"])] } }) })).toBe("macos-15"); | ||
| }); | ||
|
|
||
| it("stays hosted when the Actions API fails", () => { | ||
| const failing = tempDir(); | ||
| const result = route({ ...pr, FAKE_GH: failing }); | ||
| expect(result.status).toBe(0); | ||
| expect(result.stdout.trim()).toBe('macos="macos-15"'); | ||
| expect(result.stderr).toContain("::warning::"); | ||
| }); | ||
|
|
||
| it("never sends a fork, a tag, a dispatch or another event to the Mac, and asks the API nothing", () => { | ||
| for (const env of [ | ||
| { EVENT_NAME: "pull_request", HEAD_REPO: "someone/ovis" }, | ||
| { EVENT_NAME: "pull_request_target", HEAD_REPO: "" }, | ||
| { EVENT_NAME: "push", REF: "refs/tags/remote-v9" }, | ||
| { EVENT_NAME: "push", REF: "refs/heads/feature" }, | ||
| { EVENT_NAME: "workflow_dispatch", REF: "refs/heads/main" }, | ||
| { EVENT_NAME: "workflow_run", HEAD_REPO: repo }, | ||
| { EVENT_NAME: "" }, | ||
| ]) { | ||
| const dir = actions({}); | ||
| expect(routed({ ...env, FAKE_GH: dir })).toBe("macos-15"); | ||
| expect(apiCalled(dir)).toBe(false); | ||
| } | ||
| }); | ||
|
|
||
| it("keeps everything hosted while the variable says macos-15, and refuses any other value", () => { | ||
| const dir = actions({}); | ||
| expect(routed({ ...pr, CONFIGURED_LABELS: ' "macos-15" ', FAKE_GH: dir })).toBe("macos-15"); | ||
| expect(apiCalled(dir)).toBe(false); | ||
| for (const value of ['["self-hosted"]', "macos-15", '"ubuntu-24.04"']) { | ||
| const result = route({ ...pr, CONFIGURED_LABELS: value, FAKE_GH: actions({}) }); | ||
| expect(result.status).toBe(1); | ||
| expect(result.stderr).toContain("::error::"); | ||
| } | ||
| }); | ||
|
|
||
| it("refuses limits that are not whole numbers", () => { | ||
| for (const env of [{ MAC_MAX_JOBS: "two" }, { MAC_STALE_MINUTES: "-1" }, { MAC_STALE_MINUTES: "99999" }, { MAC_SEEN_SECONDS: "5m" }]) { | ||
| expect(route({ ...pr, ...env, FAKE_GH: actions({}) }).status).toBe(1); | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
rg -n 'ci-mac-runner-route|concurrency:|group:|self-hosted-ovis-mac' .github/workflows scriptsRepository: devswha/ovis
Length of output: 13176
Script executed:
Repository: devswha/ovis
Length of output: 17102
Script executed:
Repository: devswha/ovis
Length of output: 6989
Reserve Mac capacity atomically, or document the limit as best-effort.
The capacity check reads a snapshot at
scripts/ci-mac-runner-route.sh:76-80and emits the label without reserving it. Two routing decisions that overlap can both see one unfinished Mac job and both selectself-hosted-ovis-mac. The third job then queues behind the single-job runner, which exceeds theMAC_MAX_JOBSlimit described in the script header.Why a route-only concurrency group is not enough
Serializing the
changesjob does not cover the gap.macos-sessionruns only afterchangescompletes, so the selected job may not appear in the Actions API when the next decision reads.