CI: Linux runners for the parity job (desktop, ThinkPad), paused while a game runs

runner-env.sh and vanilla-data.sh find Python 3.13, the pinned JDK and sccache on NixOS;
linux-runner.sh installs a runner as a systemd user service with its own screen; runner-pause.py
stops it from taking jobs while a game runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-25 22:28:03 +01:00
parent d58d26c793
commit 8463325648
4 changed files with 392 additions and 6 deletions
+191
View File
@@ -0,0 +1,191 @@
#!/usr/bin/env bash
# A Horizon CI runner (labels self-hosted, Linux, X64, horizon-game and the host's name) on a Linux machine of the
# maintainer's (NixOS: ludodesktop, ludothinkpad), as a systemd user service of the account that holds his
# Minecraft files, like the Mac mini's runners (docs/release-flow.md). Run it on that machine, as that user:
#
# bash tools/ci/linux-runner.sh install # register (gh login), install, start; again to update the scripts
# bash tools/ci/linux-runner.sh status # the services, the runner's state, the pause watcher's last lines
# bash tools/ci/linux-runner.sh uninstall # stop and unregister
#
# Everything lives in ~/.actions-runners/horizon (never in ~/code): the runner, its own rustup and cargo homes,
# the work folder, and copies of this script and runner-pause.py taken at install time (a pull request's checkout
# never runs as the service). The service runs nice, in horizon-ci.slice (low CPU and I/O weight, memory capped),
# on its own virtual screen: vscreen (a headless sway) where it is installed, else Xvfb from nixpkgs with Mesa's
# Vulkan drivers. runner-pause.py pauses it while a game runs (horizon-runner-pause.service).
# HORIZON_SHARED_SOURCE: the imported vanilla data (default ~/horizon-local/shared-local, else
# ~/code/horizon/.local); RUNNER_JOBS: cargo jobs and harnesses at once (default 2/3 of the threads).
set -euo pipefail
repo=ludovic111/horizon
dir=$HOME/.actions-runners/horizon
units=${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user
version=2.338.0
sha=af4b794c1bc41d73d40535e3fe092a39f9679cd8d965954c2aca25a05ca41d32
here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# Nix packages the jobs need, kept alive by GC roots in $dir/nix.
nix_out() { nix-build '<nixpkgs>' -A "$1" -o "$dir/nix/$2" > /dev/null && readlink -f "$dir/nix/$2"; }
# The runner is a .NET program: on NixOS its native libraries (libstdc++, ICU, OpenSSL) come from nix-ld.
export LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
# NixOS has no /bin/bash: the runner's scripts (again after each of its self-updates) get a portable one.
fix_shebangs() { sed -i '1s|^#!/bin/bash|#!/usr/bin/env bash|' "$dir"/*.sh "$dir"/bin/*.sh; }
display_env() {
# The jobs' screen. Never the maintainer's: the user manager hands every service his DISPLAY and WAYLAND_DISPLAY.
if command -v vscreen > /dev/null; then
VSCREEN=ci-horizon vscreen env
else
echo "unset WAYLAND_DISPLAY; export DISPLAY=:$(cat "$dir/display")"
fi
}
install() {
local name=${RUNNER_NAME:-$(hostname)-horizon} jobs=${RUNNER_JOBS:-$(( $(nproc) * 2 / 3 ))}
local source=${HORIZON_SHARED_SOURCE:-}
if [ -z "$source" ]; then
for candidate in "$HOME/horizon-local/shared-local" "$HOME/code/horizon/.local"; do
[ -d "$candidate/minecraft" ] && { source=$candidate; break; }
done
fi
[ -n "$source" ] && [ -d "$source/minecraft" ] || { echo "no imported Minecraft (HORIZON_SHARED_SOURCE)"; exit 1; }
mkdir -p "$dir/nix" "$units"
cp "$here/linux-runner.sh" "$here/runner-pause.py" "$dir/"
if [ ! -f "$dir/.runner" ]; then
local cache=$HOME/.cache/gha-runner/actions-runner-linux-x64-$version.tar.gz
if ! echo "$sha $cache" | sha256sum -c --quiet - > /dev/null 2>&1; then
mkdir -p "$(dirname "$cache")"
curl -fsSL -o "$cache" "https://github.com/actions/runner/releases/download/v$version/actions-runner-linux-x64-$version.tar.gz"
echo "$sha $cache" | sha256sum -c --quiet -
fi
tar xzf "$cache" -C "$dir"
fix_shebangs
gh api -X POST "repos/$repo/actions/runners/registration-token" --jq .token |
(cd "$dir" && bash ./config.sh --unattended --replace --url "https://github.com/$repo" --token "$(cat)" \
--name "$name" --labels "${RUNNER_LABELS:-horizon-game,$(hostname)}" --work _work > /dev/null)
fi
# Libraries for building (pkg-config) and running (dlopen) the game, the JDK pinned by research-lock.json, sccache.
local alsa udev java sccache
alsa=$(nix_out alsa-lib.dev alsa-dev)
udev=$(nix_out systemd.dev systemd-dev)
java=$(nix_out "jdk$(sed -n 's/.*"java_major": *\([0-9]*\).*/\1/p' "$here/../../research-lock.json" | head -1)_headless" jdk)/lib/openjdk
sccache=$(nix_out sccache sccache)
local libs=/run/opengl-driver/lib:/run/current-system/sw/share/nix-ld/lib
if ! command -v vscreen > /dev/null; then
local mesa x
mesa=$(nix_out mesa mesa)
x=$(nix_out xvfb-run xvfb-run)
for lib in libx11 libxcursor libxrandr libxi libxext libxinerama libxrender libxxf86vm libxcb libxkbcommon \
vulkan-loader libGL; do
libs=$libs:$(nix_out "$lib" "$lib")/lib
done
libs=$mesa/lib:$libs
echo "VK_DRIVER_FILES=$mesa/share/vulkan/icd.d/intel_icd.x86_64.json:$mesa/share/vulkan/icd.d/lvp_icd.x86_64.json" \
> "$dir/.env.display"
echo "$x/bin" > "$dir/.path.display"
fi
cat > "$dir/.env" <<EOF
LANG=C.UTF-8
RUSTUP_HOME=$dir/rustup
CARGO_HOME=$dir/cargo
CARGO_BUILD_JOBS=$jobs
PARITY_MACHINE_JOBS=$jobs
JAVA_HOME=$java
HORIZON_SHARED_SOURCE=$source
HORIZON_NO_AUDIO=1
HORIZON_NO_HEARTBEAT=1
HORIZON_TELEMETRY_URL=off
HORIZON_LAUNCHER_NO_SELF_UPDATE=1
PKG_CONFIG_PATH=$alsa/lib/pkgconfig:$udev/lib/pkgconfig
C_INCLUDE_PATH=$udev/include
LD_LIBRARY_PATH=$libs
NIX_LD=/run/current-system/sw/share/nix-ld/lib/ld.so
NIX_LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib
EOF
if [ -f "$dir/.env.display" ]; then cat "$dir/.env.display" >> "$dir/.env"; else echo "VSCREEN=ci-horizon" >> "$dir/.env"; fi
echo "$dir/cargo/bin:$(cat "$dir/.path.display" 2>/dev/null || true)${dir}/nix/sccache/bin:$java/bin:$HOME/.local/bin:/run/wrappers/bin:/etc/profiles/per-user/$USER/bin:/run/current-system/sw/bin" \
| sed 's/::/:/g' > "$dir/.path"
cat > "$units/horizon-ci.slice" <<EOF
[Unit]
Description=Horizon CI: the runner's jobs and parity workers sent from other machines
[Slice]
CPUWeight=20
IOWeight=20
MemoryHigh=$(( $(awk '/MemTotal/ {print int($2 / 1048576)}' /proc/meminfo) / 2 ))G
MemoryMax=$(( $(awk '/MemTotal/ {print int($2 / 1048576)}' /proc/meminfo) * 2 / 3 ))G
EOF
cat > "$units/horizon-runner.service" <<EOF
[Unit]
Description=GitHub Actions runner for $repo (parity), paused while a game runs
After=network-online.target
[Service]
Slice=horizon-ci.slice
WorkingDirectory=$dir
ExecStart=/usr/bin/env bash $dir/linux-runner.sh run
Nice=10
# runsvc.sh hands SIGTERM to the runner, which stops after cancelling its job; then the rest (Xvfb) goes.
KillMode=mixed
KillSignal=SIGTERM
TimeoutStopSec=5min
Restart=on-failure
RestartSec=30
[Install]
WantedBy=default.target
EOF
cat > "$units/horizon-runner-pause.service" <<EOF
[Unit]
Description=Pauses the Horizon CI runner while a game runs
[Service]
ExecStart=$(command -v python3) $dir/runner-pause.py
Restart=always
RestartSec=10
[Install]
WantedBy=default.target
EOF
# User services run without a login session (after a reboot): lingering, once.
if [ "$(loginctl show-user "$USER" -p Linger --value 2>/dev/null)" != yes ]; then
sudo -n loginctl enable-linger "$USER" || echo "Run once: sudo loginctl enable-linger $USER"
fi
systemctl --user daemon-reload
systemctl --user enable horizon-runner.service horizon-runner-pause.service > /dev/null
systemctl --user restart horizon-runner-pause.service
[ -e "$dir/paused" ] || systemctl --user start horizon-runner.service
status
}
run() {
cd "$dir"
fix_shebangs
if command -v vscreen > /dev/null; then
eval "$(display_env)"
else
# Xvfb on the first free display from :90, for this service's lifetime.
local n=90
while [ -e "/tmp/.X$n-lock" ]; do n=$((n + 1)); done
echo "$n" > "$dir/display"
Xvfb ":$n" -screen 0 1280x720x24 -nolisten tcp &
eval "$(display_env)"
fi
exec bash ./bin/runsvc.sh
}
status() {
systemctl --user --no-pager list-units 'horizon-runner*' 'vscreen-ci-horizon*'
[ -e "$dir/paused" ] && echo "paused: $(cat "$dir/paused")"
tail -5 "$dir/pause.log" 2>/dev/null || true
}
uninstall() {
systemctl --user disable --now horizon-runner-pause.service horizon-runner.service 2>/dev/null || true
gh api -X POST "repos/$repo/actions/runners/remove-token" --jq .token |
(cd "$dir" && bash ./config.sh remove --token "$(cat)")
rm -f "$units/horizon-runner.service" "$units/horizon-runner-pause.service" "$units/horizon-ci.slice"
systemctl --user daemon-reload
}
case ${1:-} in
install|run|status|uninstall) "$1" ;;
*) sed -n '2,10p' "$0"; exit 2 ;;
esac
+29 -3
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# The tools the vanilla harnesses need, on the self-hosted Mac mini runner (label horizon-game): its service
# starts with a bare PATH. Python 3.13 and the JDK pinned by research-lock.json come from the machine, never
# from a download. Writes them to $GITHUB_PATH and $GITHUB_ENV for the next steps.
# The tools the vanilla harnesses need, on a self-hosted runner (label horizon-game): the Mac mini's, whose service
# starts with a bare PATH, and the Linux ones (tools/ci/linux-runner.sh, NixOS). Python 3.13 and the JDK pinned by
# research-lock.json come from the machine, never from a download. Writes them to $GITHUB_PATH and $GITHUB_ENV for
# the next steps.
set -euo pipefail
java_major=$(sed -n 's/.*"java_major": *\([0-9]*\).*/\1/p' research-lock.json | head -1)
bin="$RUNNER_TEMP/horizon-bin"
@@ -17,5 +18,30 @@ if [ "$(uname)" = Darwin ]; then
if [ -x /opt/homebrew/bin/sccache ]; then
{ echo "RUSTC_WRAPPER=/opt/homebrew/bin/sccache"; echo "CARGO_INCREMENTAL=0"; } >> "$GITHUB_ENV"
fi
else
python=$(command -v python3.13 || true)
[ -n "$python" ] || { echo "::error::no python3.13 on this runner"; exit 1; }
ln -sfn "$python" "$bin/python3"
ln -sfn "$python" "$bin/python"
# The JDK: the runner's JAVA_HOME (linux-runner.sh pins one), else the java on PATH, else nixpkgs' jdk<major>.
major_of() { "$1/bin/java" -version 2>&1 | sed -n 's/.*version "\([0-9]*\).*/\1/p' | head -1; }
java_home=${JAVA_HOME:-}
if [ -z "$java_home" ] || [ "$(major_of "$java_home")" != "$java_major" ]; then
java_home=""
if command -v java > /dev/null; then
candidate=$(dirname "$(dirname "$(readlink -f "$(command -v java)")")")
[ "$(major_of "$candidate")" = "$java_major" ] && java_home=$candidate
fi
fi
if [ -z "$java_home" ] && command -v nix-build > /dev/null; then
out=$(nix-build '<nixpkgs>' --no-out-link -A "jdk${java_major}_headless" 2>/dev/null || true)
[ -n "$out" ] && java_home=$out/lib/openjdk
fi
[ -n "$java_home" ] || { echo "::error::no JDK $java_major on this runner"; exit 1; }
{ echo "$bin"; echo "$java_home/bin"; } >> "$GITHUB_PATH"
echo "JAVA_HOME=$java_home" >> "$GITHUB_ENV"
if sccache=$(command -v sccache); then
{ echo "RUSTC_WRAPPER=$sccache"; echo "CARGO_INCREMENTAL=0"; } >> "$GITHUB_ENV"
fi
fi
echo "HORIZON_NO_AUDIO=1" >> "$GITHUB_ENV"
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""Pauses the Horizon CI runner (tools/ci/linux-runner.sh) while the maintainer plays a game on this machine.
A game is running when any of these holds:
- fleet-load says so (~/fleet/load: Steam, gamescope, Wine or Proton processes);
- a process of his matches GAME below (the same, plus Minecraft and a Horizon game he started himself);
- a process outside horizon-ci.slice keeps the GPU busy (nvidia-smi: SM use >= GPU_BUSY % twice in a row);
- ~/.actions-runners/horizon/pause exists (pause by hand: `touch` it; `rm` it to let the watcher decide).
Paused, the runner takes no new job: while it is idle its service is stopped, so GitHub sends the jobs to the
Mac mini. A job already running is throttled, not stopped: horizon-ci.slice (the job, and the parity workers other machines
send here) drops to CPU weight 1, I/O weight 1
and a quota of THROTTLE_CPUS threads, and the service stops once the job ends. Freezing it (SIGSTOP or the cgroup
freezer) would stop the runner's heartbeat, so GitHub would drop the job as lost, and the harnesses' wall-clock
timeouts would fail runs that were only waiting. The runner comes back RESUME_AFTER seconds after the last sign
of a game. Every change is written to ~/.actions-runners/horizon/pause.log.
"""
import json
import os
import re
import subprocess
import time
from pathlib import Path
DIR = Path.home() / ".actions-runners" / "horizon"
SERVICE, SLICE = "horizon-runner.service", "horizon-ci.slice"
MANUAL, STATE, LOG = DIR / "pause", DIR / "paused", DIR / "pause.log"
GAME = re.compile(r"(SteamLaunch|gamescope|wine64-preloader|wineserver|wine-preloader|\.exe(\s|$)|proton\b"
r"|net\.minecraft\.client\.main\.Main|minecraft-launcher|prismlauncher)", re.I)
GPU_BUSY = int(os.environ.get("GPU_BUSY", 30))
INTERVAL = int(os.environ.get("INTERVAL", 15))
RESUME_AFTER = int(os.environ.get("RESUME_AFTER", 300))
THROTTLE_CPUS = int(os.environ.get("THROTTLE_CPUS", 2))
def log(text):
with LOG.open("a") as handle:
handle.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S')} {text}\n")
def systemctl(*arguments):
return subprocess.run(["systemctl", "--user", *arguments], capture_output=True, text=True)
def ci_process(pid):
"""A process of the runner's slice (its jobs, the parity workers other machines start here)."""
try:
return SLICE in Path(f"/proc/{pid}/cgroup").read_text()
except OSError:
return True # gone
def fleet_load_gaming():
status = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "fleet-load" / "status.json"
try:
if time.time() - status.stat().st_mtime > 120:
return None
return "fleet-load: playing a game" if json.loads(status.read_text())["human"]["gaming"] else None
except (OSError, ValueError, KeyError, TypeError):
return None
def game_process():
uid = os.getuid()
for entry in Path("/proc").iterdir():
if not entry.name.isdigit():
continue
try:
if entry.stat().st_uid != uid:
continue
command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace")
except OSError:
continue
# A Horizon game counts when he started it (its parent is his launcher), not when a harness or agent did.
if GAME.search(command) or (" --offscreen" not in command and "/horizon-launcher/" in command
and "horizon-client" in command.split(" ")[0]):
if not ci_process(int(entry.name)):
return f"process {entry.name}: {command[:120]}"
return None
def gpu_users():
"""Processes outside the CI slice using the GPU's shader cores, as {pid: SM %}."""
try:
output = subprocess.run(["nvidia-smi", "pmon", "-c", "1", "-s", "u"], capture_output=True, text=True,
timeout=20).stdout
except (OSError, subprocess.TimeoutExpired):
return {}
users = {}
for line in output.splitlines():
fields = line.split()
if line.startswith("#") or len(fields) < 4 or not fields[1].isdigit() or not fields[3].isdigit():
continue
if not ci_process(int(fields[1])):
users[int(fields[1])] = int(fields[3])
return users
def runner_busy():
"""The runner is in a job: a Runner.Worker runs in its service."""
group = systemctl("show", "-p", "ControlGroup", "--value", SERVICE).stdout.strip()
try:
pids = Path(f"/sys/fs/cgroup{group}/cgroup.procs").read_text().split() if group else []
except OSError:
return False
for pid in pids:
try:
if Path(f"/proc/{pid}/comm").read_text().strip() == "Runner.Worker":
return True
except OSError:
pass
return False
def throttle(on):
if on:
systemctl("set-property", "--runtime", SLICE, "CPUWeight=1", "IOWeight=1", f"CPUQuota={THROTTLE_CPUS * 100}%")
else:
systemctl("set-property", "--runtime", SLICE, "CPUWeight=20", "IOWeight=20", "CPUQuota=")
def main():
hot = {} # GPU users seen busy at the last sample
last_game = 0.0
paused = STATE.exists()
while True:
reason = None
if MANUAL.exists():
reason = "paused by hand (" + str(MANUAL) + ")"
reason = reason or fleet_load_gaming() or game_process()
if not reason:
busy = {pid for pid, sm in gpu_users().items() if sm >= GPU_BUSY}
twice = busy & set(hot)
hot = dict.fromkeys(busy)
if twice:
pid = min(twice)
try:
name = Path(f"/proc/{pid}/comm").read_text().strip()
except OSError:
name = "?"
reason = f"GPU busy: process {pid} ({name})"
now = time.monotonic()
if reason:
last_game = now
if reason and not paused:
paused = True
STATE.write_text(reason + "\n")
throttle(True) # also what other machines' parity workers run here meanwhile
if runner_busy():
log(f"pause: {reason}; a job is running: throttled to {THROTTLE_CPUS} threads, stops after it")
else:
systemctl("stop", SERVICE)
log(f"pause: {reason}; runner stopped")
elif paused and reason is None and now - last_game >= RESUME_AFTER:
paused = False
STATE.unlink(missing_ok=True)
throttle(False)
systemctl("start", SERVICE)
log(f"resume: no game for {RESUME_AFTER} s; runner started")
elif paused and systemctl("is-active", "--quiet", SERVICE).returncode == 0 and not runner_busy():
systemctl("stop", SERVICE)
log("the job ended: runner stopped until the game ends")
time.sleep(INTERVAL)
if __name__ == "__main__":
main()
+5 -3
View File
@@ -1,8 +1,9 @@
#!/usr/bin/env bash
# The vanilla data for this checkout on the self-hosted runner. Horizon never downloads the game: the runner
# holds the maintainer's own copy, imported and decompiled once (HORIZON_SHARED_SOURCE, default
# ~/code/horizon-parity/shared-local). It is cloned once into the runner's work folder ($RUNNER_WORKSPACE/
# shared-local; APFS clones, so no second copy of the bytes), and .local/ links to it as in a parity worktree.
# ~/code/horizon-parity/shared-local; tools/ci/linux-runner.sh sets it on Linux). It is cloned once into the runner's
# work folder ($RUNNER_WORKSPACE/shared-local; APFS clones, or reflinks where the file system has them, so no second
# copy of the bytes), and .local/ links to it as in a parity worktree.
# .local/horizon-client and the exporter outputs beside it, what horizon-prepare makes, are prepared by this
# checkout's own preparer once per preparer version (its sources, the exporters and research-lock.json), so a
# change to the preparer is checked with what it prepares; the four newest preparations are kept.
@@ -31,7 +32,8 @@ for entry in "$shared"/*; do
done
# HORIZON_PREPARE_KEY: the same key, computed where the Git history is (tools/pr_ready.py on another machine).
key=${HORIZON_PREPARE_KEY:-$(git ls-files -s crates/horizon-prepare mods/horizon/src/test/java research-lock.json | shasum -a 256 | cut -c1-16)}
sha256() { if command -v shasum > /dev/null; then shasum -a 256; else sha256sum; fi; }
key=${HORIZON_PREPARE_KEY:-$(git ls-files -s crates/horizon-prepare mods/horizon/src/test/java research-lock.json | sha256 | cut -c1-16)}
prepared="$shared/prepared/$key"
# Two runners share the vanilla data (~/.actions-runners/horizon-2/_work/horizon/shared-local links to the first
# one's): one preparation at a time. A lock older than 30 minutes belongs to a job that died.