Merge origin/main into t3/fix-critical-hit-particles

Keep both critical-hit and replant regressions.

Co-Authored-By: OpenCode (agentrouter/gpt-6.1-sol) <noreply@openai.com>
This commit is contained in:
rdbtCVS
2026-10-26 01:45:16 +00:00
35 changed files with 1669 additions and 233 deletions
+213
View File
@@ -0,0 +1,213 @@
#!/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). horizon-runner-pause.service (runner_pause.py) starts the runner only while nobody
# uses the machine (screen locked or untouched for 15 min, no game), and stops it otherwise. The runner 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.
# 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 a third of the threads, at most 8:
# ludodesktop froze under ~7 cold cargo builds on 2026-10-14, and it is the maintainer's own machine).
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-build prints the store path; the root's name
# gets the output's suffix (alsa-dev-dev for alsa-lib.dev), so it is not read back from the link.
nix_out() { nix-build '<nixpkgs>' -A "$1" -o "$dir/nix/$2" | tail -1; }
# 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; }
# Other machines' parity runs can send harnesses here (tools/parity_hosts.json "desktop": parity.py --worker over
# ssh, in horizon-ci.slice). Their vanilla data is the runner checkout's: parity-host/shared-local links to its
# .local links, so it follows the preparation of the runner's last job.
parity_host_links() {
local checkout=$dir/_work/horizon/horizon/.local shared=$dir/parity-host/shared-local entry
[ -d "$checkout" ] || return 0
mkdir -p "$shared"
for entry in "$checkout"/*; do
if [ -L "$entry" ]; then ln -sfn "$entry" "$shared/$(basename "$entry")"; fi
done
}
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} threads jobs
threads=$(nproc)
jobs=${RUNNER_JOBS:-$(( threads / 3 > 8 ? 8 : threads / 3 > 1 ? threads / 3 : 1 ))}
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
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
nix_out sccache sccache > /dev/null # on the PATH below: runner-env.sh hands it to cargo
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
PARITY_LOCAL_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
CPUQuota=$(( threads * 50 ))%
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), started and stopped by horizon-runner-pause
After=network-online.target
[Service]
Slice=horizon-ci.slice
WorkingDirectory=$dir
ExecStart=/usr/bin/env bash $dir/linux-runner.sh run
Nice=19
# 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
EOF
cat > "$units/horizon-runner-pause.service" <<EOF
[Unit]
Description=Runs the Horizon CI runner only while nobody uses the machine or plays on it
[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
# Only the watcher starts the runner (never the boot itself): it decides whether anyone is at the screen.
systemctl --user enable horizon-runner-pause.service > /dev/null
# The runner reads .env when it starts: stop it, unless it is in a job (that would cancel the job); the watcher
# starts it again when it may run.
if pgrep -f "$dir/bin/Runner.Worker" > /dev/null; then echo "In a job: stop horizon-runner.service after it"
else systemctl --user stop horizon-runner.service; rm -f "$dir/paused"; fi
systemctl --user restart horizon-runner-pause.service
status
}
run() {
cd "$dir"
fix_shebangs
parity_host_links
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"
+266
View File
@@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""Pauses the Horizon CI runner (tools/ci/linux-runner.sh) while the maintainer uses this machine or plays on it.
The runner works while nobody uses the machine: its screen locked, or untouched for IDLE_AFTER seconds (900).
It pauses when any of these holds:
- keyboard, mouse or gamepad input in the last INPUT_PAUSE seconds (60), or an unlocked session on seat0 with
input in the last IDLE_AFTER seconds;
- the CPU package at TEMP_LIMIT °C (90) or more (the median of 5 readings);
- fleet-load says a game runs (~/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 %, default 50, in two
samples in a row; the browser, Discord and the compositor stay under 20 %);
- ~/.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, and the parity workers other machines started here stop (their harnesses go back to those machines). A
job already running is throttled, not stopped: horizon-ci.slice 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 of these signs.
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", 50))
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))
# Working, the slice gets half the threads: on all of them ludodesktop's CPU sits at 92 °C through a cargo build.
NORMAL_CPUS = int(os.environ.get("NORMAL_CPUS", max(1, (os.cpu_count() or 2) // 2)))
INPUT_PAUSE = int(os.environ.get("INPUT_PAUSE", 60))
IDLE_AFTER = int(os.environ.get("IDLE_AFTER", 900))
TEMP_LIMIT = int(os.environ.get("TEMP_LIMIT", 90))
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
class Input:
"""Keyboard, mouse and gamepad activity, from /dev/input (the input group): only whether bytes came, never what."""
def __init__(self):
self.devices = {} # path -> file descriptor
self.last = 0.0 # the boot (the monotonic clock's zero on Linux) counts as input
def poll(self):
try:
text = Path("/proc/bus/input/devices").read_text()
except OSError:
text = ""
wanted = {f"/dev/input/{handler}" for block in text.split("\n\n") for line in block.splitlines()
if line.startswith("H: Handlers=") and re.search(r"\b(kbd|mouse\d*|js\d*)\b", line)
for handler in line.split("=", 1)[1].split() if handler.startswith("event")}
for path in set(self.devices) - wanted:
os.close(self.devices.pop(path))
for path in wanted - set(self.devices):
try:
self.devices[path] = os.open(path, os.O_RDONLY | os.O_NONBLOCK)
except OSError:
pass
for path, descriptor in list(self.devices.items()):
try:
while os.read(descriptor, 4096):
self.last = time.monotonic()
except BlockingIOError:
pass
except OSError: # unplugged
os.close(self.devices.pop(path))
return time.monotonic() - self.last
def seat_session():
"""The graphical session on seat0 and whether its screen is locked, or None."""
sessions = subprocess.run(["loginctl", "list-sessions", "--no-legend"], capture_output=True, text=True).stdout
for line in sessions.splitlines():
fields = line.split()
if "seat0" in fields:
locked = subprocess.run(["loginctl", "show-session", fields[0], "-p", "LockedHint", "--value"],
capture_output=True, text=True).stdout.strip() == "yes"
return fields[0], locked
return None
def at_the_screen(input_idle):
"""Someone is at the machine: input in the last INPUT_PAUSE seconds, or an unlocked session with input in the last
IDLE_AFTER seconds. A locked screen, or one nobody touched for IDLE_AFTER, leaves the machine to CI."""
if input_idle < INPUT_PAUSE:
return f"input {input_idle:.0f} s ago"
session = seat_session()
if session and not session[1] and input_idle < IDLE_AFTER:
return f"session {session[0]} unlocked, input {input_idle:.0f} s ago"
return None
def too_hot():
"""The CPU package at TEMP_LIMIT °C or more (coretemp or k10temp), as the median of 5 readings over 2 s: under
load it jumps for a second at a time (to 96 °C on ludodesktop at a median of 68 °C), which is no reason to stop."""
for monitor in Path("/sys/class/hwmon").glob("hwmon*"):
try:
if (monitor / "name").read_text().strip() not in ("coretemp", "k10temp"):
continue
readings = []
for _ in range(5):
readings.append(int((monitor / "temp1_input").read_text()) / 1000)
time.sleep(0.5)
except (OSError, ValueError):
continue
celsius = sorted(readings)[2]
return f"CPU at {celsius:.0f} °C" if celsius >= TEMP_LIMIT else None
return None
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:
# Two samples: the first one nvidia-smi prints has no utilisation yet.
output = subprocess.run(["nvidia-smi", "pmon", "-c", "2", "-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])] = max(users.get(int(fields[1]), 0), 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", f"CPUQuota={NORMAL_CPUS * 100}%")
def pause_reason(hot, keys):
"""Why the runner may not work now, or None. hot: the GPU users seen busy at the last sample (updated);
keys: the Input watcher."""
if MANUAL.exists():
return f"paused by hand ({MANUAL})"
reason = at_the_screen(keys.poll()) or too_hot() or fleet_load_gaming() or game_process()
if reason:
return reason
busy = {pid for pid, sm in gpu_users().items() if sm >= GPU_BUSY}
twice = sorted(busy & set(hot))
hot.clear()
hot.update(dict.fromkeys(busy))
if twice:
try:
name = Path(f"/proc/{twice[0]}/comm").read_text().strip()
except OSError:
name = "?"
return f"GPU busy: process {twice[0]} ({name})"
return None
def main():
hot, keys = {}, Input()
# The boot counts as a sign: the runner starts RESUME_AFTER seconds after it at the earliest, which leaves time
# to log in after switching the machine on. Restarting this watcher later changes nothing for a running job.
last_sign = 0.0
paused = None
while True:
reason = pause_reason(hot, keys)
now = time.monotonic()
if reason:
last_sign = now
active = systemctl("is-active", "--quiet", SERVICE).returncode == 0
if reason or now - last_sign < RESUME_AFTER:
if paused is not True:
paused = True
STATE.write_text((reason or "starting") + "\n")
throttle(True)
# Parity workers other machines started here (tools/parity_hosts.json): they stop, and those
# machines run the harnesses themselves.
systemctl("stop", "horizon-parity-worker-*.scope")
log(f"pause: {reason or 'waiting ' + str(RESUME_AFTER) + ' s after starting'}"
+ (f"; a job is running: throttled to {THROTTLE_CPUS} threads, stops after it" if active else ""))
if active and not runner_busy():
systemctl("stop", SERVICE)
log("runner stopped")
else:
if paused is not False:
paused = False
STATE.unlink(missing_ok=True)
throttle(False)
log(f"resume: nobody at the screen and no game for {RESUME_AFTER} s")
if not active:
systemctl("start", SERVICE)
log("runner started")
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.
+135 -7
View File
@@ -52,9 +52,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
- grindstone: a grindstone opens on the guest's screen; the enchanted sword the guest shift-clicks in
shows the server's result, and the guest takes it with only its curse left and the
experience orbs the server awards (#868);
- anvil: an anvil opens on the guest's screen; the guest repairs a sword with iron ingots and
renames it (ServerboundRenameItemPacket), takes it for the server's level cost, and the
server has the repaired, renamed sword (#868);
- anvil: each player repairs and renames a sword (ServerboundRenameItemPacket), takes it for
the server's level cost, and the server has the repaired, renamed sword (#868);
both players hear exactly one anvil sound for each result (#1907);
- enchanting: an enchanting table opens on the guest's screen with the server's offers for the
sword the guest puts in; the guest clicks the first offer and the server enchants the
sword for a level and a lapis, and counts it in the guest's enchant_item stat (#868);
@@ -250,6 +250,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
- falling: an item and a falling block the host summons high up fall smoothly on the guest, a
little further every tick between the server's updates (every 20 ticks), as their own
client tick moves them (they used to hang, then jump down once a second, #1568).
- instant_digging: an instant survival break leaves no repeated stone hit sounds or stale server dig (#1908).
- replant: flowers and crops replanted after a short harvest click stay planted for both players;
the server forgets the completed instant break (#1880).
Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
both sides go to --out (host-*.png, guest-*.png).
@@ -1620,6 +1623,12 @@ def check_grindstone(host, guest, out):
def check_anvil(host, guest, out):
# AnvilMenu.onTake emits one level event to everyone, including the user.
# Exercise both the in-frame host and a remote user (both remote with --server-thread).
return {actor.name: check_anvil_user(actor, (host, guest), out) for actor in (guest, host)}
def check_anvil_user(guest, listeners, out):
guest('command', command='gamemode survival')
guest('command', command='clear @s')
guest('command', command='xp set @s 5 levels')
@@ -1638,8 +1647,12 @@ def check_anvil(host, guest, out):
menu = guest.raw('menu')
offered = (menu['info']['anvil_cost'], station_slots(guest).get(650))
guest.shot(out, 'anvil-rename')
sounds = ('minecraft:block.anvil.use', 'minecraft:block.anvil.destroy')
before = {g.name: sum(heard(g, s) for s in sounds) for g in listeners}
guest.raw('click-slot', 650, 'shift')
guest.wait(10)
guest.wait(20)
sound_counts = {g.name: sum(heard(g, s) for s in sounds) - before[g.name] for g in listeners}
assert sound_counts == {g.name: 1 for g in listeners}, f'anvil sounds: {sound_counts}'
left = station_slots(guest)
close_station(guest, at)
sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}].components',
@@ -1653,7 +1666,7 @@ def check_anvil(host, guest, out):
want = {'offered': (4, ('minecraft:iron_sword', 1)), 'left': {}, 'name': True, 'damage': True,
'levels': 1, 'ingots': 0}
assert seen == want, f'the anvil on the guest: {seen} ({sword!r})'
return seen
return {**seen, 'heard': sound_counts}
def check_smithing(host, guest, out):
@@ -3762,17 +3775,21 @@ def check_frames(host, guest, out):
# Within a survival player's 3 blocks of reach: a frame on a wall, an armor stand beside it.
player('command', command=f'fill {x - 2} {y} {z + 1} {x + 2} {y + 2} {z + 2} minecraft:air')
player('command', command=f'fill {x - 2} {y} {z + 3} {x + 2} {y + 2} {z + 3} minecraft:stone')
player('command', command=f'summon minecraft:item_frame {x + 0.5} {y + 1.5} {z + 2.97} '
frame_kind = 'item_frame' if label == 'host' else 'glow_item_frame'
player('command', command=f'summon minecraft:{frame_kind} {x + 0.5} {y + 1.5} {z + 2.97} '
f'{{block_pos:[I;{x},{y + 1},{z + 2}],Facing:2b}}')
player('command', command=f'summon minecraft:armor_stand {x - 1.5} {y} {z + 1.5}')
player('command', command='clear @s')
player('command', command='item replace entity @s weapon.mainhand with minecraft:diamond')
frame_name = f'{label} framed diamond'
player('command', command='item replace entity @s weapon.mainhand with '
f"minecraft:diamond[minecraft:custom_name='{frame_name}']")
player.wait(30)
try:
frame = [o for o in player('status')['objects'] if o['kind'].endswith('item_frame')
and o['position'] == [x, y + 1, z + 2]]
assert frame, f'the {label} sees no item frame at {[x, y + 1, z + 2]}'
player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 1.5:.2f}', f'{z + 2.95:.2f}')
assert frame_name not in (player('status').get('name_tags') or []), 'empty frame name visible'
player.raw('mouse', 'right', 'click')
player.wait(10)
player.raw('mouse', 'right', 'click')
@@ -3780,6 +3797,15 @@ def check_frames(host, guest, out):
frame = [o for o in player('status')['objects'] if o['id'] == frame[0]['id']][0]
assert frame['item'] == 'minecraft:diamond', f'the {label}\'s frame holds {frame["item"]}'
assert frame['rotation'] == 1, f'the {label}\'s frame turned to {frame["rotation"]}'
assert frame_name in (player('status').get('name_tags') or []), \
f"the {label}'s targeted frame has no item name"
player.shot(out, f'{label}-framed-item-name')
player.raw('key', 'f1', 'tap')
player.wait(2)
assert frame_name not in (player('status').get('name_tags') or []), 'F1 left the frame name visible'
player.raw('key', 'f1', 'tap')
player.raw('look-at', f'{x + 2:.2f}', f'{y + 1.5:.2f}', f'{z + 2.95:.2f}')
assert frame_name not in (player('status').get('name_tags') or []), 'untargeted frame name visible'
theirs = [o for o in other('status')['objects'] if o['kind'].endswith('item_frame')
and o['position'] == [x, y + 1, z + 2]]
assert theirs and theirs[0]['item'] == 'minecraft:diamond' and theirs[0]['rotation'] == 1, \
@@ -5396,6 +5422,42 @@ CHECKS += ['digging']
CHECK_FNS.update(digging=check_digging)
def check_instant_digging(host, guest, out):
"""#1908: an instant survival START has no STOP. ServerPlayerGameMode.tick
forgets a dig once its block is air; it must neither hit air nor break a replacement.
Exercise the in-frame host and network guest (both are clients with --server-thread).
"""
result = {}
for label, player in (('host', host), ('guest', guest)):
x, y, z = (int(v // 1) for v in pos_of(player))
cell = (x, y + 1, z + 2)
player('command', command='gamemode survival')
player('command', command='clear @s')
host('command', command=f'fill {x - 1} {y} {z + 1} {x + 1} {y + 3} {z + 4} minecraft:air')
host('command', command=f'setblock {x} {y} {z + 2} minecraft:sand')
host('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:dead_bush')
player.wait(10)
before = heard(player, 'minecraft:block.stone.hit')
player.raw('look-at', x + 0.5, y + 1.4, z + 2.5)
player.raw('mouse', 'left', 'click')
player.wait(20)
broken = host.raw('block', *cell).get('block')
hits = heard(player, 'minecraft:block.stone.hit') - before
host('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:dead_bush')
player.wait(20)
replacement = host.raw('block', *cell).get('block')
result[label] = {'broken': broken, 'stone_hits': hits, 'replacement': replacement}
assert broken == 'minecraft:air', f'{label}: the bush did not break: {result}'
assert hits == 0, f'{label}: hitting air after an instant break: {result}'
assert replacement == 'minecraft:dead_bush', f'{label}: the server kept digging: {result}'
host('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:air')
return result
CHECKS += ['instant_digging']
CHECK_FNS.update(instant_digging=check_instant_digging)
def check_vehicles(host, guest, out):
"""The host and the guest each (#1551):
- in creative, break a block and have it put back: the server's dig ends with the break
@@ -6486,5 +6548,71 @@ CHECKS += ['critical-hits']
CHECK_FNS['critical-hits'] = check_critical_hits
def check_replant(host, guest, out):
"""Instant breaks leave no server dig that can destroy a replacement (#1880).
ServerPlayerGameMode.handleBlockBreakAction's insta-mine branch finishes on
START; MultiPlayerGameMode sends no STOP or ABORT when attack is released.
Exercise actual flower placement and seed planting after a short click.
"""
spots = apart(host, guest)
seen = {}
host('command', command='gamerule random_tick_speed 0')
try:
for label, player in (('host', host), ('guest', guest)):
x, y, z = spots[label]
cell = (x, y, z + 2)
def observe(block):
# The integrated host is itself a client: wait for both views.
for _ in range(40):
blocks = [g.raw('block', *cell).get('block') for g in (host, guest)]
if blocks == [f'minecraft:{block}'] * 2:
return blocks
host.wait(2)
raise AssertionError(f'{label} expected {block} on both clients: {blocks}')
for mode, block, item, soil in (
('survival', 'dandelion', 'dandelion', 'dirt'),
('survival', 'wheat', 'wheat_seeds', 'farmland[moisture=7]'),
('survival', 'carrots', 'carrot', 'farmland[moisture=7]'),
('creative', 'dandelion', 'dandelion', 'dirt'),
):
player('command', command=f'gamemode {mode}')
player('command', command='clear @s')
player('command', command=f'item replace entity @s weapon.mainhand with minecraft:{item} 8')
player('command', command=f'setblock {x} {y - 1} {z + 2} minecraft:{soil}')
player('command', command=f'setblock {x} {y} {z + 2} minecraft:{block}')
player.wait(5)
observe(block)
# Flowers' narrow outlines have a position-dependent offset.
for dx in (0.0, -0.2, 0.2):
player.raw('look-at', x + 0.5 + dx, y + (0.3 if block == 'dandelion' else 0.1), z + 2.5)
target = player('looking_at').get('block') or {}
if target.get('pos') == list(cell):
break
assert target.get('pos') == list(cell), f'{label} does not aim at {block}: {target}'
player.raw('mouse', 'left', 'click')
player.wait(5)
observe('air')
# Keep aiming at the supporting soil and use the held flower/seeds.
player.raw('mouse', 'right', 'click')
player.wait(3)
observe(block)
player.wait(20) # past the stale dig's five-tick destroy delay
key = f'{label} {mode} {block}'
seen[key] = [g.raw('block', *cell).get('block') for g in (host, guest)]
player.shot(out, f'replant-{mode}-{block}')
assert seen[key] == [f'minecraft:{block}'] * 2, f'{key}: {seen}'
player('command', command=f'setblock {x} {y} {z + 2} minecraft:air')
finally:
host('command', command='gamerule random_tick_speed 3')
return seen
CHECKS += ['replant']
CHECK_FNS['replant'] = check_replant
if __name__ == '__main__':
main()
+9
View File
@@ -11,6 +11,15 @@
"jobs": 14,
"exclude": {}
},
"desktop": {
"ssh": "desktop",
"root": ".actions-runners/horizon/parity-host",
"shell": "systemd-run --user --scope --quiet --slice=horizon-ci.slice --unit=horizon-parity-worker-$$ bash -c",
"setup": "test ! -e ~/.actions-runners/horizon/paused && set -a && . ~/.actions-runners/horizon/.env && set +a && export PATH=$(cat ~/.actions-runners/horizon/.path) && eval \"$(vscreen env)\"",
"jobs": 8,
"nice": 19,
"note": "ludodesktop, the maintainer's own machine: only while nobody uses it (tools/ci/runner_pause.py: screen locked or untouched for 15 min, no game; a paused desktop refuses workers and stops the running ones, whose harnesses then run here); 8 jobs at most, in the CI runner's environment and slice"
},
"thinkpad": {
"ssh": "thinkpad",
"root": "code/horizon-parity",
+14 -1
View File
@@ -191,6 +191,16 @@ def scenarios():
'mob minecraft:wandering_trader 0.5 -60 0.5 0 104 persistent',
'mob minecraft:trader_llama 3.5 -60 1.5 0 105 persistent leashto=0 strength=2',
'mob minecraft:trader_llama 3.5 -60 -1.5 0 106 persistent leashto=0 strength=4'])
# Death must detach immediately and drop exactly one lead throughout the corpse animation.
add('leash_death_trader_llama', 10, [
'player 14.5 -60 0.5',
'mob minecraft:wandering_trader 0.5 -60 0.5 0 104 persistent',
'mob minecraft:trader_llama 3.5 -60 1.5 0 105 persistent leashto=0 strength=2 dead',
])
add('leash_death_player_llama', 10, [
'player 0.5 -60 0.5',
'mob minecraft:llama 3.5 -60 0.5 0 101 persistent leashed strength=3 dead',
])
# Copper golems sorting chests (TransportItemsBetweenContainers): from a copper chest to a chest,
# skipping a chest without the carried item, queueing at a chest another golem has open, a double
# chest, a blocked copper chest, a part-full chest, and idling with nothing to carry.
@@ -358,6 +368,9 @@ def parse(path):
if parts[1] == 'hive':
cur.setdefault('hives', {}).setdefault(t, []).append(parts[2])
continue
if parts[1] == 'leads':
cur.setdefault('leads', {}).setdefault(t, []).append(parts[2])
continue
if parts[1] == 'chest':
cur.setdefault('chests', {}).setdefault(t, []).append(parts[2])
continue
@@ -455,7 +468,7 @@ def compare(vanilla, rust, fields=None):
clean = False
break
# Sounds, watched block changes, chest contents and hives: first differing tick.
for kind in ('sounds', 'blocks', 'chests', 'hives'):
for kind in ('sounds', 'blocks', 'chests', 'hives', 'leads'):
va, ra = v.get(kind, {}), r.get(kind, {})
for t in sorted(set(va) | set(ra)):
if va.get(t, []) != ra.get(t, []):