Merge origin/main into refactor/horizon-command
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+68
-6
@@ -26,6 +26,11 @@ change costs only the Rust side. A harness that fails while reusing oracle
|
||||
results is rerun fresh, and stops reusing them if it then passes. --all and
|
||||
--fresh never reuse them.
|
||||
|
||||
A harness listed in parity_hosts.json's "known_flaky" (each with its reason)
|
||||
that fails runs once more from scratch instead, and a pass then counts. Every
|
||||
retry is printed as a RETRIED line in the summary and in the CI job's summary.
|
||||
Fix the cause, then take the harness off the list: nothing else gets this retry.
|
||||
|
||||
Harness probes build into .local/parity-target with release optimisations but
|
||||
without LTO and with 16 codegen units (`PROFILE` below), which builds in
|
||||
seconds instead of minutes. Rust does not let those settings change results:
|
||||
@@ -1014,11 +1019,26 @@ def harness_of(label):
|
||||
return label.split("~")[0]
|
||||
|
||||
|
||||
def run(selected, state, hasher, environment_digest, executors, reuse_oracles, rounds=None):
|
||||
def keep_first_log(label):
|
||||
"""Move a harness's log aside before its retry writes a new one; returns where it went."""
|
||||
log = STATE_DIR / "logs" / f"{label}.log"
|
||||
kept = log.with_name(f"{label}.first-run.log")
|
||||
try:
|
||||
log.replace(kept)
|
||||
except OSError:
|
||||
return log # a remote host's run: its log stays on that machine
|
||||
return kept
|
||||
|
||||
|
||||
def run(selected, state, hasher, environment_digest, executors, reuse_oracles, rounds=None, known_flaky=None):
|
||||
"""Run the selected harnesses on the executors. rounds: how many times each must run (default once); its runs
|
||||
must agree, and a harness that both passes and fails is reported as flaky and recorded as failing."""
|
||||
must agree, and a harness that both passes and fails is reported as flaky and recorded as failing.
|
||||
known_flaky ({name: reason}, tools/parity_hosts.json): a harness listed there that fails its single round runs
|
||||
once more, from scratch; its record keeps `retried` (the first run's log is kept beside its own)."""
|
||||
records = state["harnesses"]
|
||||
rounds = rounds or {}
|
||||
known_flaky = known_flaky or {}
|
||||
second_chance = set() # known flaky harnesses that already failed once in this run
|
||||
# Longest first, so the slow harnesses don't start last; a harness's later rounds after its first.
|
||||
queue = sorted((name if index == 1 else f"{name}~{index}" for name in selected for index in range(1, rounds.get(name, 1) + 1)),
|
||||
key=lambda label: (-records.get(harness_of(label), {}).get("seconds", 1e9), label))
|
||||
@@ -1041,7 +1061,9 @@ def run(selected, state, hasher, environment_digest, executors, reuse_oracles, r
|
||||
if pick is None:
|
||||
break
|
||||
name = harness_of(pick)
|
||||
reuse = reuse_oracles and records.get(name, {}).get("oracle_reuse", True) and pick not in retried
|
||||
# A retry runs the oracle again too: it may be the side that failed (mob_ai's heap).
|
||||
reuse = reuse_oracles and records.get(name, {}).get("oracle_reuse", True) and pick not in retried \
|
||||
and name not in second_chance
|
||||
if not executor.start(pick, selected[name], reuse, records.get(name, {}).get("peak_bytes", DEFAULT_MEMORY),
|
||||
SHARDS.get(name)):
|
||||
break
|
||||
@@ -1066,9 +1088,12 @@ def run(selected, state, hasher, environment_digest, executors, reuse_oracles, r
|
||||
queue.insert(0, label)
|
||||
continue
|
||||
passed = record["status"] == "pass"
|
||||
if not passed and reused and label == name and records.get(name, {}).get("status") != "fail":
|
||||
flaky_retry = rounds.get(name, 1) == 1 and base_name(name) in known_flaky
|
||||
if not passed and reused and label == name and records.get(name, {}).get("status") != "fail" \
|
||||
and not flaky_retry:
|
||||
# A new failure might come from a reused oracle result: run it again from scratch. Later rounds reuse
|
||||
# what the first just validated, so their failures count (a flaky harness).
|
||||
# what the first just validated, so their failures count (a flaky harness). A known flaky harness
|
||||
# gets its own retry below instead, which keeps reusing oracle results afterwards.
|
||||
retried.add(label)
|
||||
queue.insert(0, label)
|
||||
print(f"retry {label} without reused oracle results", flush=True)
|
||||
@@ -1086,8 +1111,19 @@ def run(selected, state, hasher, environment_digest, executors, reuse_oracles, r
|
||||
if len(done[name]) < rounds.get(name, 1):
|
||||
continue
|
||||
runs = done.pop(name)
|
||||
if runs[0]["status"] != "pass" and flaky_retry and name not in second_chance:
|
||||
second_chance.add(name)
|
||||
first_log = keep_first_log(label)
|
||||
print(f"RETRIED {name}: failed, and it is a known flaky harness ({known_flaky[base_name(name)]}): "
|
||||
f"running it once more (first run's log: {first_log})", flush=True)
|
||||
queue.insert(0, label)
|
||||
continue
|
||||
record = dict(runs[0], status="pass" if all(run["status"] == "pass" for run in runs) else "fail",
|
||||
rounds=len(runs))
|
||||
if name in second_chance:
|
||||
record["retried"] = "known flaky"
|
||||
elif label in retried:
|
||||
record["retried"] = "reused oracle results"
|
||||
if len({run["status"] for run in runs}) > 1:
|
||||
record["flaky"] = [run["status"] for run in runs]
|
||||
print(f"FLAKY {name}: {', '.join(record['flaky'])} in {len(runs)} runs", flush=True)
|
||||
@@ -1309,12 +1345,36 @@ def platform_skips(config):
|
||||
return dict(config.get("linux_only", {}))
|
||||
|
||||
|
||||
def known_flaky(config):
|
||||
"""Harnesses tools/parity_hosts.json lists as failing now and then for a cause not fixed yet: one that fails runs
|
||||
once more, and passing then counts, reported as RETRIED. {name: reason}"""
|
||||
return dict(config.get("known_flaky", {}))
|
||||
|
||||
|
||||
def named_only(config):
|
||||
"""Harnesses tools/parity_hosts.json keeps out of every automatic selection (--changed, --failed, the default,
|
||||
--flake-check): they run only when named or with --all, the nightly audit. {name: reason}"""
|
||||
return dict(config.get("named_only", {}))
|
||||
|
||||
|
||||
def report_retries(results, flaky):
|
||||
"""Say loudly which harnesses needed their one retry (a known flaky one, or one that failed with reused oracle
|
||||
results), here and in the CI job's summary: a pass on the retry counts, so this is where flakes stay visible."""
|
||||
def why(name, record):
|
||||
if record["retried"] == "known flaky":
|
||||
return (f"known flaky: {flaky.get(base_name(name), '?')}; first run's log: "
|
||||
f"{STATE_DIR / 'logs' / (name + '.first-run.log')}")
|
||||
return "its first run reused oracle results; it no longer reuses them" if record["status"] == "pass" else \
|
||||
"its first run reused oracle results"
|
||||
lines = [f"RETRIED {name}: failed, then {'passed' if record['status'] == 'pass' else 'failed again'} on its one "
|
||||
f"retry ({why(name, record)})" for name, record in sorted(results.items()) if record.get("retried")]
|
||||
for line in lines:
|
||||
print(line, flush=True)
|
||||
if lines and os.environ.get("GITHUB_STEP_SUMMARY"):
|
||||
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary:
|
||||
summary.write("### Harnesses that failed once, then ran again\n" + "".join(f"- {line}\n" for line in lines))
|
||||
|
||||
|
||||
def finished_run(failed):
|
||||
"""Record that this run completed, for tools/gate.py: a crashed runner never writes it."""
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
@@ -1463,7 +1523,8 @@ def main():
|
||||
reuse_oracles = not (args.fresh or args.all)
|
||||
executors = [*remotes, LocalExecutor(jobs, int(memory_available() * 0.75), args.timeout,
|
||||
REMOTE_LOCAL_PEAK if remotes and args.jobs is None else None)]
|
||||
results, elapsed = run(selected, state, hasher, environment_key(hasher), executors, reuse_oracles, rounds)
|
||||
results, elapsed = run(selected, state, hasher, environment_key(hasher), executors, reuse_oracles, rounds,
|
||||
known_flaky(config))
|
||||
finally:
|
||||
for executor in remotes:
|
||||
executor.stop()
|
||||
@@ -1471,6 +1532,7 @@ def main():
|
||||
failed = sorted(name for name, record in results.items() if record["status"] != "pass")
|
||||
finished_run(failed)
|
||||
print(f"\n{len(results) - len(failed)} passed, {len(failed)} failed in {elapsed / 60:.1f} min.")
|
||||
report_retries(results, known_flaky(config))
|
||||
for index, name in enumerate(failed):
|
||||
log = STATE_DIR / 'logs' / (name + '.log')
|
||||
print(f" {name}: {log}")
|
||||
|
||||
@@ -42,5 +42,10 @@
|
||||
"linux_only": {},
|
||||
"named_only": {
|
||||
"lan_integration": "the whole lan_e2e suite: ~40 min a run on a loaded runner, and single checks flake under load; run it by name, or tools/lan_e2e.py"
|
||||
},
|
||||
"known_flaky": {
|
||||
"dedicated_server": "its Java client moves to the next step on a 1.5 s timer, not on the server's reply: under load a respawn's add_entity/update_attributes or entity_event 19 lands in the wrong step (failed, then passed at the same head, 10-26)",
|
||||
"remote_fireball": "samples the fireball on the wall clock, so a slow host sees it in too few samples (desktop runner, 3 times on 10-26)",
|
||||
"world_reopen": "counted 4 minecarts instead of 3 once on a loaded Mac mini runner, then passed at the same head (10-26)"
|
||||
}
|
||||
}
|
||||
|
||||
+37
-24
@@ -7,12 +7,13 @@
|
||||
python3 tools/pr_ready.py --quick # without running the vanilla harnesses
|
||||
|
||||
From the files the branch changes since its merge base with --base (committed or not) it decides what to run:
|
||||
rustfmt, clippy with warnings denied and the tests of the touched crates; the launcher (its own workspace) the
|
||||
same way when it, horizon-prepare or horizon-theme changed; crates/horizon-theme/tokens.css against horizon-theme;
|
||||
Cargo.lock changing only with a Cargo.toml; the Python tests and the public-tree check; and the vanilla
|
||||
harnesses the changes can affect, picked as CI's parity job picks them (tools/parity.py --changed). Harnesses run
|
||||
where the vanilla data is (a prepared .local/ here, or the Mac mini); elsewhere they are listed for CI.
|
||||
Clippy checks all targets of touched crates and their transitive workspace dependents, including examples.
|
||||
rustfmt, and clippy with warnings denied exactly as CI's verify job runs it (the whole workspace with the game's code
|
||||
mods, plus the server build when horizon-client is affected); the tests of the touched crates, with the features
|
||||
CI's workspace-wide run gives them; the launcher (its own workspace) the same way when CI's launcher job would run
|
||||
(tools/ci/rust_changes.py --launcher); crates/horizon-theme/tokens.css against horizon-theme; Cargo.lock changing
|
||||
only with a Cargo.toml; the Python tests (always, as in CI) and the public-tree check; and the vanilla harnesses the
|
||||
changes can affect, picked as CI's parity job picks them (tools/parity.py --changed). Harnesses run where the
|
||||
vanilla data is (a prepared .local/ here, or the Mac mini); elsewhere they are listed for CI.
|
||||
Tests select library, binary and integration targets explicitly, followed by doc tests, so unrelated example
|
||||
executables are not built and linked again.
|
||||
|
||||
@@ -43,6 +44,7 @@ if "PARITY_SHARED" not in os.environ and not (ROOT / ".local" / "minecraft").exi
|
||||
# A fleet worktree without vanilla data still knows each harness's dependencies.
|
||||
os.environ["PARITY_SHARED"] = str(FLEET_SHARED)
|
||||
from tools import parity, release_train # noqa: E402
|
||||
from tools.ci import rust_changes # noqa: E402
|
||||
|
||||
RBUILD = Path.home() / "fleet" / "rbuild"
|
||||
LINE_LIMIT = 500
|
||||
@@ -82,9 +84,8 @@ def workspace_rust(path):
|
||||
|
||||
|
||||
def launcher_rust(path):
|
||||
"""Whether a change to path is built into the launcher (its own workspace)."""
|
||||
return not is_doc(path) and any(path.startswith(p) for p in release_train.LAUNCHER_PATHS) and \
|
||||
path != "launcher/links.json" and not path.startswith("launcher/docs/")
|
||||
"""Whether a change to path is built into the launcher (its own workspace): CI's launcher job's own rule."""
|
||||
return rust_changes.needs_launcher([path])
|
||||
|
||||
|
||||
def touched_crates(paths, packages):
|
||||
@@ -268,14 +269,25 @@ def parity_summary(output):
|
||||
return text
|
||||
|
||||
|
||||
# CI's verify job (.github/workflows/ci.yml): clippy over the whole workspace with the game's code mods, and over the
|
||||
# server build (the game without sound or controllers); tests with code mods and mod packaging.
|
||||
CI_CLIPPY = "cargo clippy --workspace --all-targets --locked --features horizon-client/mods -- -D warnings"
|
||||
CI_CLIPPY_SERVER = "cargo clippy -p horizon-client --all-targets --locked --no-default-features -- -D warnings"
|
||||
CI_TEST_FEATURES = "horizon-client/mods,horizon-mods/pack"
|
||||
|
||||
|
||||
def mod_features(crates):
|
||||
"""Code mods are off by default (docs/mods.md): on wherever horizon-mods is checked, as in CI."""
|
||||
if crates is not None and "horizon-mods" not in crates:
|
||||
return ""
|
||||
features = ["horizon-mods/runtime", "horizon-mods/pack"]
|
||||
if crates is None or "horizon-client" in crates:
|
||||
"""The features CI's workspace-wide test run gives these crates (code mods are off by default: docs/mods.md).
|
||||
Cargo unifies features over the packages it builds, so a crate tested alone needs the ones the workspace would
|
||||
have turned on for it: horizon-client's code mods, and horizon-mods' runtime, packaging and index."""
|
||||
if crates is None:
|
||||
return f" --features {CI_TEST_FEATURES}"
|
||||
features = []
|
||||
if "horizon-mods" in crates:
|
||||
features += ["horizon-mods/runtime", "horizon-mods/pack", "horizon-mods/index"]
|
||||
if "horizon-client" in crates:
|
||||
features.append("horizon-client/mods")
|
||||
return f" --features {','.join(features)}"
|
||||
return f" --features {','.join(features)}" if features else ""
|
||||
|
||||
|
||||
def plan(args, base, changed, crates_of, libraries, dependencies):
|
||||
@@ -283,16 +295,18 @@ def plan(args, base, changed, crates_of, libraries, dependencies):
|
||||
rust = any(workspace_rust(path) for path in changed)
|
||||
launcher = any(launcher_rust(path) for path in changed)
|
||||
# The Python tests also hold ROADMAP.md to roadmap/roadmap.toml (tests/test_roadmap.py).
|
||||
python = any(path.endswith(".py") or path.startswith(("tests/", "tools/", "roadmap/")) or path == "ROADMAP.md"
|
||||
for path in changed)
|
||||
crates = touched_crates(changed, crates_of) if rust else []
|
||||
# An unrecognised Rust path must not silently skip validation.
|
||||
if rust and crates == []:
|
||||
crates = None
|
||||
selection = "--workspace" if crates is None else " ".join(f"-p {shlex.quote(c)}" for c in crates)
|
||||
# CI's own clippy commands: a crate checked alone gets other features than in CI's workspace-wide run, and an
|
||||
# unused import behind a feature passed here and failed in CI (#1895). Warm, the workspace run costs about what
|
||||
# the touched crates and their dependents did (14-32 s against 14-17 s on the Mac mini, 2026-10-26).
|
||||
clippy_crates = dependent_crates(crates, dependencies)
|
||||
clippy_selection = "--workspace" if clippy_crates is None else " ".join(
|
||||
f"-p {shlex.quote(c)}" for c in clippy_crates)
|
||||
clippy = CI_CLIPPY
|
||||
if clippy_crates is None or "horizon-client" in clippy_crates:
|
||||
clippy += f" && {CI_CLIPPY_SERVER}"
|
||||
test_skip = None if crates is None or crates else "no crate touched"
|
||||
doc_crates = sorted(libraries if crates is None else libraries.intersection(crates))
|
||||
doc_selection = "--workspace" if crates is None else " ".join(f"-p {shlex.quote(c)}" for c in doc_crates)
|
||||
@@ -300,11 +314,10 @@ def plan(args, base, changed, crates_of, libraries, dependencies):
|
||||
steps = [
|
||||
Step("Cargo.lock", where="git"),
|
||||
Step("Public tree", "python3 tools/check_public_tree.py", where="here"),
|
||||
Step("Python tests", "python3 -m unittest discover -s tests", where="here",
|
||||
skip=None if python else "no Python change", summary=unittest_passed),
|
||||
# Always, as in CI: some read the crates, the roadmap or the workflows.
|
||||
Step("Python tests", "python3 -m unittest discover -s tests", where="here", summary=unittest_passed),
|
||||
Step("rustfmt", "cargo fmt --all -- --check", skip=None if rust else no_rust),
|
||||
Step("clippy", f"cargo clippy {clippy_selection}{mod_features(clippy_crates)} --all-targets --locked -- -D warnings",
|
||||
skip=None if rust else no_rust),
|
||||
Step("clippy", clippy, skip=None if rust else no_rust),
|
||||
Step("tests" + (": workspace" if crates is None else f": {', '.join(crates)}" if crates else ""),
|
||||
f"cargo test --locked {selection}{mod_features(crates)} --tests",
|
||||
skip=test_skip, summary=tests_passed),
|
||||
@@ -404,7 +417,7 @@ def run_windows(steps, verbose):
|
||||
elif step.name == "rustfmt":
|
||||
command = ["cargo", "fmt", "--all", "--", "--check"]
|
||||
elif step.name == "clippy":
|
||||
command = ["cargo", "clippy", "--workspace", "--all-targets", "--locked", "--", "-D", "warnings"]
|
||||
command = shlex.split(CI_CLIPPY) # the server build's clippy runs in CI (Linux)
|
||||
elif step.name.startswith("tests"):
|
||||
command = shlex.split(step.command)
|
||||
elif step.name == "tokens.css up to date":
|
||||
|
||||
Executable
+104
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run a command on a Linux build host (default playhorizon) at a worktree's commit, and get its output back.
|
||||
#
|
||||
# tools/remote.sh [--host H] [--name N] [--cpus LIST] [--jobs J] <worktree> <command...>
|
||||
# tools/remote.sh .claude/worktrees/my-fix cargo test -p horizon-world --lib
|
||||
# tools/remote.sh . python3 tools/parity.py food light
|
||||
# tools/remote.sh --list # checkouts on the host, their size and last use
|
||||
# tools/remote.sh --gc [DAYS] # remove checkouts unused for DAYS (default 2)
|
||||
#
|
||||
# The host fetches the commit from GitHub itself: commit and push first (uncommitted changes are not sent, and
|
||||
# nothing else leaves this machine: no files, no credentials, no environment). Each name (default: the worktree's
|
||||
# folder) keeps one checkout there, ~/remote-work/<name>, with its own target/: the next run checks out the new
|
||||
# commit over it, so only what changed rebuilds (sccache shares the registry crates between names). One run per
|
||||
# name at a time. The command runs in bash at the checkout's root, niced in the host's CI slice, with the host's
|
||||
# toolchains, a virtual screen and scratch homes for the game and launcher. .local/ links to the host's vanilla
|
||||
# data; a command that runs harnesses (it names parity, lan_e2e or horizon-prepare) also gets .local/horizon-client,
|
||||
# prepared as CI prepares it (tools/ci/vanilla-data.sh). Output streams back and is kept in ~/remote-work/<name>.logs/.
|
||||
# The exit status is the command's.
|
||||
#
|
||||
# The host is lent by a partner who keeps hypervisor access: never send secrets, tokens or credentials there,
|
||||
# and never treat a result from it as a CI result.
|
||||
set -euo pipefail
|
||||
|
||||
# CPUs 0-3 stay free for benchmarks (perf-world-entry measures on playhorizon pinned to them); --cpus all for every one.
|
||||
host=playhorizon name="" jobs="" cpus=4-7
|
||||
usage() { sed -n '2,8s/^# \{0,1\}//p' "$0" >&2; exit 2; }
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--host) host=$2; shift 2;;
|
||||
--name) name=$2; shift 2;;
|
||||
--jobs) jobs=$2; shift 2;;
|
||||
--cpus) cpus=$2; shift 2;;
|
||||
--list) exec ssh "ludovic@$host" 'cd ~/remote-work 2>/dev/null && for d in */; do d=${d%/};
|
||||
printf "%-32s %8s last used %s\n" "$d" "$(du -sh "$d" 2>/dev/null | cut -f1)" "$(stat -c %y "$d.logs" 2>/dev/null | cut -c1-16)"; done';;
|
||||
--gc) days=${2:-2}; exec ssh "ludovic@$host" "cd ~/remote-work 2>/dev/null || exit 0
|
||||
find . -maxdepth 1 -name '*.logs' -mtime +$days | while read -r logs; do d=\${logs%.logs};
|
||||
flock -n \"\$d.lock\" rm -rf \"\$d\" \"\$logs\" \"\$d.lock\" && echo \"removed \${d#./}\"; done";;
|
||||
-h|--help) usage;;
|
||||
*) break;;
|
||||
esac
|
||||
done
|
||||
[ $# -ge 2 ] || usage
|
||||
tree=$(cd "$1" && git rev-parse --show-toplevel); shift
|
||||
sha=$(git -C "$tree" rev-parse HEAD)
|
||||
name=${name:-$(basename "$tree")}
|
||||
[[ $name =~ ^[A-Za-z0-9._-]+$ ]] || { echo "remote.sh: name '$name' must be letters, digits, . _ -" >&2; exit 2; }
|
||||
if ! git -C "$tree" diff --quiet HEAD -- 2>/dev/null; then
|
||||
echo "remote.sh: uncommitted changes in $tree are not sent: the host runs ${sha:0:9}" >&2
|
||||
fi
|
||||
if [ -z "$(git -C "$tree" branch -r --contains "$sha" 2>/dev/null)" ]; then
|
||||
git -C "$tree" fetch -q origin 2>/dev/null || true
|
||||
[ -n "$(git -C "$tree" branch -r --contains "$sha" 2>/dev/null)" ] ||
|
||||
{ echo "remote.sh: ${sha:0:9} is not on GitHub yet: push it first (the host fetches from GitHub)" >&2; exit 2; }
|
||||
fi
|
||||
command=$(printf '%q ' "$@")
|
||||
|
||||
# The host side reads its script and these four values on stdin (nothing is re-split by a remote shell); its
|
||||
# own environment comes from the runner's files there.
|
||||
{
|
||||
printf 'name=%q sha=%q jobs=%q cpus=%q command=%q\n' "$name" "$sha" "$jobs" "$cpus" "$command"
|
||||
cat <<'REMOTE'
|
||||
set -euo pipefail
|
||||
if [ "$cpus" = all ]; then pin=(); jobs=${jobs:-$(nproc)}; else pin=(taskset -c "$cpus"); jobs=${jobs:-$(taskset -c "$cpus" nproc)}; fi
|
||||
runner=~/.actions-runners/horizon
|
||||
if [ -e "$runner/paused" ]; then echo "remote.sh: this host is paused ($runner/paused)" >&2; exit 75; fi
|
||||
set -a; . "$runner/.env"; set +a
|
||||
export PATH="$(cat "$runner/.path")" DISPLAY=":$(cat "$runner/display")" RUSTC_WRAPPER="$(command -v sccache || true)"
|
||||
export CARGO_BUILD_JOBS=$jobs FLEET_LOAD_JOBS=$jobs PARITY_LOCAL_JOBS=$(( jobs > 1 ? jobs / 2 : 1 ))
|
||||
unset WAYLAND_DISPLAY
|
||||
mkdir -p ~/remote-work && cd ~/remote-work
|
||||
exec 9> "$name.lock"
|
||||
flock -n 9 || { echo "remote.sh: $name is busy with another run" >&2; exit 75; }
|
||||
if [ ! -d "$name/.git" ]; then
|
||||
git clone -q --filter=blob:none --no-checkout https://github.com/ludovic111/horizon "$name" 9>&-
|
||||
fi
|
||||
cd "$name"
|
||||
# The lock's descriptor stays out of everything started here (9>&-): a daemon one of them starts (sccache's server,
|
||||
# from the preparer's build or the command's) would hold the lock after the run.
|
||||
git fetch -q --no-tags origin "$sha" 9>&-
|
||||
git checkout -q --force --detach "$sha"
|
||||
git clean -qfd -e /target -e /.local
|
||||
# The host's vanilla data, linked as CI's runner links it; for harnesses also .local/horizon-client, prepared by
|
||||
# this commit's own preparer (once per preparer version, kept beside the data and shared by every name).
|
||||
if [[ $command =~ parity|lan_e2e|horizon-prepare ]]; then
|
||||
RUNNER_WORKSPACE=$(dirname "$HORIZON_SHARED_SOURCE") RUNNER_TEMP=$(mktemp -d) bash tools/ci/vanilla-data.sh >&2 9>&-
|
||||
else
|
||||
mkdir -p .local
|
||||
for d in minecraft tools datagen; do
|
||||
if [ -e "$HORIZON_SHARED_SOURCE/$d" ]; then ln -sfn "$HORIZON_SHARED_SOURCE/$d" ".local/$d"; fi
|
||||
done
|
||||
fi
|
||||
scratch=$(mktemp -d)
|
||||
trap 'rm -rf "$scratch"' EXIT
|
||||
export HORIZON_HOME=$scratch/game HORIZON_LAUNCHER_HOME=$scratch/launcher XDG_DATA_HOME=$scratch/data \
|
||||
XDG_CONFIG_HOME=$scratch/config HORIZON_NO_AUDIO=1 HORIZON_LAUNCHER_NO_SELF_UPDATE=1 HORIZON_TELEMETRY_URL=off
|
||||
mkdir -p "$HORIZON_HOME" "$HORIZON_LAUNCHER_HOME" "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" ../"$name.logs"
|
||||
log=../"$name.logs/$(date -u +%Y%m%dT%H%M%SZ)-${sha:0:9}.log"
|
||||
echo "remote.sh: $(hostname) at ${sha:0:9} in ~/remote-work/$name, CPUs $cpus, -j $jobs; log ~/remote-work/${log#../}" >&2
|
||||
status=0
|
||||
systemd-run --user --scope --quiet --slice=horizon-ci.slice --unit="remote-$name-$$" \
|
||||
"${pin[@]}" nice -n 10 bash -c "$command" 2>&1 < /dev/null 9>&- | tee "$log" || status=${PIPESTATUS[0]}
|
||||
exit "$status"
|
||||
REMOTE
|
||||
} | ssh -o BatchMode=yes "ludovic@$host" bash -s
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A vanilla loot chest at spawn has its loot when Horizon opens the world.
|
||||
|
||||
Vanilla rolls a container's loot table when a player first opens it
|
||||
(`RandomizableContainer.unpackLootTable`). Horizon rolls a loaded container with a loot table
|
||||
and no items as its chunk is read from disk (`save::roll_loaded_loot`), so a container nobody
|
||||
opens still saves as vanilla wrote it. The loot tables have to be loaded before the first chunks
|
||||
are read: the spawn chunks are read while the world opens, and a chest read before the tables
|
||||
came out empty, its loot table lost on the next save.
|
||||
|
||||
The vanilla 26.3 server writes a flat world with a seeded loot chest beside the world spawn, then
|
||||
rolls the chest itself in a copy of that world (`execute if items` unpacks it). Horizon opens the
|
||||
untouched world in a new process, so nothing was loaded before the world, and must hold the same
|
||||
items in the same slots. Both single-player paths: the default server thread and in-frame.
|
||||
|
||||
test_spawn_loot_parity.py [--bin-dir DIR] [--keep]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from test_save_roundtrip_parity import Vanilla # noqa: E402
|
||||
from test_world_reopen_parity import game_env # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
RESOURCES = ROOT / '.local' / 'horizon-client' / '26.3'
|
||||
RUN = ROOT / '.local' / 'spawn-loot'
|
||||
CHEST = (2, -60, 1)
|
||||
LOOT = '{LootTable:"minecraft:chests/simple_dungeon",LootTableSeed:42L}'
|
||||
MODES = {'server thread': [], 'in-frame': ['--in-frame']}
|
||||
|
||||
|
||||
def vanilla_world():
|
||||
"""The world with the unopened chest, and what vanilla rolls from it: [(slot, id, count)]."""
|
||||
server = Vanilla(RUN / 'v0')
|
||||
try:
|
||||
server.run('setworldspawn 0 -60 0')
|
||||
server.run('forceload add 0 0')
|
||||
time.sleep(2)
|
||||
server.run('setblock {} {} {} minecraft:chest{}'.format(*CHEST, LOOT))
|
||||
server.run('save-all flush')
|
||||
time.sleep(2)
|
||||
finally:
|
||||
server.stop()
|
||||
shutil.copytree(RUN / 'v0', RUN / 'vv')
|
||||
server = Vanilla(RUN / 'vv')
|
||||
try:
|
||||
server.run('forceload add 0 0')
|
||||
time.sleep(2)
|
||||
server.run('execute if items block {} {} {} container.* *'.format(*CHEST))
|
||||
text = ' '.join(server.run('data get block {} {} {} Items'.format(*CHEST)))
|
||||
finally:
|
||||
server.stop()
|
||||
rolled = []
|
||||
for item in re.finditer(r'\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}', text.split('data:', 1)[-1]):
|
||||
found = item.group(0)
|
||||
count = re.search(r'count: (\d+)', found)
|
||||
rolled.append((int(re.search(r'Slot: (\d+)b', found).group(1)), re.search(r'id: "([^"]+)"', found).group(1),
|
||||
int(count.group(1)) if count else 1))
|
||||
return sorted(rolled)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build them with the fast profile)')
|
||||
parser.add_argument('--keep', action='store_true', help='keep the run folder')
|
||||
args = parser.parse_args()
|
||||
bin_dir = Path(args.bin_dir).resolve() if args.bin_dir else None
|
||||
if bin_dir is None:
|
||||
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'], cwd=ROOT, check=True)
|
||||
bin_dir = ROOT / os.environ.get('CARGO_TARGET_DIR', 'target') / 'fast'
|
||||
shutil.rmtree(RUN, ignore_errors=True)
|
||||
RUN.mkdir(parents=True)
|
||||
expected = vanilla_world()
|
||||
print('vanilla rolls:', expected)
|
||||
if not expected:
|
||||
sys.exit('vanilla rolled nothing from the chest')
|
||||
env, extra = game_env()
|
||||
failures = 0
|
||||
for index, (mode, flags) in enumerate(MODES.items()):
|
||||
folder = RUN / f'h{index}'
|
||||
shutil.copytree(RUN / 'v0' / 'world', folder / 'saves' / 'world')
|
||||
socket = Path(tempfile.mkdtemp(prefix='hzsl')) / 'control.sock' # sockets need short paths
|
||||
|
||||
def ctl(*words, check=True):
|
||||
result = subprocess.run([str(bin_dir / 'horizon-ctl'), '--socket', str(socket), '--timeout', '600',
|
||||
*map(str, words)], cwd=folder, env=env, capture_output=True, text=True)
|
||||
if check and result.returncode:
|
||||
sys.exit(f'horizon-ctl {" ".join(map(str, words))} failed: {result.stdout}{result.stderr}')
|
||||
return json.loads(result.stdout) if result.stdout.strip().startswith('{') else result.stdout
|
||||
|
||||
ctl('launch', '--resources', RESOURCES, '--world', 'world', '--render-distance', '4', *flags, *extra)
|
||||
try:
|
||||
ctl('wait-ready', '300')
|
||||
slots = ctl('container', *CHEST)['slots']
|
||||
finally:
|
||||
ctl('quit', check=False)
|
||||
got = sorted((slot, stack['item'], stack['count']) for slot, stack in enumerate(slots) if stack)
|
||||
ok = got == expected
|
||||
failures += not ok
|
||||
print(f'{mode}: {len(got)} stacks', 'ok' if ok else f'FAIL: {got}')
|
||||
if not args.keep and not failures:
|
||||
shutil.rmtree(RUN, ignore_errors=True)
|
||||
print('spawn loot:', 'PASS' if not failures else f'{failures} FAILED')
|
||||
sys.exit(1 if failures else 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user