From d4b2e24535111e7b8e1b839bcc16c4ef126fa663 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Dr=C3=A4ger?= <20014538+sdraeger@users.noreply.github.com> Date: Sat, 24 Oct 2026 13:21:23 -0700 Subject: [PATCH 01/43] Add mod command capability and Predator Missile example --- AGENTS.md | 2 +- Cargo.lock | 7 + Cargo.toml | 2 +- crates/horizon-client/src/game/mods.rs | 13 ++ .../examples/predator-missile/Cargo.toml | 16 ++ .../predator-missile/horizon-mod.toml | 8 + .../examples/predator-missile/src/lib.rs | 161 ++++++++++++++++++ crates/horizon-mod-sdk/src/lib.rs | 4 +- crates/horizon-mod-sdk/wit/horizon.wit | 9 + crates/horizon-mods/src/manifest.rs | 12 +- crates/horizon-mods/src/runtime.rs | 17 +- crates/horizon-mods/tests/sandbox.rs | 45 ++++- docs/api/mods-reference.md | 13 +- docs/mods.md | 3 +- 14 files changed, 300 insertions(+), 12 deletions(-) create mode 100644 crates/horizon-mod-sdk/examples/predator-missile/Cargo.toml create mode 100644 crates/horizon-mod-sdk/examples/predator-missile/horizon-mod.toml create mode 100644 crates/horizon-mod-sdk/examples/predator-missile/src/lib.rs diff --git a/AGENTS.md b/AGENTS.md index f6f6b463b..fda05c1e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,7 +80,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end ~25, a file of the client lib ~103, of `horizon-world` ~103–109, of `horizon-core` ~119. Plan for it. - Rust integration tests: `crates/horizon-client/tests/` (`lan_bot.rs`, `generation_saves.rs`, `streaming_meshes.rs`). - **macOS:** `cargo build/test --workspace` may fail to link the two wasm guest cdylibs (undefined - `horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude horizon-mods-test-guest`. + `horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude predator-missile --exclude horizon-mods-test-guest`. Their real check is `cargo test -p horizon-mods` (builds them for `wasm32-unknown-unknown`). - Linux needs `libasound2-dev libudev-dev`; `--no-default-features` drops audio and controllers (the server build). - Run and drive the game (starts the `horizon-client` beside `horizon-ctl`; other arguments go to the game): diff --git a/Cargo.lock b/Cargo.lock index 27eaad0c4..1468327ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2620,6 +2620,13 @@ dependencies = [ "zerovec", ] +[[package]] +name = "predator-missile" +version = "0.1.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "presser" version = "0.3.1" diff --git a/Cargo.toml b/Cargo.toml index f197c34fe..a0feaba87 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 572f9fe2b..c203d0ca2 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -342,6 +342,19 @@ impl Game<'_> { } Output::Feedback { text, error: false } => Text::literal(text), Output::Feedback { text, error: true } => Text::literal(text).with_color(text::RED), + // Vanilla's commands only: a mod running a mod command could loop. + Output::Command { line } => { + let name = line.split(' ').next().unwrap_or_default(); + // As handle_chat_input, without the chat history. + if !vanilla_command(name) { + // dropped + } else if self.remote.is_some() { + self.send_chat(&format!("/{line}")); + } else { + self.run_command(&line); + } + continue; + } Output::Stopped { name, reason } => { self.list_mods(); self.sync_mod_commands(); diff --git a/crates/horizon-mod-sdk/examples/predator-missile/Cargo.toml b/crates/horizon-mod-sdk/examples/predator-missile/Cargo.toml new file mode 100644 index 000000000..a3a77ce0b --- /dev/null +++ b/crates/horizon-mod-sdk/examples/predator-missile/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "predator-missile" +version = "0.1.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Example Horizon mod: a missile you launch with /missile and steer with the mouse" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../.." } + +[lints] +workspace = true diff --git a/crates/horizon-mod-sdk/examples/predator-missile/horizon-mod.toml b/crates/horizon-mod-sdk/examples/predator-missile/horizon-mod.toml new file mode 100644 index 000000000..3baaf7d87 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/predator-missile/horizon-mod.toml @@ -0,0 +1,8 @@ +id = "predator_missile" +name = "Predator Missile" +version = "0.1.0" +description = "/missile launches a guided missile 60 blocks above you. Steer it with the mouse; it explodes on whatever it hits. Needs cheats (it runs vanilla commands as you)." +authors = ["Horizon"] +api = "0.1" +side = "client" +capabilities = ["game-read", "hud", "chat", "command"] diff --git a/crates/horizon-mod-sdk/examples/predator-missile/src/lib.rs b/crates/horizon-mod-sdk/examples/predator-missile/src/lib.rs new file mode 100644 index 000000000..75ebbbdec --- /dev/null +++ b/crates/horizon-mod-sdk/examples/predator-missile/src/lib.rs @@ -0,0 +1,161 @@ +//! Example Horizon mod (`docs/mods.md`): `/missile` turns you into a guided +//! missile 60 blocks up. You fly along your own look, so the mouse steers; +//! on a block or a mob a stack of primed TNT goes off, and you are put back +//! where you launched. Built from vanilla commands (capability `command`), +//! so it needs cheats. +use horizon_mod_sdk::{ + Mod, Registration, + command::run, + game::{self, Player}, + hud::{self, Corner, Line}, +}; + +/// Blocks per tick (a fired arrow does about 3). +const SPEED: f64 = 1.5; +const ALTITUDE: i32 = 60; +/// Ticks of flight before the missile detonates on its own. +const FUEL: u32 = 30 * 20; +/// Ticks to watch the blast before going back. +const AFTERMATH: u32 = 40; +/// Primed TNT per blast: the stack's explosions add up. +const WARHEAD: usize = 4; +/// What the impact checks print; the mod hears it through the chat hook. +const IMPACT: &str = "Predator: impact"; + +enum State { + Idle, + Flying { from: Player, ticks: u32 }, + Aftermath { from: Player, ticks: u32 }, +} + +struct Predator { + state: State, +} + +fn launch() { + run("gamerule send_command_feedback false"); + run("execute if entity @s[gamemode=creative] run tag @s add pm_creative"); + run("gamemode spectator"); + run(&format!("tp @s ~ ~{ALTITUDE} ~ ~ 60")); + run("effect give @s night_vision 60 0 true"); + // The thermal camera: every mob outlined. + run("effect give @e[type=!player,distance=..256] glowing 60 0 true"); +} + +/// One tick of flight: stop at the surface (the next step would enter a +/// block or a mob), else move one step along the look. +fn fly() { + run(&format!( + "execute at @s unless block ^ ^ ^{SPEED} #minecraft:air run tellraw @s \"{IMPACT}\"" + )); + run(&format!( + "execute at @s positioned ^ ^ ^{SPEED} if entity @e[type=!player,distance=..2] run tellraw @s \"{IMPACT}\"" + )); + run(&format!( + "execute at @s if block ^ ^ ^{SPEED} #minecraft:air run tp @s ^ ^ ^{SPEED}" + )); +} + +fn detonate() { + for _ in 0..WARHEAD { + run("execute at @s run summon tnt ^ ^ ^1 {fuse:0s}"); + } +} + +fn land(from: &Player) { + run(&format!( + "tp @s {} {} {} {} {}", + from.x, from.y, from.z, from.yaw, from.pitch + )); + run("execute if entity @s[tag=pm_creative] run gamemode creative"); + run("execute unless entity @s[tag=pm_creative] run gamemode survival"); + run("execute if entity @s[tag=pm_creative] run tag @s remove pm_creative"); + run("effect clear @s night_vision"); + // shortcut: assumes feedback was on before launch, as in a new world. + run("gamerule send_command_feedback true"); +} + +fn panel(p: &Player, ticks: u32) -> Vec { + let green = 0x7CFF7C; + let left = (FUEL - ticks.min(FUEL)) / 20; + [ + "PREDATOR".to_string(), + format!("ALT {:.0}", p.y), + format!("FUEL {left}s"), + "Mouse to steer, /missile to detonate".to_string(), + ] + .into_iter() + .map(|text| Line { text, color: green }) + .collect() +} + +impl Predator { + fn impact(&mut self) { + if let State::Flying { from, .. } = &self.state { + detonate(); + self.state = State::Aftermath { + from: from.clone(), + ticks: 0, + }; + } + } +} + +impl Mod for Predator { + fn init() -> Result<(Self, Registration), String> { + let hooks = Registration::new().command("missile").on_tick().on_chat(); + Ok((Predator { state: State::Idle }, hooks)) + } + + fn tick(&mut self, _tick: u64) { + match &mut self.state { + State::Idle => {} + State::Flying { ticks, .. } => { + *ticks += 1; + let ticks = *ticks; + if ticks >= FUEL { + return self.impact(); + } + // The first tick waits for the launch teleport. + if ticks > 1 { + fly(); + } + if let Some(p) = game::get_player() { + hud::set_panel(Corner::TopLeft, &panel(&p, ticks)); + } + } + State::Aftermath { from, ticks } => { + *ticks += 1; + if *ticks >= AFTERMATH { + land(from); + hud::clear(); + self.state = State::Idle; + } + } + } + } + + fn chat(&mut self, text: &str) { + if text.contains(IMPACT) { + self.impact(); + } + } + + fn command(&mut self, _name: &str, _args: &str) -> Result, String> { + match self.state { + State::Idle => { + let from = game::get_player().ok_or("Not in a world")?; + launch(); + self.state = State::Flying { from, ticks: 0 }; + Ok(Some("Missile away".into())) + } + State::Flying { .. } => { + self.impact(); + Ok(None) + } + State::Aftermath { .. } => Err("Wait for the blast to clear".into()), + } + } +} + +horizon_mod_sdk::export_mod!(Predator); diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 71c36cf80..7efcf20b3 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -21,7 +21,7 @@ //! ``` //! //! Every interface but `log` is a capability: list the ones the mod uses in -//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`). +//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`, `command`). wit_bindgen::generate!({ path: "wit", @@ -32,7 +32,7 @@ wit_bindgen::generate!({ }); pub use exports::horizon::mods::events::{Guest as __Guest, Registration}; -pub use horizon::mods::{chat, game, hud, log, storage}; +pub use horizon::mods::{chat, command, game, hud, log, storage}; /// The game's calls into a mod. Only the hooks [`Registration`] asks for /// are called; the others may stay as their defaults. diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 9f00a12b1..e14913782 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -86,6 +86,14 @@ interface storage { delete: func(key: string); } +/// Capability `command`: vanilla commands run as the player, with the +/// player's permissions, after the hook call returns (8 per call). A mod's +/// own commands are not run this way. +interface command { + /// `line` without its slash; its feedback goes to the chat as if typed. + run: func(line: string); +} + /// What the game calls. Only the hooks `init` asks for are ever called. interface events { record registration { @@ -117,5 +125,6 @@ world horizon-mod { import chat; import hud; import storage; + import command; export events; } diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index a71210883..6f1674e05 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -69,16 +69,19 @@ pub enum Capability { Chat, Hud, Storage, + /// Runs vanilla commands as the player, with the player's permissions. + Command, /// New blocks and items from the mod's `data/` (API 0.2): no WIT /// interface, the game reads them before the world loads. Registries, } impl Capability { - pub const ALL: [Capability; 5] = [ + pub const ALL: [Capability; 6] = [ Capability::GameRead, Capability::Chat, Capability::Hud, Capability::Storage, + Capability::Command, Capability::Registries, ]; /// The WIT interface it grants, in `horizon:mods`. @@ -88,6 +91,7 @@ impl Capability { Capability::Chat => "chat", Capability::Hud => "hud", Capability::Storage => "storage", + Capability::Command => "command", Capability::Registries => "registries", } } @@ -98,6 +102,7 @@ impl Capability { Capability::Chat => "show you chat messages", Capability::Hud => "draw text on your screen", Capability::Storage => "save its own settings to disk", + Capability::Command => "run commands as you, with your permissions", Capability::Registries => "add blocks and items to your worlds", } } @@ -128,6 +133,7 @@ impl fmt::Display for Capability { Capability::Chat => "chat", Capability::Hud => "hud", Capability::Storage => "storage", + Capability::Command => "command", Capability::Registries => "registries", }; f.write_str(name) @@ -366,6 +372,10 @@ capabilities = ["game-read", "hud"] storage, Err("uses capability storage, missing from horizon-mod.toml".into()) ); + assert_eq!( + m.check_imports(["horizon:mods/command@0.1.0"]), + Err("uses capability command, missing from horizon-mod.toml".into()) + ); let with_storage = EXAMPLE.replace("\"hud\"", "\"hud\", \"storage\""); let m = Manifest::parse(&with_storage).unwrap(); assert_eq!(m.check_imports(["horizon:mods/storage@0.1.0"]), Ok(())); diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 9dd2eb54e..07be81909 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -23,7 +23,7 @@ pub use bindings::horizon::mods::{ use bindings::{ HorizonMod, exports::horizon::mods::events::Registration, - horizon::mods::{chat, game, hud, log as mod_log, storage}, + horizon::mods::{chat, command, game, hud, log as mod_log, storage}, }; /// A mod's linear memory cap. @@ -67,6 +67,9 @@ pub enum Output { Chat { name: String, text: String }, /// A mod command's feedback, red when `error`. Feedback { text: String, error: bool }, + /// `command.run`: a vanilla command line, without its slash, to run as + /// the player. + Command { line: String }, /// The mod was turned off: it trapped, overran or failed to start. Stopped { name: String, reason: String }, } @@ -514,6 +517,18 @@ impl chat::Host for State { } } } +impl command::Host for State { + fn run(&mut self, line: String) { + let queued = self + .out + .iter() + .filter(|o| matches!(o, Output::Command { .. })) + .count(); + if queued < CHAT_PER_CALL { + self.out.push(Output::Command { line: clip(line) }); + } + } +} impl hud::Host for State { fn set_panel(&mut self, corner: Corner, lines: Vec) { let lines = lines diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index a246c07b0..c8e4fb883 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -1,4 +1,5 @@ -//! Loads real mods built with the SDK: the coords-hud example and a guest +//! Loads real mods built with the SDK: the coords-hud and predator-missile +//! examples and a guest //! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`. use horizon_mods::{ Clock, Corner, Mods, Output, Package, Player, Snapshot, Status, manifest::componentize, @@ -18,7 +19,7 @@ api = "0.1" capabilities = ["chat", "storage"] "#; -/// Builds both mods once and writes their `.hmod` files; returns the folder. +/// Builds the mods once and writes their `.hmod` files; returns the folder. fn mods_dir() -> &'static Path { static DIR: OnceLock = OnceLock::new(); DIR.get_or_init(|| { @@ -31,6 +32,8 @@ fn mods_dir() -> &'static Path { "-p", "coords-hud", "-p", + "predator-missile", + "-p", "horizon-mods-test-guest", "--target-dir", ]) @@ -44,9 +47,13 @@ fn mods_dir() -> &'static Path { let built = target.join("wasm32-unknown-unknown/release"); let dir = target.join("mods"); std::fs::create_dir_all(&dir).unwrap(); - let example = root.join("crates/horizon-mod-sdk/examples/coords-hud/horizon-mod.toml"); + let example = |name: &str| { + let path = format!("crates/horizon-mod-sdk/examples/{name}/horizon-mod.toml"); + std::fs::read_to_string(root.join(path)).unwrap() + }; let mods = [ - ("coords_hud", std::fs::read_to_string(example).unwrap()), + ("coords_hud", example("coords-hud")), + ("predator_missile", example("predator-missile")), ("horizon_mods_test_guest", GUEST_MANIFEST.to_string()), ]; for (name, manifest) in mods { @@ -81,6 +88,36 @@ fn player() -> Snapshot { } } +/// Capability `command`: `/missile` queues vanilla commands, and the chat +/// line its impact check prints sets off the warhead. +#[test] +fn predator_missile_runs_commands() { + let mut mods = load("predator_missile.hmod"); + assert_eq!(mods.entries()[0].status, Status::Running); + mods.set_snapshot(player()); + let commands = |mods: &mut Mods| -> Vec { + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Command { line } => Some(line), + _ => None, + }) + .collect() + }; + assert!(mods.command("missile")); + let launch = commands(&mut mods); + assert_eq!(launch.len(), 6); + assert!(launch.contains(&"gamemode spectator".to_string())); + mods.tick(1); + mods.tick(2); + let flight = commands(&mut mods); + assert!(flight.iter().any(|l| l.ends_with("run tp @s ^ ^ ^1.5"))); + mods.chat("Predator: impact"); + let blast = commands(&mut mods); + assert_eq!(blast.len(), 4); + assert!(blast.iter().all(|l| l.contains("summon tnt"))); +} + #[test] fn coords_hud_draws_and_answers() { let mut mods = load("coords_hud.hmod"); diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index ca2fe9d7a..28703e784 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -11,11 +11,12 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `chat` | [`chat`](#chat) | show you chat messages | | `hud` | [`hud`](#hud) | draw text on your screen | | `storage` | [`storage`](#storage) | save its own settings to disk | +| `command` | [`command`](#command) | run commands as you, with your permissions | | `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds | ## World `horizon-mod` -- Imports (what the game offers): `log`, `game`, `chat`, `hud`, `storage` +- Imports (what the game offers): `log`, `game`, `chat`, `hud`, `storage`, `command` - Exports (what the mod provides): `events` ## `log` @@ -117,6 +118,16 @@ Capability `storage`: a per-mod folder of small key/value files, quota'd (docs/m | `set` | `func(key: string, value: list) -> result<_, string>` | Errs on a malformed key or over quota (bytes for the whole mod). | | `delete` | `func(key: string)` | No error if `key` was already absent. | +## `command` + +Access: capability `command`. + +Capability `command`: vanilla commands run as the player, with the player's permissions, after the hook call returns (8 per call). A mod's own commands are not run this way. + +| Function | Signature | What it does | +| --- | --- | --- | +| `run` | `func(line: string)` | `line` without its slash; its feedback goes to the chat as if typed. | + ## `events` Access: exported by the mod: the game calls it. diff --git a/docs/mods.md b/docs/mods.md index d8ea925b3..5d386720b 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -13,7 +13,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. |---|---|---| | The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage; tick, frame, chat and command hooks | | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | -| Example mod | `crates/horizon-mod-sdk/examples/coords-hud` | coordinates, facing and time HUD, `/where`, `/coords` | +| Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands | | Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model | | Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new / build / run` | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | @@ -84,6 +84,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `chat` | `chat` | `show(text)`: a line only the local player sees, after the mod's name (8 per call) | | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | +| `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run | | Hook (export) | When | |---|---| From c2c8df4542b857911ec396e0430da5b46fdffdb1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 10:47:54 +0100 Subject: [PATCH 02/43] Mods: run a mod's commands on the next tick Run while the mod's output was shown, a command's chat line reached the mods again inside that call: a mod that answers a line with a command that prints one recursed without end, and when a control-socket command set the hook off, the mod's commands ran with the console's level. Queue them for the next tick instead, where the player's own level applies (the server already checks it on a server). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/mods.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index c203d0ca2..8364a4d58 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -39,6 +39,11 @@ pub(super) struct ModsState { /// The chat's command tree while a running mod owns commands. #[cfg(feature = "mods")] tree: Option, + /// `command.run` lines for this window's own world, run on the next tick: + /// run at once, their chat lines would reach the mods while their output + /// is still being shown, and a mod answering its own lines would recurse. + #[cfg(feature = "mods")] + commands: Vec, } impl ModsState { /// The chat's command tree: vanilla's, plus the running mods' commands. @@ -283,6 +288,11 @@ impl Game<'_> { } /// A game tick. pub(super) fn tick_mods(&mut self) { + // Here, at the player's level: shown inside a console call (a control + // socket command set the hook off), they would run as the console. + for line in std::mem::take(&mut self.mods.commands) { + self.run_command(&line); + } if !self.mods.mods.is_running() { return; } @@ -345,13 +355,13 @@ impl Game<'_> { // Vanilla's commands only: a mod running a mod command could loop. Output::Command { line } => { let name = line.split(' ').next().unwrap_or_default(); - // As handle_chat_input, without the chat history. if !vanilla_command(name) { - // dropped + // Dropped. } else if self.remote.is_some() { + // The server checks the player's permissions. self.send_chat(&format!("/{line}")); } else { - self.run_command(&line); + self.mods.commands.push(line); } continue; } From 5262effa7e4b13cd4737563dabeda3dc03e2f8af Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 10:48:35 +0100 Subject: [PATCH 03/43] cargo horizon-mod check: list the commands a mod runs Main's check reports every output; the command capability adds one. Co-Authored-By: Claude Opus 5.5 --- crates/cargo-horizon-mod/src/check.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 0294bec98..a1cb44c9e 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -214,6 +214,7 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { Output::Feedback { text, error } => { format!("{}: {text}", if error { "error" } else { "feedback" }) } + Output::Command { line } => format!("command: /{line}"), Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), }); } From 39904c8051546efdb808f0fa9a8ccb68043f7dd2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 11:33:08 +0100 Subject: [PATCH 04/43] docs/mods.md: the contract lists the command interface Co-Authored-By: Claude Opus 5.5 --- docs/mods.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mods.md b/docs/mods.md index 2f7105398..a021d420b 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -12,7 +12,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | Part | Where | State | |---|---|---| -| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage; tick, frame, chat and command hooks | +| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, command; tick, frame, chat and command hooks | | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | | Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands | | Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model | From 1437537cbfd16e349ee39eef7ec544fb6cb3fe01 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 08:39:29 +0100 Subject: [PATCH 05/43] Worker threads: leave one core, as vanilla does, not two Graphics::worker_threads sizes the worker pools (the server thread's, which generates and lights, and the window's, which meshes). Its automatic count left two cores to the render and server threads; vanilla's executor leaves one (Util.maxAllowedExecutorThreads). The workers run behind those threads (niced on Linux; above four cores, raised server and render threads on macOS and Windows), so the second core mostly idled: on a 4-thread laptop only 2 cores generated while a world loaded. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/graphics.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 3cf1402d2..291bf8a80 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -376,14 +376,18 @@ impl Graphics { if self.workers > 0 { return self.workers as usize; } - // The pool never takes every core. The render thread and the - // integrated server thread (single player runs on its own server - // thread by default) each need one, and a pool that fills every core - // starves them: the frame rate collapses to single digits while the - // workers saturate the CPU and its memory bandwidth. + // Vanilla's count (Util.maxAllowedExecutorThreads: every core but + // one). The pool never takes every core: a pool that fills them all + // starves the render and server threads, and the frame rate collapses + // while the workers saturate the CPU and its memory bandwidth. One + // core left is enough with the workers behind those two threads + // (horizon_threads: niced on Linux; on macOS and Windows the server + // and render threads are raised above four cores, where vanilla + // raises its server thread). Leaving two idled a core of a 4-thread + // laptop while a world loaded: a teleport there took ~15% longer. let auto = std::thread::available_parallelism() .map_or(2, |n| n.get()) - .saturating_sub(2) + .saturating_sub(1) .max(1); if self.battery { auto.div_ceil(2) } else { auto } } @@ -546,11 +550,11 @@ mod tests { } #[test] - fn automatic_workers_leave_cores_for_the_render_and_server_threads() { + fn automatic_workers_leave_a_core_as_vanilla_does() { let g = Graphics::default(); assert_eq!(g.workers, 0); let cores = std::thread::available_parallelism().map_or(2, |n| n.get()); - assert_eq!(g.worker_threads(), cores.saturating_sub(2).max(1)); + assert_eq!(g.worker_threads(), cores.saturating_sub(1).max(1)); // A manual count is the player's own choice, kept as asked. let manual = Graphics { workers: 3, ..g }; assert_eq!(manual.worker_threads(), 3); From 40c77c02f0332188ae7622dd7b2ae842df5becb7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:15:19 +0100 Subject: [PATCH 06/43] PalettedContainer: look up a word's filled bits, not divide for them `locate` found an entry's word by multiplication (the MAGIC table) but still divided `64 / bits` at run time for the shift, on every block read and write of a section stored in 5, 6 or 7 bits. A division by a value the compiler does not know costs tens of cycles on x86: `perf annotate` of a 10-bot server on the ThinkPad put 12% of `PalettedContainer::get`, the server thread's top function, on that `div`. The table now also holds the bits a word's entries fill, so the shift is `i * bits - word * filled`. A test checks `locate` against the division for every width and entry. ThinkPad (i5-7200U), 4M random reads, 5-7 bit palettes: 28.5-36.9 -> 24.6-32.4 ns over 2,000 sections, 6.7-7.1 -> 5.4-5.8 ns within one; 4 and 8 bits (shifts, unchanged) the same. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-core/src/paletted.rs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index 802eac225..9aa4aec6a 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -106,14 +106,16 @@ enum Palette { List(Vec), Global, } -/// `n / per_word` for `n < 4096` by multiplication: `MAGIC[bits] = ceil(2^20 / -/// (64 / bits))` is exact while `n * (64 / bits) < 2^20`. -const MAGIC: [u32; 33] = { - let mut table = [0; 33]; +/// `n / per_word` for `n < 4096` by multiplication: `MAGIC[bits].0 = ceil(2^20 / +/// (64 / bits))` is exact while `n * (64 / bits) < 2^20`. `.1` is the bits a +/// word's entries fill (`64 / bits * bits`): looked up, not divided for, as a +/// division by a run-time value costs tens of cycles on x86. +const MAGIC: [(u32, u32); 33] = { + let mut table = [(0, 0); 33]; let mut bits = 1; while bits <= 32 { let per = 64 / bits as u32; - table[bits] = (1u32 << 20).div_ceil(per); + table[bits] = ((1u32 << 20).div_ceil(per), per * bits as u32); bits += 1; } table @@ -134,9 +136,9 @@ fn locate(bits: u8, i: usize) -> (usize, u32) { let word = i >> (6 - log); (word, ((i & ((64 >> log) - 1)) as u32) << log) } else { - let per = 64 / u32::from(bits); - let word = (i as u32 * MAGIC[usize::from(bits)]) >> 20; - (word as usize, (i as u32 - word * per) * u32::from(bits)) + let (magic, filled) = MAGIC[usize::from(bits)]; + let word = (i as u32 * magic) >> 20; + (word as usize, i as u32 * u32::from(bits) - word * filled) } } #[inline] @@ -720,6 +722,17 @@ mod tests { use super::*; const BLOCKS: Strategy = Strategy::blocks(16); const BIOMES: Strategy = Strategy::biomes(7); + + #[test] + fn locate_matches_division_for_every_width() { + for bits in 1..=32u8 { + let per = 64 / usize::from(bits); + for i in 0..4096 { + let expected = (i / per, ((i % per) * usize::from(bits)) as u32); + assert_eq!(locate(bits, i), expected, "{bits} bits, entry {i}"); + } + } + } fn rng(state: &mut u64) -> u64 { *state ^= *state << 13; *state ^= *state >> 7; From 1506c1808a2e5bd9bee4307090c09d111ad9e446 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 13:16:16 +0100 Subject: [PATCH 07/43] Add /pregen: generate, light and save an area ahead of the players A Chunky-like command for single player and servers: /pregen start [square|circle] [ ], status, pause, continue and cancel, with progress (chunks, chunks/s, time left) in the log and to the player who started it. The area is swept strip by strip by a band of rows that streaming treats like a player's area (Streaming::set_band). A row is done once its chunks are lit and post-processed; the rows behind the band then unload and are saved, so memory holds only the rows in flight. The band's chunks are ranked for decoration row by row as they come within reach, so a task decorates in the same order however its jobs are timed. Between ticks the server waits on the workers' results and schedules the next jobs at once instead of once a tick. --- crates/horizon-client/src/command/vanilla.rs | 46 +++- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/commands.rs | 2 + .../horizon-client/src/game/commands/extra.rs | 2 + .../src/game/commands/pregen.rs | 252 ++++++++++++++++++ .../src/game/commands/terrain_cmds.rs | 2 +- crates/horizon-client/src/game/levels.rs | 13 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/pregen.rs | 111 ++++++++ crates/horizon-client/src/streaming.rs | 131 ++++++++- docs/README.md | 1 + docs/hosting.md | 2 + docs/pregeneration.md | 41 +++ 13 files changed, 594 insertions(+), 11 deletions(-) create mode 100644 crates/horizon-client/src/game/commands/pregen.rs create mode 100644 crates/horizon-client/src/pregen.rs create mode 100644 docs/pregeneration.md diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index cdd4848d7..cba5a5d5b 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -538,12 +538,50 @@ fn apply_vanilla_order(d: &mut Dispatcher) { } /// The tree the game runs: a release integrated server's, or with /// `HORIZON_DEV_COMMANDS` set the development one -/// (SharedConstants.DEBUG_DEV_COMMANDS). +/// (SharedConstants.DEBUG_DEV_COMMANDS), plus Horizon's own commands. pub fn game_dispatcher() -> &'static Dispatcher { - if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() { - dispatcher() + static DEV: std::sync::OnceLock = std::sync::OnceLock::new(); + static RELEASE: std::sync::OnceLock = std::sync::OnceLock::new(); + let (tree, dev) = if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() { + (&DEV, true) } else { - release_dispatcher() + (&RELEASE, false) + }; + tree.get_or_init(|| { + let mut d = build_with(dev); + horizon_commands(&mut d, 0); + d + }) +} +/// Commands vanilla doesn't have, after its own: `/pregen` +/// (docs/pregeneration.md). +fn horizon_commands(d: &mut Dispatcher, root: usize) { + let pregen = d.literal(root, "pregen"); + d.requires(pregen, GAMEMASTERS); + let start = d.literal(pregen, "start"); + let radius = d.argument( + start, + "radius", + ArgType::Integer { + min: 0, + max: 30_000_000, + }, + ); + d.executes(radius, "pregen.start"); + for shape in ["square", "circle"] { + let shape = d.literal(radius, shape); + d.executes(shape, "pregen.start"); + let center = d.argument(shape, "center", ArgType::ColumnPos); + d.executes(center, "pregen.start"); + } + for (word, id) in [ + ("pause", "pregen.pause"), + ("continue", "pregen.continue"), + ("cancel", "pregen.cancel"), + ("status", "pregen.status"), + ] { + let w = d.literal(pregen, word); + d.executes(w, id); } } pub fn dispatcher() -> &'static Dispatcher { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..fa00e3804 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10590,6 +10590,7 @@ impl Game<'_> { // The loading screen's chunk map fills ring by ring, as vanilla's. self.streaming.loading = self.options.execution_role.is_client() && self.loading_reason().is_some(); + self.tick_pregen(); let (uploads, unloaded) = horizon_client::spans::time("streaming", || self.streaming.update(&mut self.world)); if let Some(lod) = &mut self.lod { diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 19a16e261..d5f9e6542 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -10,6 +10,7 @@ mod items; mod misc; mod place; mod players; +pub(super) mod pregen; mod raid; mod terrain_cmds; mod text_commands; @@ -758,6 +759,7 @@ impl Game<'_> { "ride.mount" | "ride.dismount" => self.cmd_ride(id, ctx), "spreadplayers" => self.cmd_spreadplayers(ctx), id if id.starts_with("forceload.") => self.cmd_forceload(id, ctx), + id if id.starts_with("pregen.") => self.cmd_pregen(id, ctx), "fillbiome" => self.cmd_fillbiome(ctx), id if id.starts_with("worldborder.") => self.cmd_worldborder(id, ctx), id if id.starts_with("loot.") => self.cmd_loot(id, ctx), diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index ef69be6d9..ca431b8e7 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -57,6 +57,8 @@ pub(in crate::game) struct CommandExtras { /// The `CommandResultCallback` results of the outermost source, when a /// harness records them. pub results: Option>, + /// The running `/pregen` task. + pub pregen: Option, } use horizon_core::version::{BUILD_TIME, DATA_VERSION, STABLE, VANILLA_VERSION, VERSION_ID}; diff --git a/crates/horizon-client/src/game/commands/pregen.rs b/crates/horizon-client/src/game/commands/pregen.rs new file mode 100644 index 000000000..d61ba63ac --- /dev/null +++ b/crates/horizon-client/src/game/commands/pregen.rs @@ -0,0 +1,252 @@ +//! `/pregen`, Horizon's own command: generate, light and save every chunk of a +//! square or a circle ahead of the players (docs/pregeneration.md). The task +//! lives on the server and hands its band to the level's streaming, whose +//! workers do the work; chunks behind the band unload and are saved as any +//! chunk the players leave. +use super::{CommandError, Context, Dim, Game, R}; +use horizon_client::{ + lan::data::component_nbt, + pregen::{Pregen, Shape}, + text::{self, Text}, +}; +use horizon_protocol::packets::play::{self, Clientbound as C}; +use std::time::{Duration, Instant}; + +/// How often the progress is reported. +const REPORT_EVERY: Duration = Duration::from_secs(5); + +pub(in crate::game) struct PregenTask { + pregen: Pregen, + dim: Dim, + paused: bool, + /// Time spent running, up to the last pause, and when it last resumed. + ran: Duration, + resumed: Instant, + reported: Instant, + /// The player who started it, told the progress too (a guest's connection). + owner: Option, +} + +impl PregenTask { + fn running_for(&self) -> Duration { + if self.paused { + self.ran + } else { + self.ran + self.resumed.elapsed() + } + } + fn progress(&self) -> Text { + let p = &self.pregen; + let seconds = self.running_for().as_secs_f64(); + let rate = p.done as f64 / seconds.max(1e-3); + let left = p.total - p.done; + let eta = if rate > 0.0 { + duration(left as f64 / rate) + } else { + "unknown".into() + }; + Text::literal(format!( + "Pregenerating {}: {} of {} chunks ({:.1}%), {rate:.1} chunks/s, {} left", + self.dim.id(), + p.done, + p.total, + 100.0 * p.done as f64 / p.total.max(1) as f64, + if p.done == p.total { + "nothing".into() + } else { + eta + }, + )) + } +} + +fn failure(message: &str) -> CommandError { + CommandError::new(Text::literal(message)) +} + +/// `1h 02m 03s`. +fn duration(seconds: f64) -> String { + let s = seconds.round() as u64; + match (s / 3600, s / 60 % 60, s % 60) { + (0, 0, s) => format!("{s}s"), + (0, m, s) => format!("{m}m {s:02}s"), + (h, m, s) => format!("{h}h {m:02}m {s:02}s"), + } +} + +impl Game<'_> { + pub(super) fn cmd_pregen(&mut self, id: &str, ctx: &Context) -> R { + match id { + "pregen.start" => { + if self.cmds.pregen.is_some() { + return Err(failure( + "Pregeneration is already running: /pregen cancel stops it", + )); + } + let radius = Self::int(ctx, "radius").unwrap_or(0); + let shape = if ctx.literals.iter().any(|l| l == "circle") { + Shape::Circle + } else { + Shape::Square + }; + let [x, z] = if ctx.get("center").is_some() { + self.column_arg(ctx, "center")? + } else { + let p = self.source_position(); + [p[0].floor() as i32, p[2].floor() as i32] + }; + let pregen = Pregen::new((x >> 4, z >> 4), radius >> 4, shape); + let now = Instant::now(); + let total = pregen.total; + self.feedback(Text::literal(format!( + "Pregenerating {total} chunks of {}: a {} of radius {radius} around {x} {z}", + self.dim.id(), + match shape { + Shape::Square => "square", + Shape::Circle => "circle", + }, + ))); + self.cmds.pregen = Some(PregenTask { + pregen, + dim: self.dim, + paused: false, + ran: Duration::ZERO, + resumed: now, + reported: now, + owner: self.lan_acting, + }); + Ok(total as i32) + } + "pregen.pause" | "pregen.continue" => { + let pause = id == "pregen.pause"; + let task = self + .cmds + .pregen + .as_mut() + .ok_or_else(|| failure("No pregeneration is running"))?; + if task.paused != pause { + task.paused = pause; + if pause { + task.ran += task.resumed.elapsed(); + } else { + task.resumed = Instant::now(); + } + } + let (progress, dim) = (task.progress(), task.dim); + if pause && self.dim == dim { + self.streaming.set_band(None); + } + self.feedback( + Text::literal(if pause { "Paused. " } else { "Continuing. " }).append(progress), + ); + Ok(1) + } + "pregen.cancel" => { + let task = self + .cmds + .pregen + .take() + .ok_or_else(|| failure("No pregeneration is running"))?; + if self.dim == task.dim { + self.streaming.set_band(None); + } + self.feedback(Text::literal("Cancelled. ").append(task.progress())); + Ok(task.pregen.done as i32) + } + _ => { + let task = self + .cmds + .pregen + .as_ref() + .ok_or_else(|| failure("No pregeneration is running"))?; + let progress = task.progress(); + let done = task.pregen.done as i32; + self.feedback(progress); + Ok(done) + } + } + } + + /// Move the task's band past the rows that are lit and hand it to the + /// level's streaming, and report the progress now and then. Runs before + /// each streaming update of the level in place. + pub(in crate::game) fn tick_pregen(&mut self) { + let Some(task) = self.cmds.pregen.as_mut() else { + return; + }; + if task.dim != self.dim || task.paused { + return; + } + // A row is done once its chunks are lit and post-processed + // (`postprocess_chunks`, on the tick), as vanilla's are by the time + // they are FULL: then they may unload and be saved. + let (streaming, chunks) = (&mut self.streaming, &self.world.chunks); + task.pregen.advance(|x, z| { + streaming.is_lit(x, z) + && chunks + .get(&(x, z)) + .is_some_and(|c| c.postprocess.is_empty()) + }); + streaming.set_band(task.pregen.band()); + let finished = task.pregen.finished(); + if finished || task.reported.elapsed() >= REPORT_EVERY { + task.reported = Instant::now(); + let (owner, mut message) = (task.owner, task.progress()); + if finished { + message = Text::literal("Done. ") + .append(message) + .with_color(text::GREEN); + self.cmds.pregen = None; + } + self.pregen_report(owner, message); + } + } + + /// Whether the level in place has a running task, which the server pumps + /// between its ticks (`pump_pregen`). + pub(in crate::game) fn pregen_runs_here(&self) -> bool { + self.cmds + .pregen + .as_ref() + .is_some_and(|t| t.dim == self.dim && !t.paused) + } + + /// The level a running task needs ticked, whoever is in it. + pub(in crate::game) fn pregen_level(&self) -> Option { + self.cmds.pregen.as_ref().map(|t| t.dim) + } + + /// Keep the workers fed until `until`: collect what they finished and + /// hand them the next jobs as soon as each one is done, rather than once + /// a tick. + pub(in crate::game) fn pump_pregen(&mut self, until: Instant) { + while self.pregen_runs_here() { + let now = Instant::now(); + if now >= until { + break; + } + self.streaming + .wait((until - now).min(Duration::from_millis(5))); + self.update_world(); + } + } + + /// The console and the player who started the task get the progress. + fn pregen_report(&mut self, owner: Option, message: Text) { + if self.options.dedicated.is_some() { + super::super::dedicated::log("INFO", &message.plain()); + } else { + log::info!("{}", message.plain()); + } + if let Some(host) = &self.lan { + if let Some(g) = owner.and_then(|c| host.hub.guest(c)) { + g.send(&C::SystemChat(play::SystemChat { + content: component_nbt(&message.component()), + overlay: false, + })); + } + } else if self.options.dedicated.is_none() { + self.system_message(message); + } + } +} diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index df52f2251..d4b1c125c 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -30,7 +30,7 @@ fn ticks_to_seconds(ticks: i64) -> String { impl Game<'_> { // ---- /forceload ---------------------------------------------------------- - fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> { + pub(super) fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> { let c = self .coords(ctx, name) .ok_or_else(|| err("argument.pos2d.incomplete", &[]))?; diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index f685200f2..588f425a4 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -365,7 +365,12 @@ impl Game<'_> { } *next += self.clock.tick_duration(); if *next > now { - std::thread::sleep(*next - now); + // A `/pregen` task keeps the workers fed until the next tick. + self.pump_pregen(*next); + let now = Instant::now(); + if *next > now { + std::thread::sleep(*next - now); + } } else if now - *next > Duration::from_secs(2) { *next = now; } @@ -373,7 +378,7 @@ impl Game<'_> { /// The levels this server tick runs, in `MinecraftServer.levels` order /// (the Overworld, the Nether, the End): every level with a player in - /// it, or the Overworld while nobody is online. + /// it or a `/pregen` task, or the Overworld while nobody is online. pub(super) fn levels_to_tick(&self) -> Vec { let guests = self .lan @@ -381,7 +386,9 @@ impl Game<'_> { .map_or(&[][..], |h| h.hub.guests.as_slice()); let mut dims: Vec = [Dim::Overworld, Dim::Nether, Dim::End] .into_iter() - .filter(|d| guests.iter().any(|g| g.dimension == d.id())) + .filter(|d| { + guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d) + }) .collect(); if dims.is_empty() { dims.push(Dim::Overworld); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ae95e1bdb..5125608d4 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -145,6 +145,7 @@ pub mod player_sync; pub mod poi_sections; pub mod portal_sections; pub mod pose; +pub mod pregen; pub mod projectiles; pub mod raid; pub mod random_sequences; diff --git a/crates/horizon-client/src/pregen.rs b/crates/horizon-client/src/pregen.rs new file mode 100644 index 000000000..f31a6d712 --- /dev/null +++ b/crates/horizon-client/src/pregen.rs @@ -0,0 +1,111 @@ +//! Pregeneration (`/pregen`): every chunk of a square or a circle generated, +//! lit and saved ahead of the players. The area is cut into strips of columns +//! and each strip is swept north to south by a [`Band`] a few rows deep: +//! streaming generates the band's chunks and keeps them until they are lit, +//! then the band moves on and the rows behind it unload and are saved, so +//! memory stays bounded whatever the radius. +use crate::streaming::Band; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Shape { + Square, + Circle, +} + +/// The widest strip, in chunks. Strips are swept one after another; the few +/// columns along the edge between two are generated with both. +const STRIP_WIDTH: i32 = 256; +/// How many chunks a band holds at least: enough to keep every worker busy +/// while the rows before it finish. +const BAND_CHUNKS: i32 = 1024; + +pub struct Pregen { + /// The centre chunk and the radius in chunks. + pub center: (i32, i32), + pub radius: i32, + pub shape: Shape, + /// The strips' columns, west to east. + strips: Vec<(i32, i32)>, + strip: usize, + /// The band's first row: every row of the strip before it is done. + row: i32, + /// Chunks of the area lit so far, and in all. + pub done: u64, + pub total: u64, +} + +impl Pregen { + pub fn new(center: (i32, i32), radius: i32, shape: Shape) -> Self { + let radius = radius.max(0); + let (x0, width) = (center.0 - radius, 2 * radius + 1); + let count = (width + STRIP_WIDTH - 1) / STRIP_WIDTH; + let strips = (0..count) + .map(|i| (x0 + width * i / count, x0 + width * (i + 1) / count - 1)) + .collect(); + let mut pregen = Self { + center, + radius, + shape, + strips, + strip: 0, + row: center.1 - radius, + done: 0, + total: 0, + }; + pregen.total = (center.1 - radius..=center.1 + radius) + .map(|z| pregen.row_chunks(x0, x0 + width - 1, z)) + .sum(); + pregen + } + + fn contains(&self, x: i32, z: i32) -> bool { + match self.shape { + Shape::Square => true, + Shape::Circle => { + let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1)); + dx * dx + dz * dz <= i64::from(self.radius) * i64::from(self.radius) + } + } + } + + fn row_chunks(&self, x0: i32, x1: i32, z: i32) -> u64 { + (x0..=x1).filter(|&x| self.contains(x, z)).count() as u64 + } + + /// The band streaming should hold now; none once every strip is done. + pub fn band(&self) -> Option { + let &(x0, x1) = self.strips.get(self.strip)?; + let rows = (BAND_CHUNKS + (x1 - x0)) / (x1 - x0 + 1); + Some(Band { + x0, + x1, + z0: self.row, + z1: (self.row + rows - 1).min(self.center.1 + self.radius), + circle: (self.shape == Shape::Circle).then_some((self.center, self.radius)), + }) + } + + /// Move past the band's first rows once all their chunks are `lit`. + /// Returns whether the band moved. + pub fn advance(&mut self, lit: impl Fn(i32, i32) -> bool) -> bool { + let mut moved = false; + while let Some(&(x0, x1)) = self.strips.get(self.strip) { + let z = self.row; + if !(x0..=x1).all(|x| !self.contains(x, z) || lit(x, z)) { + break; + } + self.done += self.row_chunks(x0, x1, z); + self.row += 1; + if self.row > self.center.1 + self.radius { + self.strip += 1; + self.row = self.center.1 - self.radius; + } + moved = true; + } + moved + } + + pub fn finished(&self) -> bool { + self.strip >= self.strips.len() + } +} diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 55a2f0086..51c4eaea4 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -278,6 +278,11 @@ pub struct Streaming { cover: Option, /// Mesh the sections for drawing (false on a server thread). pub mesh: bool, + /// The pregeneration band (`set_band`). + band: Option, + /// The columns and the next row the band's decoration ranks were given + /// for (`set_band`). + band_ranked: Option<(i32, i32, i32)>, } /// Snapshot only after a scan found no missing candidates. Public range fields /// and `World::chunks` can change without going through Streaming, so compare @@ -289,6 +294,7 @@ struct GenerationScan { radius: i32, extra: Vec<((i32, i32), i32)>, forced: HashSet<(i32, i32)>, + band: Option, chunk_revision: u64, } impl GenerationScan { @@ -298,6 +304,7 @@ impl GenerationScan { && self.radius == ranges.radius && self.extra == ranges.extra && self.forced == *ranges.forced + && self.band.as_ref() == ranges.band && self.chunk_revision == world.chunks.membership_revision() } fn remember(&mut self, ranges: Ranges<'_>, world: &World) { @@ -307,6 +314,7 @@ impl GenerationScan { self.extra.clear(); self.extra.extend_from_slice(ranges.extra); self.forced.clone_from(ranges.forced); + self.band = ranges.band.copied(); self.chunk_revision = world.chunks.membership_revision(); } } @@ -348,6 +356,10 @@ impl GenerationScan { let r = radius + margin.max(reach + 1); runs.extend((center.1 - r..=center.1 + r).map(|z| (z, center.0 - r, center.0 + r))); } + if let Some(band) = input.ranges.band { + let r = margin.max(reach + 1); + runs.extend((band.z0 - r..=band.z1 + r).map(|z| (z, band.x0 - r, band.x1 + r))); + } runs.sort_unstable(); let mut runs = runs.into_iter().peekable(); while let Some((z, x0, mut x1)) = runs.next() { @@ -392,6 +404,7 @@ impl GenerationScan { extra: input.ranges.extra, forced: input.ranges.forced, cover: input.ranges.cover, + band: input.ranges.band, }; self.remember(ranges, input.world); } else { @@ -564,6 +577,8 @@ impl Streaming { extra: Vec::new(), cover: None, mesh: true, + band: None, + band_ranked: None, } } /// Shares generation resources, but gives distant work its own worker state. @@ -916,6 +931,7 @@ impl Streaming { p.is_some() && i64::from(x - center.0).pow(2) + i64::from(z - center.1).pow(2) > r4 * r4 && !ranges.in_extra(x, z, 4) + && !ranges.in_band(x, z, 4) && !ranges .forced .iter() @@ -985,6 +1001,7 @@ impl Streaming { extra: &self.extra, forced: &self.forced, cover: ExtraCover::matching(&self.cover, &self.extra), + band: self.band.as_ref(), }; let (protos, generating) = (&self.protos, &self.generating); self.decoration_order.retain(|x, z| { @@ -1113,6 +1130,7 @@ impl Streaming { extra: &self.extra, forced: &self.forced, cover: ExtraCover::matching(&self.cover, &self.extra), + band: self.band.as_ref(), }; self.waiting.retain(|&(x, sy, z)| { let back = ranges.in_view(x, z); @@ -1189,6 +1207,7 @@ impl Streaming { extra: &self.extra, forced: &self.forced, cover: ExtraCover::matching(&self.cover, &self.extra), + band: self.band.as_ref(), }, world, generating: &self.generating, @@ -1285,6 +1304,7 @@ impl Streaming { extra: &self.extra, forced: &self.forced, cover: ExtraCover::matching(&self.cover, &self.extra), + band: self.band.as_ref(), } } fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool { @@ -1354,6 +1374,45 @@ impl Streaming { fn in_range(&self, x: i32, z: i32, margin: i32) -> bool { self.ranges().in_range(x, z, margin) } + pub fn band(&self) -> Option { + self.band + } + /// Generate, light and keep the chunks of `band` (none: stop), and let + /// go of what earlier bands held as it falls out of range. The chunks a + /// band reaches are ranked for decoration row by row, as they first come + /// within reach, so that a task decorates in the same order however its + /// work is timed and shared among the workers. + pub fn set_band(&mut self, band: Option) { + if self.band == band { + return; + } + self.band = band; + self.generation_scan.exhausted = false; + let Some(band) = band else { + return; + }; + // Decoration reaches two chunks past the band and generation three. + const REACH: i32 = 4; + let (x0, x1) = (band.x0 - REACH, band.x1 + REACH); + let first = match self.band_ranked { + Some((rx0, rx1, next)) if (rx0, rx1) == (x0, x1) => next, + _ => band.z0 - REACH, + }; + let end = band.z1 + REACH; + for z in first..=end { + for x in x0..=x1 { + self.decoration_order.rank_or_append(x, z); + } + } + self.band_ranked = Some((x0, x1, end.max(first - 1) + 1)); + } + /// Wait up to `timeout` for a worker to finish a job; the next `update` + /// takes it. A server pumps generation with this between its ticks. + pub fn wait(&mut self, timeout: std::time::Duration) { + if let Ok(done) = self.results.recv_timeout(timeout) { + self.deferred.push(done); + } + } } /// `ChunkTrackingView.isInViewDistance`: whether the column (x, z) is drawn /// at this render distance around `center`, the camera's column @@ -1373,6 +1432,53 @@ struct Ranges<'a> { /// `extra` as a grid, when one was made for it: `in_extra` without a /// scan of every area. cover: Option<&'a ExtraCover>, + band: Option<&'a Band>, +} +/// The chunks a pregeneration task (`/pregen`) wants lit now: rows `z0..=z1` +/// of the columns `x0..=x1`, those within `circle` (a centre and a radius in +/// chunks) when there is one. Like an extra area, it finishes its chunks and +/// the ring around them, so that its own chunks can be lit, and generation +/// reaches past that. A task moves it down a strip of columns a row at a +/// time, so each chunk is generated once and only the rows in flight stay +/// loaded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Band { + pub x0: i32, + pub x1: i32, + pub z0: i32, + pub z1: i32, + pub circle: Option<((i32, i32), i32)>, +} +impl Band { + /// Whether (x, z) lies within `margin` (Chebyshev) of one of the band's + /// chunks: the square of side `2 * margin + 1` around it meets the + /// rectangle at a point inside the circle. + pub fn within(&self, x: i32, z: i32, margin: i32) -> bool { + let (x0, x1) = ( + x.saturating_sub(margin).max(self.x0), + x.saturating_add(margin).min(self.x1), + ); + let (z0, z1) = ( + z.saturating_sub(margin).max(self.z0), + z.saturating_add(margin).min(self.z1), + ); + if x0 > x1 || z0 > z1 { + return false; + } + self.circle.is_none_or(|((cx, cz), r)| { + let dx = i64::from(cx.clamp(x0, x1)) - i64::from(cx); + let dz = i64::from(cz.clamp(z0, z1)) - i64::from(cz); + dx * dx + dz * dz <= i64::from(r) * i64::from(r) + }) + } + /// The band's chunks go after the players' (lower runs first), row by + /// row, as the task wants them lit. + fn priority(&self, x: i32, z: i32) -> i64 { + const AFTER_PLAYERS: i64 = 1 << 40; + AFTER_PLAYERS + + (i64::from(z - self.z0 + 8).max(0) << 20) + + i64::from(x - self.x0 + 8).max(0) + } } /// For every column near the extra areas, how far it lies outside the /// nearest one's square (Chebyshev distance less its radius; 0 inside). A server has an area per player, and streaming asks of every @@ -1468,10 +1574,14 @@ impl ExtraCover { impl Ranges<'_> { /// `distance`, or `rings` while the level loading screen is up. fn priority(&self, x: i32, z: i32, loading: bool) -> i64 { - if loading { + let own = if loading { self.rings(x, z) } else { self.distance(x, z) + }; + match self.band { + Some(band) if band.within(x, z, 4) => own.min(band.priority(x, z)), + _ => own, } } /// Ring by ring: the Chebyshev distance to the nearest centre first, then @@ -1532,10 +1642,18 @@ impl Ranges<'_> { let (dx, dz) = (gap(x - self.center.0), gap(z - self.center.1)); let r = i64::from(self.radius + 1); // The extra areas are squares: their finished square grown by `reach`. - dx * dx + dz * dz <= r * r || self.in_extra(x, z, 1 + reach) + dx * dx + dz * dz <= r * r + || self.in_extra(x, z, 1 + reach) + || self.in_band(x, z, 1 + reach) } fn in_range(&self, x: i32, z: i32, margin: i32) -> bool { - self.in_main_range(x, z, margin) || self.in_extra(x, z, margin) + self.in_main_range(x, z, margin) + || self.in_extra(x, z, margin) + || self.in_band(x, z, margin) + } + /// Within `margin` of the pregeneration band. + fn in_band(&self, x: i32, z: i32, margin: i32) -> bool { + self.band.is_some_and(|b| b.within(x, z, margin)) } /// Within `margin` of an extra area's square (Chebyshev distance, as /// vanilla's ticket levels spread). @@ -1659,6 +1777,7 @@ mod tests { extra: &self.extra, forced: &self.forced, cover: None, + band: None, }, world: &self.world, generating: &self.generating, @@ -1972,6 +2091,7 @@ mod tests { extra: &[], forced: &forced, cover: None, + band: None, }; let square = |x: i32, z: i32, n: i32| { (-n..=n).flat_map(move |dz| (-n..=n).map(move |dx| (x + dx, z + dz))) @@ -2027,6 +2147,7 @@ mod tests { extra: &[], forced: &forced, cover: None, + band: None, }; let at = |dx: i32, dz: i32| (2 + dx, -1 + dz); let key = |(x, z): (i32, i32), loading| r.priority(x, z, loading); @@ -2053,6 +2174,7 @@ mod tests { extra: &[((radius * 2 + 9, 3), 4)], forced: &forced, cover: None, + band: None, }; let span = radius * 3 + 20; for x in -span..=span { @@ -2093,6 +2215,7 @@ mod tests { extra: &extra, forced: &forced, cover: None, + band: None, }; let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0); for x in 40 - view - 8..=40 + view + 8 { @@ -2161,6 +2284,7 @@ mod cover_tests { extra: &extra, forced: &forced, cover, + band: None, }; let (scan, grid) = (ranges(None), ranges(Some(&cover))); let span = [4, 30, 120][case % 3] + 40; @@ -2218,6 +2342,7 @@ mod cover_tests { extra: &extra, forced: &forced, cover, + band: None, }; // The columns streaming asks about: everything kept, and the // generation scan's ring past it. diff --git a/docs/README.md b/docs/README.md index 1450ba388..48ddfd7b5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -34,6 +34,7 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor ## Architecture: world generation - [World generation](world-generation.md): the pipeline from noise to features. +- [Pregeneration](pregeneration.md): `/pregen`, generating, lighting and saving an area ahead of the players. - [Noise generation](noise-generation.md), [compiled density functions](density-functions.md), [structure density](structure-density.md), [terrain filling](terrain-filling.md). - Biomes: [lookup](biome-lookup.md), [temperatures](biome-temperatures.md). - Surfaces: [material surfaces](material-surfaces.md), [material conditions](material-conditions.md), [rule libraries](material-rule-libraries.md), [vertical anchors](vertical-anchors.md), [value providers](value-providers.md). diff --git a/docs/hosting.md b/docs/hosting.md index bf431cada..4c4c954bc 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -218,6 +218,8 @@ horizon-server rollback back to the release before While the server runs, `op`, `whitelist` and `cmd` go to the game's console, so they act exactly as vanilla's console commands do. While it's stopped, they edit vanilla's files directly. Any console command works through `cmd`: `horizon-server cmd ban Griefer`, `horizon-server cmd say Restarting in 5 minutes`. +To generate the world around spawn ahead of the players, Horizon has its own `pregen` command: +`horizon-server cmd pregen start 2500` ([pregeneration](pregeneration.md)). `config set` changes `server.toml` without opening it: `horizon-server config set world.difficulty=hard server.max_players=10`. Each key is a section and a name from the file (`properties.spawn-protection=0` for any diff --git a/docs/pregeneration.md b/docs/pregeneration.md new file mode 100644 index 000000000..a8ca228b3 --- /dev/null +++ b/docs/pregeneration.md @@ -0,0 +1,41 @@ +# Pregeneration: `/pregen` + +`/pregen` generates every chunk of a square or a circle ahead of the players, lights it and saves it, as +Chunky does on a Java server. It is Horizon's own command (vanilla has none), available in single player +with cheats on and to operators (level 2) on a server, from the chat or the server console +(`horizon-server cmd pregen start 2500`). + +```text +/pregen start [square|circle] [ ] radius in blocks; the centre defaults to where you + stand (the world spawn from the console) +/pregen status chunks done, chunks per second, time left +/pregen pause | continue stop scheduling new chunks, and go on +/pregen cancel stop; what is done stays saved +``` + +The area is the chunks within `radius / 16` chunks of the centre chunk: a square of side +`2 * (radius / 16) + 1` (radius 2500 is 313 x 313 = 97,969 chunks), or the chunks whose distance from the +centre chunk is at most `radius / 16`. It runs in the dimension the command was run in; that level keeps +ticking while the task runs, whoever is in it. The progress goes to the server log every five seconds +and to the player who started it, and once more when it is done. A task is not kept across a restart: +start it again and the chunks already saved load instead of generating. + +## How it works + +- `horizon_client::pregen::Pregen` cuts the area into strips at most 256 chunks wide and sweeps each + north to south with a band of rows (`streaming::Band`) holding about a thousand chunks. +- Streaming treats the band like a player's area: it generates its chunks and the rings around them that + decoration and light need, and lights its own chunks. Once every chunk of the band's first row is lit + and post-processed (`LevelChunk.postProcessGeneration`, which vanilla runs before a chunk is FULL), the + band moves down a row; the rows that fall out of its reach unload and are saved like any chunk the + players leave, so memory holds only the rows in flight. +- The chunks a band reaches are ranked for decoration row by row as they come within its reach + (`Streaming::set_band`). Decoration is order dependent where neighbours' writes overlap + (`DecorationOrder`), and this makes a task decorate in the same order however its jobs are timed and + shared among the workers: the same seed gives the same chunks. +- Between server ticks the server waits for the workers' results and hands out the next jobs at once + (`Streaming::wait`, `pump_pregen`), instead of once a tick: a chunk passes through five jobs + (generate, decorate, finish, light, save), each needing its neighbours' earlier ones. + +The chunks of the band's outer ring are finished (FULL) but not lit, as at the edge of what a player has +loaded; they light when their neighbours load later. From 35254c4f0230580e5293146a5203022a3c54d027 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 14:04:28 +0100 Subject: [PATCH 08/43] Pregen: keep an empty dedicated server from pausing while it runs pause-when-empty-seconds paused a server with nobody online after a minute, and a paused server skips its tick: post-processing stopped, so the band waited forever on a row of lit chunks. A running /pregen now counts as activity; the countdown starts once it is done. --- crates/horizon-client/src/game/dedicated.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 9cc892fe0..edea0e800 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -667,7 +667,9 @@ impl Game<'_> { self.poll_server_control(&mut state); let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len()); if pause_after > 0 { - if players == 0 { + // A `/pregen` task keeps the server busy as a player would: + // paused, nothing would post-process its chunks. + if players == 0 && self.pregen_level().is_none() { state.empty_ticks += 1; } else { state.empty_ticks = 0; From 4cd1504513ab7c5f9c4bd326fa1e4913adb3147d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 14:04:28 +0100 Subject: [PATCH 09/43] Pregen: report what a stalled band waits for, and requeue lost light When the band hasn't moved for 30 seconds the task logs how many chunks of its first row are not loaded, being lit, unlit with no light job or not post-processed, with the streaming stage counts, and queues light again for unlit chunks whose neighbours are all loaded. --- .../src/game/commands/pregen.rs | 28 +++++++++++++++++-- crates/horizon-client/src/pregen.rs | 11 ++++++++ crates/horizon-client/src/streaming.rs | 21 ++++++++++++++ 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/commands/pregen.rs b/crates/horizon-client/src/game/commands/pregen.rs index d61ba63ac..d497e2734 100644 --- a/crates/horizon-client/src/game/commands/pregen.rs +++ b/crates/horizon-client/src/game/commands/pregen.rs @@ -14,6 +14,8 @@ use std::time::{Duration, Instant}; /// How often the progress is reported. const REPORT_EVERY: Duration = Duration::from_secs(5); +/// How long the band may stay put before the task looks for what holds it. +const STALL: Duration = Duration::from_secs(30); pub(in crate::game) struct PregenTask { pregen: Pregen, @@ -23,6 +25,8 @@ pub(in crate::game) struct PregenTask { ran: Duration, resumed: Instant, reported: Instant, + /// When the band last moved, to notice a task that stopped advancing. + moved: Instant, /// The player who started it, told the progress too (a guest's connection). owner: Option, } @@ -113,6 +117,7 @@ impl Game<'_> { ran: Duration::ZERO, resumed: now, reported: now, + moved: now, owner: self.lan_acting, }); Ok(total as i32) @@ -181,13 +186,32 @@ impl Game<'_> { // (`postprocess_chunks`, on the tick), as vanilla's are by the time // they are FULL: then they may unload and be saved. let (streaming, chunks) = (&mut self.streaming, &self.world.chunks); - task.pregen.advance(|x, z| { + if task.pregen.advance(|x, z| { streaming.is_lit(x, z) && chunks .get(&(x, z)) .is_some_and(|c| c.postprocess.is_empty()) - }); + }) { + task.moved = Instant::now(); + } streaming.set_band(task.pregen.band()); + if task.moved.elapsed() >= STALL { + // Nothing advanced for a while: say what the first row waits + // for, and queue light again for chunks that lost their job. + task.moved = Instant::now(); + let row = task.pregen.first_row(); + let waiting = row + .iter() + .filter(|k| chunks.get(k).is_some_and(|c| !c.postprocess.is_empty())) + .count(); + let [missing, lighting, unlit] = streaming.unstick_light(&mut self.world, &row); + log::warn!( + "Horizon: pregeneration waits on row {:?}: {missing} not loaded, {lighting} being lit, \ + {unlit} unlit with no light job (queued again), {waiting} not post-processed; {:?}", + row.first(), + streaming.stages() + ); + } let finished = task.pregen.finished(); if finished || task.reported.elapsed() >= REPORT_EVERY { task.reported = Instant::now(); diff --git a/crates/horizon-client/src/pregen.rs b/crates/horizon-client/src/pregen.rs index f31a6d712..e714bcda2 100644 --- a/crates/horizon-client/src/pregen.rs +++ b/crates/horizon-client/src/pregen.rs @@ -105,6 +105,17 @@ impl Pregen { moved } + /// The chunks of the band's first row, which it waits for. + pub fn first_row(&self) -> Vec<(i32, i32)> { + let Some(&(x0, x1)) = self.strips.get(self.strip) else { + return Vec::new(); + }; + (x0..=x1) + .filter(|&x| self.contains(x, self.row)) + .map(|x| (x, self.row)) + .collect() + } + pub fn finished(&self) -> bool { self.strip >= self.strips.len() } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 51c4eaea4..c9e858aea 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -1406,6 +1406,27 @@ impl Streaming { } self.band_ranked = Some((x0, x1, end.max(first - 1) + 1)); } + /// What holds up the columns `keys`, for a task that stopped advancing: + /// how many are not loaded, loaded but unlit with a light job in flight, + /// and unlit with none (those whose neighbours are all loaded are queued + /// for light again). + pub fn unstick_light(&mut self, world: &mut World, keys: &[(i32, i32)]) -> [usize; 3] { + let mut counts = [0; 3]; + for &key in keys { + if !world.chunks.contains_key(&key) { + counts[0] += 1; + } else if self.lit.contains(&key) { + } else if self.lighting.contains_key(&key) { + counts[1] += 1; + } else { + counts[2] += 1; + if Self::region(world, key.0, key.1).is_some() { + world.dirty_light.insert(key); + } + } + } + counts + } /// Wait up to `timeout` for a worker to finish a job; the next `update` /// takes it. A server pumps generation with this between its ticks. pub fn wait(&mut self, timeout: std::time::Duration) { From 749a2dc9bd5d0c0367701c59b814141e24b65b19 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:30:43 +0100 Subject: [PATCH 10/43] Global level events reach a server's players; explosions play their packet's sound ServerLevel.globalLevelEvent (an end portal opening, 1038; the dragon's death roar, 1028) went to the Game's own audio without a position, which is never forwarded: on the server thread, LAN and dedicated servers nobody heard them. They now go to every guest as a global LevelEvent, which a client plays two blocks from its camera towards the event (LevelEventHandler.globalLevelEvent). ClientPacketListener.handleExplosion plays the packet's explosionSound; the client always played entity.generic.explode (a vanilla server's wind charge sounded like TNT). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 3 ++ crates/horizon-client/src/game/dragon.rs | 7 ++-- crates/horizon-client/src/game/end.rs | 7 ++-- crates/horizon-client/src/game/lan.rs | 3 ++ .../horizon-client/src/game/lan_particles.rs | 12 +++---- .../src/game/level_particles.rs | 33 +++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 30 +++++++++++------ crates/horizon-client/src/lan/containers.rs | 11 +++++++ 8 files changed, 84 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..afd8181cc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1544,6 +1544,8 @@ struct Game<'a> { /// position) for the guests. lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, + /// Global level events for every guest (`ServerLevel.globalLevelEvent`). + lan_global_events: Vec<(i32, [i32; 3], i32)>, /// `ContainerOpenersCounter`: how many players (the host and the guests) /// have each chest open. lid_openers: HashMap<(i32, i32, i32), i32>, @@ -11990,6 +11992,7 @@ impl<'a> Game<'a> { lan_events: Vec::new(), lan_block_events: Vec::new(), lan_entity_events: Vec::new(), + lan_global_events: Vec::new(), lid_openers: HashMap::new(), lan_acting: None, guest_packets: Vec::new(), diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 54b260c67..fb555c2d8 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1963,9 +1963,10 @@ impl Game<'_> { self.spawn_orbs([p.x, p.y, p.z], (xp as f32 * 0.08) as u32); } if t == 1 { - // Level event 1028: the death roar, heard everywhere. - self.audio - .play("minecraft:entity.ender_dragon.death", None, 5.0, 1.0); + // EnderDragon.tickDeath: global level event 1028, the death + // roar, heard everywhere. + let at = [p.x, p.y, p.z].map(|v| v.floor() as i32); + self.global_level_event(1028, at, 0); } if let Some(d) = self.dragon.as_mut() { d.position.y += 0.1; diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 599158e3e..d3fb79172 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -311,9 +311,10 @@ impl Game<'_> { )?; } } - // Global LevelEvent 1038: END_PORTAL_SPAWN. - self.audio - .play("minecraft:block.end_portal.spawn", None, 1.0, 1.0); + // EnderEyeItem.useOn: global level event 1038 (END_PORTAL_SPAWN), + // heard by every player (vanilla places it at the frame's corner + // + (1, 0, 1); only its direction matters). + self.global_level_event(1038, c, 0); } Ok(true) } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8460f54e6..442c38a66 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1150,6 +1150,9 @@ impl Game<'_> { for (id, event, at) in std::mem::take(&mut self.lan_entity_events) { host.hub.entity_event(id, event, at); } + for (kind, pos, data) in std::mem::take(&mut self.lan_global_events) { + host.hub.global_level_event(kind, pos, data); + } self.lan_broadcast_effects(host); if host.hub.guests.is_empty() { host.mob_state.clear(); diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 1efb4ac58..0e35392bf 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -161,12 +161,12 @@ impl Game<'_> { + (self.particles.random().next_float() - self.particles.random().next_float()) * 0.2) * 0.7; - self.audio.play( - "minecraft:entity.generic.explode", - Some(p.center), - 4.0, - pitch, - ); + // The packet's explosionSound: a wind charge's burst, a bed's + // or anchor's blast, a modded sound. + let sound = self + .remote_sound_name(&p.sound) + .unwrap_or_else(|| "minecraft:entity.generic.explode".to_owned()); + self.audio.play(&sound, Some(p.center), 4.0, pitch); } if let Some(options) = self.received_particle(&p.particle, p.center) { self.particles.add(&options, p.center, [1.0, 0.0, 0.0]); diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index d239c69d0..f12aedc5b 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -101,6 +101,39 @@ impl Game<'_> { } } } + /// `ServerLevel.globalLevelEvent`: heard by every player on the server + /// (an end portal opening, the dragon's death roar): here, and sent to + /// every guest whatever their dimension. + pub(super) fn global_level_event(&mut self, id: i32, pos: [i32; 3], data: i32) { + self.global_level_event_sound(id, pos); + if self.audio.capture.is_some() { + self.lan_global_events.push((id, pos, data)); + } + } + /// `LevelEventHandler.globalLevelEvent`: the sound two blocks from the + /// camera towards the event, so it is heard from anywhere. + pub(super) fn global_level_event_sound(&mut self, id: i32, pos: [i32; 3]) { + let (sound, volume) = match id { + 1023 => ("minecraft:entity.wither.spawn", 1.0), + 1028 => ("minecraft:entity.ender_dragon.death", 5.0), + 1038 => ("minecraft:block.end_portal.spawn", 1.0), + _ => return, + }; + let at = self.eye_position().map(|eye| { + let d = [ + f64::from(pos[0]) + 0.5 - eye[0], + f64::from(pos[1]) + 0.5 - eye[1], + f64::from(pos[2]) + 0.5 - eye[2], + ]; + let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + if length < 1.0e-4 { + return eye; + } + [0, 1, 2].map(|k| eye[k] + d[k] / length * 2.0) + }); + // Each guest plays it from the global packet. + self.audio.play_unshared(sound, at, volume, 1.0); + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 044e43835..a80f0087a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -255,6 +255,22 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo } impl Game<'_> { + /// A `Holder` off the wire: an inline event's location, or + /// the name of a registered one. + pub(super) fn remote_sound_name( + &self, + sound: &(i32, Option<(String, Option)>), + ) -> Option { + match &sound.1 { + Some((location, _)) => Some(location.clone()), + None => self.remote.as_ref().and_then(|r| { + r.builtin + .get("minecraft:sound_event")? + .name(sound.0) + .map(str::to_owned) + }), + } + } /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { if self.defer_world_entry(super::PendingWorldEntry::Server { @@ -1814,20 +1830,14 @@ impl Game<'_> { // ClientLevel.levelEvent: LevelEventHandler, as this client's own // level plays them (particles and sounds: a spawner's burst, bone // meal, waxing, a block broken by someone else). + // ClientPacketListener.handleLevelEvent: a global one is heard + // from anywhere (ClientLevel.globalLevelEvent). + C::LevelEvent(p) if p.global => self.global_level_event_sound(p.kind, p.pos), C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data), C::LevelParticles(p) => self.remote_level_particles(&p), C::Explode(p) => self.remote_explode(&p), C::Sound(p) => { - let name = match &p.sound.1 { - Some((location, _)) => Some(location.clone()), - None => self.remote.as_ref().and_then(|r| { - r.builtin - .get("minecraft:sound_event")? - .name(p.sound.0) - .map(str::to_owned) - }), - }; - if let Some(name) = name { + if let Some(name) = self.remote_sound_name(&p.sound) { let at = [ f64::from(p.x) / 8.0, f64::from(p.y) / 8.0, diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index d43cb5c27..f34d5ff58 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -78,6 +78,17 @@ impl Hub { ); } + /// `ServerLevel.globalLevelEvent`: the packet with its global flag, for + /// every player on the server (`PlayerList.broadcastAll`). + pub fn global_level_event(&self, kind: i32, pos: [i32; 3], data: i32) { + self.broadcast(&C::LevelEvent(play::LevelEvent { + kind, + pos, + data, + global: true, + })); + } + /// ClientboundBlockEventPacket (`PlayerList.broadcast` within 64 blocks). pub fn block_event(&self, pos: [i32; 3], b0: i32, b1: i32, state: u32) { let block = self From c5a640dd56c0ac7607fc056934ef7471a6eb60a6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:59:56 +0100 Subject: [PATCH 11/43] Endermen, endermites, blazes, eyes of ender, dried ghasts and end portals make their ambient effects The client-side branches vanilla runs on its own level: Enderman and Endermite aiStep (two portal particles a tick), Blaze aiStep (two large smoke particles, the burn sound one tick in 24), EyeOfEnder.tick (a portal particle behind it, four bubbles in water), and the DriedGhastBlock and EndPortalBlock animateTick. They run on the window's game in-frame and as a server's client, never on a server. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/animate_tick.rs | 50 +++++++++++++++++ crates/horizon-client/src/game.rs | 2 + .../horizon-client/src/game/client_ambient.rs | 37 +++++++++++++ crates/horizon-client/src/game/end.rs | 36 +++++++++++- crates/horizon-client/src/game/remote.rs | 1 + crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/ambient.rs | 55 +++++++++++++++++++ 7 files changed, 181 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/src/game/client_ambient.rs create mode 100644 crates/horizon-client/src/mobs/ambient.rs diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index ce34df510..48e8f16f4 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -63,6 +63,10 @@ enum Animate { SculkSensor, /// Potent sulfur that is not dry. PotentSulfur, + DriedGhast { + waterlogged: bool, + }, + EndPortal, } fn step(facing: &str) -> [i32; 3] { match facing { @@ -137,6 +141,10 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { drag: prop("drag").as_deref() == Some("true"), }, "fire" | "soul_fire" => Animate::Fire, + "dried_ghast" => Animate::DriedGhast { + waterlogged: prop("waterlogged").as_deref() == Some("true"), + }, + "end_portal" => Animate::EndPortal, "sculk_sensor" | "calibrated_sculk_sensor" if prop("sculk_sensor_phase").as_deref() == Some("active") => { @@ -180,6 +188,8 @@ pub struct AnimateTables { impermeable: Vec, power_provider: Vec, power_transmitter: Vec, + /// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil). + dried_ghast_sounds: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). ambient: Vec>, } @@ -237,6 +247,7 @@ impl AnimateTables { impermeable: by_state("minecraft:impermeable"), power_provider: by_state("minecraft:enchantment_power_provider"), power_transmitter: by_state("minecraft:enchantment_power_transmitter"), + dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"), ambient, }) } @@ -869,6 +880,45 @@ fn block_animate_tick( ]; add(engine, T::Smoke, p, [0.0; 3]); } + Animate::DriedGhast { waterlogged } => { + // DriedGhastBlock.animateTick. + let c = [fx + 0.5, fy + 0.5, fz + 0.5]; + if waterlogged { + if next_int(engine.random(), 40) == 0 { + let name = "minecraft:block.dried_ghast.ambient_water"; + sound(engine, name, c, 1.0, 1.0); + } + let r = engine.random(); + if next_int(r, 6) == 0 { + let x = c[0] + f64::from((r.next_float() * 2.0 - 1.0) / 3.0); + let y = c[1] + 0.4; + let z = c[2] + f64::from((r.next_float() * 2.0 - 1.0) / 3.0); + let v = [0.0, f64::from(r.next_float()), 0.0]; + add(engine, T::HappyVillager, [x, y, z], v); + } + } else { + let below = ctx.state([pos[0], pos[1] - 1, pos[2]]); + let triggers = || { + tables + .dried_ghast_sounds + .get(below.0 as usize) + .copied() + .unwrap_or(false) + }; + if next_int(engine.random(), 40) == 0 && triggers() { + sound(engine, "minecraft:block.dried_ghast.ambient", c, 1.0, 1.0); + } + if next_int(engine.random(), 6) == 0 { + add(engine, T::WhiteSmoke, c, [0.0, 0.02, 0.0]); + } + } + } + Animate::EndPortal => { + // EndPortalBlock.animateTick: one smoke particle above the surface. + let r = engine.random(); + let p = [fx + r.next_double(), fy + 0.8, fz + r.next_double()]; + add(engine, T::Smoke, p, [0.0; 3]); + } Animate::EnderChest => { for _ in 0..3 { let r = engine.random(); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..46621082e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -20,6 +20,7 @@ mod bossbars; mod breezes; mod cartography; mod chat; +mod client_ambient; mod clipboard; mod combat; mod command_blocks; @@ -4447,6 +4448,7 @@ impl Game<'_> { self.tick_block_entity_anims() }); horizon_client::spans::time("tick_particles", || self.tick_particles()); + self.tick_client_ambient(); } // ServerBossEvent broadcasts, after this level's entities have ticked. self.publish_boss_bars(); diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs new file mode 100644 index 000000000..a10c6da49 --- /dev/null +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -0,0 +1,37 @@ +//! The window's own ambient effects of entities, which a client makes for +//! itself (`level().isClientSide()` branches): endermen's and endermites' +//! portal particles, blazes' smoke and burn, eyes of ender's trail. They run +//! on the game that has the window, in-frame or following a server, never on +//! a server: nothing of them goes over the network. +use super::Game; +use horizon_client::mobs::{MobEvent, ambient}; +use horizon_client::particles::{ParticleOptions, ParticleType}; + +impl Game<'_> { + pub(super) fn tick_client_ambient(&mut self) { + if self.serving.is_some() || self.options.dedicated.is_some() { + return; + } + let mut events = Vec::new(); + for m in self.mobs.iter_mut().filter(|m| !m.removed) { + ambient::client_ai_step(m, &mut events); + } + for event in events { + match event { + MobEvent::ParticleAt { kind, at, velocity } => { + if let Some(ty) = ParticleType::from_name(kind) { + self.particles + .add(&ParticleOptions::simple(ty), at, velocity); + } + } + // Each guest of a LAN host makes its own. + MobEvent::LocalSound(name, at, volume, pitch) => { + self.audio + .play_unshared(&format!("minecraft:{name}"), Some(at), volume, pitch) + } + _ => {} + } + } + self.eye_particles(); + } +} diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 599158e3e..655971a5c 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -4,7 +4,12 @@ //! inactive until the dragon dies. use super::{Dim, Game}; use horizon_client::{ - Result, environment::Environment, items::ItemStack, mesher::Vertex, motion::PlayerMotion, + Result, + environment::Environment, + items::ItemStack, + mesher::Vertex, + motion::PlayerMotion, + particles::{ParticleOptions, ParticleType}, vanillagen::VanillaTerrain, }; use horizon_core::{ @@ -1122,6 +1127,35 @@ impl Game<'_> { self.end.eyes = eyes; } + /// `EyeOfEnder.tick` on a client: behind each eye (a quarter of its last + /// move back), four bubbles in water, else a portal particle. + pub(super) fn eye_particles(&mut self) { + for i in 0..self.end.eyes.len() { + let e = &self.end.eyes[i]; + let movement = (e.position - e.previous).to_array(); + let origin = (e.position - (e.position - e.previous) * 0.25).to_array(); + let block = origin.map(|v| v.floor() as i32); + let water = self + .res + .facts() + .get(self.world.block(block[0], block[1], block[2])) + .fluid + == horizon_client::blocks::Fluid::Water; + if water { + let bubble = ParticleOptions::simple(ParticleType::Bubble); + for _ in 0..4 { + self.particles.add(&bubble, origin, movement); + } + } else { + let r = self.particles.random(); + let x = origin[0] + r.next_double() * 0.6 - 0.3; + let z = origin[2] + r.next_double() * 0.6 - 0.3; + let portal = ParticleOptions::simple(ParticleType::Portal); + self.particles + .add(&portal, [x, origin[1] - 0.5, z], movement); + } + } + } /// ThrownItemRenderer: the ender eye item facing the camera. fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec) { let Some(r) = self.gui.atlas.sprites.get("item/ender_eye").copied() else { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 044e43835..711753869 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3187,6 +3187,7 @@ impl Game<'_> { self.tick_block_entity_anims(); self.tick_hand(); self.tick_particles(); + self.tick_client_ambient(); self.tick_client_effects(); // Player.tick's sleep counter (the darkening and the wake-up fade). self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 4e3879fe5..6dee6a829 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -7,6 +7,7 @@ //! behaviour, models, animations and sounds. pub mod ai; pub mod allay; +pub mod ambient; pub mod anim; pub mod animal_brain; pub mod aquatic; diff --git a/crates/horizon-client/src/mobs/ambient.rs b/crates/horizon-client/src/mobs/ambient.rs new file mode 100644 index 000000000..cb4146e08 --- /dev/null +++ b/crates/horizon-client/src/mobs/ambient.rs @@ -0,0 +1,55 @@ +//! What a client's copy of a mob makes on its own, in the +//! `level().isClientSide()` branches of `aiStep`: nothing of it reaches the +//! server or goes over the network, so the window's game runs it, whether it +//! simulates the world (in-frame) or follows a server. +use super::{Mob, MobEvent, Species}; +use horizon_core::random::RandomSource; + +/// `Enderman.aiStep`, `Endermite.aiStep` and `Blaze.aiStep` on a client: +/// two portal particles a tick around endermen and endermites; two large +/// smoke particles a tick around blazes and, one tick in 24, their burn. +pub fn client_ai_step(m: &mut Mob, out: &mut Vec) { + let species = m.species(); + if !matches!( + species, + Species::Enderman | Species::Endermite | Species::Blaze + ) { + return; + } + let (w, h) = (f64::from(m.width()), f64::from(m.height())); + let p = m.position; + if species == Species::Blaze && m.random.next_int_bound(24).unwrap_or(1) == 0 && !m.silent { + let volume = 1.0 + m.random.next_float(); + let pitch = m.random.next_float() * 0.7 + 0.3; + out.push(MobEvent::LocalSound( + "entity.blaze.burn", + [p.x + 0.5, p.y + 0.5, p.z + 0.5], + volume, + pitch, + )); + } + for _ in 0..2 { + // Entity.getRandomX(0.5), getRandomY(), getRandomZ(0.5). + let r = &mut m.random; + let x = p.x + w * (2.0 * r.next_double() - 1.0) * 0.5; + let y = p.y + h * r.next_double(); + let z = p.z + w * (2.0 * r.next_double() - 1.0) * 0.5; + let (kind, at, velocity) = if species == Species::Blaze { + ("large_smoke", [x, y, z], [0.0; 3]) + } else { + // The enderman's are a quarter block lower. + let y = if species == Species::Enderman { + y - 0.25 + } else { + y + }; + let velocity = [ + (r.next_double() - 0.5) * 2.0, + -r.next_double(), + (r.next_double() - 0.5) * 2.0, + ]; + ("portal", [x, y, z], velocity) + }; + out.push(MobEvent::ParticleAt { kind, at, velocity }); + } +} From 1a39af6b623f3f12fc15ba609a016c2f4e4ea464 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:36:22 +0100 Subject: [PATCH 12/43] /pregen: plan any radius at once, and skip a strip's rows outside the circle Pregen::new counted the area chunk by chunk and split the strips with an i32 product: /pregen start 30000000 overflowed, then hung the server thread for hours. Rows are now counted from the circle's half-width, the strip edges in i64, and each strip starts and ends at the rows the circle reaches, so a band never walks empty corner rows. Unit tests check that every chunk of squares and circles is swept once and that the largest radius plans at once. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/pregen.rs | 99 ++++++++++++++++++++++++----- 1 file changed, 84 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/pregen.rs b/crates/horizon-client/src/pregen.rs index e714bcda2..01215928a 100644 --- a/crates/horizon-client/src/pregen.rs +++ b/crates/horizon-client/src/pregen.rs @@ -39,48 +39,69 @@ impl Pregen { let radius = radius.max(0); let (x0, width) = (center.0 - radius, 2 * radius + 1); let count = (width + STRIP_WIDTH - 1) / STRIP_WIDTH; - let strips = (0..count) - .map(|i| (x0 + width * i / count, x0 + width * (i + 1) / count - 1)) - .collect(); + // The columns `i * width / count` on, in i64: the product overflows + // for a radius of a few hundred thousand chunks. + let edge = |i: i32| x0 + (i64::from(width) * i64::from(i) / i64::from(count)) as i32; + let strips = (0..count).map(|i| (edge(i), edge(i + 1) - 1)).collect(); let mut pregen = Self { center, radius, shape, strips, strip: 0, - row: center.1 - radius, + row: 0, done: 0, total: 0, }; pregen.total = (center.1 - radius..=center.1 + radius) .map(|z| pregen.row_chunks(x0, x0 + width - 1, z)) .sum(); + pregen.row = pregen.rows().map_or(0, |r| r.0); pregen } - fn contains(&self, x: i32, z: i32) -> bool { + /// How far from the centre column the area reaches at `d` chunks from + /// the centre row (or, the same, from the centre column), if it does. + fn half_width(&self, d: i32) -> Option { + let (r, d) = (i64::from(self.radius), i64::from(d)); match self.shape { - Shape::Square => true, - Shape::Circle => { - let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1)); - dx * dx + dz * dz <= i64::from(self.radius) * i64::from(self.radius) - } + Shape::Square => (d.abs() <= r).then_some(self.radius), + Shape::Circle => (d * d <= r * r).then(|| (r * r - d * d).isqrt() as i32), } } + fn contains(&self, x: i32, z: i32) -> bool { + self.half_width(z - self.center.1) + .is_some_and(|h| (x - self.center.0).abs() <= h) + } + + /// The area's chunks in columns `x0..=x1` of row `z`. fn row_chunks(&self, x0: i32, x1: i32, z: i32) -> u64 { - (x0..=x1).filter(|&x| self.contains(x, z)).count() as u64 + self.half_width(z - self.center.1).map_or(0, |h| { + let (lo, hi) = (x0.max(self.center.0 - h), x1.min(self.center.0 + h)); + (i64::from(hi) - i64::from(lo) + 1).max(0) as u64 + }) + } + + /// The first and last rows of the current strip that hold chunks of the + /// area. + fn rows(&self) -> Option<(i32, i32)> { + let &(x0, x1) = self.strips.get(self.strip)?; + let nearest = (x0 - self.center.0).max(self.center.0 - x1).max(0); + let h = self.half_width(nearest)?; + Some((self.center.1 - h, self.center.1 + h)) } /// The band streaming should hold now; none once every strip is done. pub fn band(&self) -> Option { let &(x0, x1) = self.strips.get(self.strip)?; + let (_, last) = self.rows()?; let rows = (BAND_CHUNKS + (x1 - x0)) / (x1 - x0 + 1); Some(Band { x0, x1, z0: self.row, - z1: (self.row + rows - 1).min(self.center.1 + self.radius), + z1: (self.row + rows - 1).min(last), circle: (self.shape == Shape::Circle).then_some((self.center, self.radius)), }) } @@ -89,16 +110,16 @@ impl Pregen { /// Returns whether the band moved. pub fn advance(&mut self, lit: impl Fn(i32, i32) -> bool) -> bool { let mut moved = false; - while let Some(&(x0, x1)) = self.strips.get(self.strip) { + while let (Some(&(x0, x1)), Some((_, last))) = (self.strips.get(self.strip), self.rows()) { let z = self.row; if !(x0..=x1).all(|x| !self.contains(x, z) || lit(x, z)) { break; } self.done += self.row_chunks(x0, x1, z); self.row += 1; - if self.row > self.center.1 + self.radius { + if self.row > last { self.strip += 1; - self.row = self.center.1 - self.radius; + self.row = self.rows().map_or(self.row, |r| r.0); } moved = true; } @@ -120,3 +141,51 @@ impl Pregen { self.strip >= self.strips.len() } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sweeps_every_chunk_of_the_area_once() { + for shape in [Shape::Square, Shape::Circle] { + for (center, radius) in [((0, 0), 0), ((3, -7), 5), ((-40, 12), 130), ((0, 0), 300)] { + let mut p = Pregen::new(center, radius, shape); + let r = i64::from(radius); + let area = (-radius..=radius) + .flat_map(|dz| (-radius..=radius).map(move |dx| (dx, dz))) + .filter(|&(dx, dz)| { + shape == Shape::Square + || i64::from(dx).pow(2) + i64::from(dz).pow(2) <= r * r + }) + .count() as u64; + assert_eq!(p.total, area, "{shape:?} {radius}"); + let mut seen = std::collections::HashSet::new(); + while !p.finished() { + let band = p.band().unwrap(); + assert!(band.z0 <= band.z1); + let row = p.first_row(); + for &(x, z) in &row { + assert!(seen.insert((x, z)), "{x} {z} twice"); + } + assert!( + p.advance(|x, z| z == band.z0 && row.contains(&(x, z))) || row.is_empty() + ); + } + assert_eq!( + (p.done, seen.len() as u64), + (area, area), + "{shape:?} {radius}" + ); + } + } + } + + #[test] + fn a_huge_area_is_planned_at_once() { + let started = std::time::Instant::now(); + let p = Pregen::new((0, 0), 30_000_000 >> 4, Shape::Circle); + assert!(p.total > 11_000_000_000_000); + assert!(started.elapsed() < std::time::Duration::from_secs(5)); + } +} From aa2f60b7bd78179f1e7723c866212fd4e1ec548e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:43:03 +0100 Subject: [PATCH 13/43] Copper golem statues turn to their next pose when right-clicked CopperGolemStatueBlock.useItemOn: anything but an axe, an empty hand too, cycles copper_golem_pose with its sound and block_change game event; honeycomb on a weathering statue passes on to waxing. Axe scraping, unwaxing and stripping and honeycomb waxing now count the item as used, and waxing sends its block_change game event, as vanilla's useOn does. The use_item_on harness gains statue cases. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 10 ++++++ crates/horizon-world/src/level/interact.rs | 31 ++++++++++++++++++ tools/test_use_item_on_parity.py | 37 ++++++++++++++++++++-- 3 files changed, 76 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7fcb3be89..ee6df4c38 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8332,6 +8332,8 @@ impl Game<'_> { 1.0, 1.0, ); + // ItemStack.useOn: a use that acted counts as one of the item. + self.stats.add("used", &stack.item, 1); self.damage_held(damage); self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), Some(new)); Ok(true) @@ -8536,6 +8538,14 @@ impl Game<'_> { 1.0, 1.0, ); + // HoneycombItem.useOn's game event, and ItemStack.useOn's used statistic. + self.post_block_game_event( + "minecraft:block_change", + hit.pos, + self.sculk_actor(), + Some(state), + ); + self.stats.add("used", &stack.item, 1); if !self.creative { self.consume_held(); } diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index b8251ba46..7b2195c34 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -592,6 +592,37 @@ impl Behaviours { { return InteractionResult::Pass; } + if self.data(state).chain.contains(&Class::CopperGolemStatue) { + return self.turn_statue(level, ticks, pos, state, item); + } self.use_without_item(level, ticks, pos, face, hit, player) } + + /// `CopperGolemStatueBlock.useItemOn` (and its weathering subclass's): anything but an axe + /// (`#minecraft:axes`, every one named `*_axe`), even an empty hand, turns the statue to its + /// next pose; honeycomb waxes a statue that still weathers instead. + fn turn_statue( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + state: BlockStateId, + item: Option<&str>, + ) -> InteractionResult { + let item = item.unwrap_or("minecraft:air"); + let waxed = self.table.name(state).starts_with("minecraft:waxed_"); + if item.ends_with("_axe") || (item == "minecraft:honeycomb" && !waxed) { + return InteractionResult::Pass; + } + let mut sim = self.sim(level, ticks); + sim.sound( + pos, + &"minecraft:entity.copper_golem_become_statue".into(), + 1.0, + 1.0, + ); + sim.set_block_and_update(pos, self.table.cycle(state, self.props.copper_golem_pose)); + sim.game_event(pos, "minecraft:block_change"); + InteractionResult::Success + } } diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index 89b463116..eabdd04eb 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -2,8 +2,9 @@ """Compare a player's right click on a block with vanilla's, for items that are both food and blocks (sweet and glow berries, carrots, potatoes), for sweet berry bushes, for spawn eggs used on a monster spawner, for shears carving -pumpkins, for blocks placed where mobs and armor stands stand, for respawn -anchors and for beds in the Nether and the End. +pumpkins, for copper golem statues turned to their next pose, for blocks +placed where mobs and armor stands stand, for respawn anchors and for beds in +the Nether and the End. Every case has a block at the origin, something above it, and a player three blocks south, survival or creative, hungry or full, sneaking or not, who @@ -228,6 +229,32 @@ def pumpkin_case(rng, states, case): case['cells'] = cells +STATUES = [f'{wax}{age}copper_golem_statue' for wax in ('', 'waxed_') + for age in ('', 'exposed_', 'weathered_', 'oxidized_')] + + +def statue_case(rng, states, case): + """A copper golem statue right-clicked (`CopperGolemStatueBlock.useItemOn`, the weathering + one's): anything but an axe, an empty hand too, turns it to its next pose; honeycomb waxes a + statue that still weathers instead (`HoneycombItem.useOn`), and an axe scrapes or unwaxes it.""" + statue = rng.choice(STATUES) + case['cells'] = [[0, 0, 0, states.any(rng, statue)]] + items = ['-', '-', 'stick', 'honeycomb', 'honeycomb', 'stone', 'copper_ingot', 'diamond_pickaxe', + 'copper_golem_statue'] + if statue != 'copper_golem_statue': + # An axe scrapes or unwaxes the others; on the unaffected one it brings the golem back + # (`CopperGolemStatueBlockEntity.removeStatue`), which Horizon does not do yet. + items.append('iron_axe') + item = rng.choice(items) + use = {'item': '-' if item == '-' else d_plain(item, rng.choice([1, 16])), 'creative': rng.random() < 0.2, + 'sneaking': rng.random() < 0.15, 'food': 20, + 'face': rng.choice(['up', 'up', 'north', 'south', 'west', 'east'])} + if rng.random() < 0.2: + # The item in the off hand, nothing in the main hand. + use.update(offhand=use['item'], item='-') + case['use_item'] = use + + # Entities a block may be placed into (`Entity.blocksBuilding`), and blocks to place. BLOCKERS = ['skeleton', 'zombie', 'pig', 'chicken', 'cow', 'armor_stand', 'slime', 'bat'] PLACED = ['obsidian', 'stone', 'oak_slab', 'oak_fence', 'white_carpet', 'torch', 'glass', 'oak_trapdoor', 'snow'] @@ -290,6 +317,12 @@ def cases(facts, count, seed): case['mode'] = 'dispense' yield case continue + if rng.random() < 0.08: + statue_case(rng, states, case) + case['items'] = [] + case['mode'] = 'dispense' + yield case + continue if rng.random() < 0.12: pumpkin_case(rng, states, case) case['items'] = [] From 481e75bc33bea120cad48a40294fdaf3df2b19aa Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:16:36 +0000 Subject: [PATCH 14/43] Clear off-hand items in vanilla inventory slot order Co-Authored-By: OpenAI Codex GPT-6.1 --- crates/horizon-client/src/game/commands.rs | 9 ++++++--- tools/command_exec_corpus.py | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 19a16e261..1f24c8a4f 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2499,12 +2499,14 @@ impl Game<'_> { }; let max = Self::int(ctx, "maxCount").unwrap_or(-1); let counting = max == 0; - // Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried. + // Inventory slots 0..40: main, armor feet to head, off hand; + // then clearOrCountMatchingItems visits the crafting grid and carried stack. let mut removed = 0i32; let mut budget = if max < 0 { i32::MAX } else { max }; let all = |g: &Self| -> Vec> { let mut v: Vec> = g.inventory.clone(); - v.extend(g.armor.iter().cloned()); + v.extend(g.armor.iter().rev().cloned()); + v.push(g.offhand.clone()); v.extend(g.craft_grid.iter().cloned()); v.push(g.carried.clone()); v @@ -2518,7 +2520,8 @@ impl Game<'_> { .collect(); let mut slots: Vec<&mut Option> = Vec::new(); slots.extend(self.inventory.iter_mut()); - slots.extend(self.armor.iter_mut()); + slots.extend(self.armor.iter_mut().rev()); + slots.push(&mut self.offhand); slots.extend(self.craft_grid.iter_mut()); slots.push(&mut self.carried); for (slot, matches) in slots.into_iter().zip(matching) { diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 0e376e260..4b24ca80f 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -182,6 +182,23 @@ def player_state(): cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:1}'), cmd('/clear @s'), cmd('/clear @s'), + # Inventory.clearOrCountMatchingItems visits the off hand as well as + # the main inventory, and consumes limited clears in inventory-slot order. + cmd('/item replace entity @s weapon.offhand with minecraft:shield'), + cmd('/clear @s minecraft:shield 0'), + cmd('/clear @s minecraft:shield 1'), + cmd('/clear @s minecraft:shield 0'), + cmd('/item replace entity @s weapon.offhand with minecraft:stone 5'), + cmd('/clear @s minecraft:stone 2'), + cmd('/clear @s minecraft:stone 0'), + cmd('/clear @s'), + cmd('/clear @s minecraft:stone 0'), + cmd('/item replace entity @s armor.head with minecraft:iron_helmet'), + cmd('/item replace entity @s armor.feet with minecraft:iron_boots'), + cmd('/clear @s * 1'), + cmd('/clear @s minecraft:iron_boots 0'), + cmd('/clear @s minecraft:iron_helmet 0'), + cmd('/clear @s'), cmd('/attribute @s minecraft:max_health get'), cmd('/attribute @s minecraft:max_health base get'), cmd('/attribute @s minecraft:max_health base set 30'), From 74e3b0adf6937575dd5c5a3d2ea99ed0cb490eec Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 21:10:52 +0100 Subject: [PATCH 15/43] ui: recapture the mouse when a mod's screen vanishes, borrow its widgets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review on #1864: when a mod stops while its screen or settings page is up, draw_mod_screen dropped the player back to Playing without capture(true), leaving the mouse free until the next click into the world. The dead surface now leaves through close_mod_screen, which puts back the screen it covered and holds the mouse on a return to Playing; the same goes for a screen dropped while it was up. mod_ui_view also cloned the title and every widget (up to 64, lists to 512 rows) on each frame, click and scroll. It now borrows the mod's stored widgets — the screen's scrolls live in a disjoint field — and the click finds the picked row first so the &mut ui_select runs after. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game/mods.rs | 87 +++++++++++++------------- 1 file changed, 44 insertions(+), 43 deletions(-) diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 47a3ce07b..d2e9627e6 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -425,30 +425,28 @@ impl Game<'_> { } /// A `ui` screen's title and widgets as the mod last pushed them; None - /// when the surface is gone (the mod stopped or closed it). - fn mod_ui_view(&self) -> Option<(String, Vec)> { - let ms = self.mods.screen.as_ref()?; + /// when the surface is gone (the mod stopped or closed it). Borrows + /// `mods` only, so `self.mods.screen` may stay borrowed for the scrolls. + fn mod_ui_view<'a>(mods: &'a Mods, ms: &ModScreen) -> Option<(&'a str, &'a [UiWidget])> { if ms.settings { - let widgets = self.mods.mods.settings_widgets(ms.owner); + let widgets = mods.settings_widgets(ms.owner); if widgets.is_empty() { return None; } - let name = self - .mods - .mods + let name = mods .entries() .get(ms.owner) .and_then(|e| e.manifest.as_ref()) .map_or("Mod", |m| m.name.as_str()); - Some((name.to_string(), widgets.to_vec())) + Some((name, widgets)) } else { - let s: &UiScreen = self.mods.mods.screen(ms.owner)?; - Some((s.title.clone(), s.widgets.clone())) + let s: &UiScreen = mods.screen(ms.owner)?; + Some((s.title.as_str(), s.widgets.as_slice())) } } /// The layout the mod screen's widgets get at `h`: (widget, top, /// height), the column being `COLUMN` wide down the middle. - fn mod_ui_layout(&self, h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { + fn mod_ui_layout(h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { let mut out = Vec::with_capacity(widgets.len()); let mut y = MOD_UI_TOP; for w in widgets { @@ -513,13 +511,19 @@ impl Game<'_> { /// The mod's screen or settings page: its title over widgets stacked /// down the middle, a Done button, Esc to leave (vanilla's menus). pub(super) fn draw_mod_screen(&mut self, batch: &mut HudBatch) { - if self.mods.screen.is_none() { + let Some(ms) = self.mods.screen.as_mut() else { + // The screen was dropped while it was up: back to the world, + // mouse held again like any return to Playing. self.screen = Screen::Playing; + if self.player.is_some() { + self.capture(true); + } return; - } - let Some((title, widgets)) = self.mod_ui_view() else { - self.mods.screen = None; - self.screen = Screen::Playing; + }; + let Some((title, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else { + // The mod's surface is gone (it stopped or cleared it): leave + // the screen like Done did, without `closed` — the mod ended it. + self.close_mod_screen(false); return; }; // Item icons draw in a second pass: `draw_item` needs `&mut self`, @@ -539,7 +543,7 @@ impl Game<'_> { ); let cx = (batch.width / 2.0).floor(); let x = cx - MOD_UI_COLUMN / 2.0; - let layout = self.mod_ui_layout(batch.height, &widgets); + let layout = Self::mod_ui_layout(batch.height, widgets); let mut list_i = 0usize; for (w, &(wy, wh)) in widgets.iter().zip(&layout) { match w { @@ -580,11 +584,8 @@ impl Game<'_> { ); } UiWidget::List(l) => { - let scroll = { - let ms = self.mods.screen.as_mut().expect("checked"); - ms.scrolls.resize_with(list_i + 1, ui::Scroll::default); - ms.scrolls[list_i] - }; + ms.scrolls.resize_with(list_i + 1, ui::Scroll::default); + let scroll = ms.scrolls[list_i]; list_i += 1; let rows_top = wy + 4.0; let rows_bottom = wy + wh - 4.0; @@ -655,53 +656,53 @@ impl Game<'_> { self.close_mod_screen(true); return; } - let Some((_, widgets)) = self.mod_ui_view() else { + let Some(ms) = self.mods.screen.as_ref() else { return; }; + let Some((_, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else { + return; + }; + let owner = ms.owner; let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0; - let layout = self.mod_ui_layout(h, &widgets); + let layout = Self::mod_ui_layout(h, widgets); let mut list_i = 0usize; + // The `ui_select` call needs `&mut`: find the pick first. + let mut hit = None; for (w, &(wy, wh)) in widgets.iter().zip(&layout) { let UiWidget::List(l) = w else { continue }; - let scroll = self - .mods - .screen - .as_ref() - .and_then(|ms| ms.scrolls.get(list_i).copied()) - .unwrap_or_default(); + let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default(); list_i += 1; let row = ((cursor.1 - (wy + 4.0) + scroll.amount) / 12.0) as i64; if ui::hovered(cursor, x + 1.0, wy + 1.0, MOD_UI_COLUMN - 7.0, wh - 2.0) && row >= 0 && (row as usize) < l.rows.len() { - self.audio.play_button_click(); - self.mods.mods.ui_select( - self.mods.screen.as_ref().map_or(0, |ms| ms.owner), - l.id, - row as u32, - ); - self.show_mod_output(); - return; + hit = Some((l.id, row as u32)); + break; } } + if let Some((id, row)) = hit { + self.audio.play_button_click(); + self.mods.mods.ui_select(owner, id, row); + self.show_mod_output(); + } } /// The wheel over a `list` scrolls it. pub(super) fn mod_screen_scroll(&mut self, delta: f32) { let (w, h) = self.gui_size(); let cursor = self.cursor; - let Some((_, widgets)) = self.mod_ui_view() else { + let Some(ms) = self.mods.screen.as_mut() else { + return; + }; + let Some((_, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else { return; }; let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0; - let layout = self.mod_ui_layout(h, &widgets); + let layout = Self::mod_ui_layout(h, widgets); let mut list_i = 0usize; for (w, &(wy, wh)) in widgets.iter().zip(&layout) { let UiWidget::List(l) = w else { continue }; let over = ui::hovered(cursor, x, wy, MOD_UI_COLUMN, wh); - let Some(ms) = self.mods.screen.as_mut() else { - return; - }; ms.scrolls.resize_with(list_i + 1, ui::Scroll::default); if over { let content = l.rows.len() as f32 * 12.0; From 386912a76d4046a6026e6caa331b5ee5576e217b Mon Sep 17 00:00:00 2001 From: sl4ppleware <66299946+sl4ppleware@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:32:27 +0300 Subject: [PATCH 16/43] Hearts blink again when the server sets health: LocalPlayer.hurtTo's damageCooldownTime --- crates/horizon-client/src/health.rs | 10 ++++++++-- crates/horizon-client/src/motion.rs | 5 +++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index da40f41fc..25c719bfb 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -261,11 +261,17 @@ impl PlayerHealth { self.hurt_animation_time = 10; } /// `LocalPlayer.hurtTo` with `flashOnSetHealth`: a drop below the current - /// health starts the hurt animation. + /// health starts the hurt animation; `damageCooldownTime` (20 on a drop, + /// 10 on a gain) is what lets `Hud.extractPlayerHealth` blink the hearts. pub fn flash_health_change(&mut self, health: f32) { let damage = self.health() - health; - if damage > 0.0 { + if damage <= 0.0 { + if damage < 0.0 { + self.hurt.cooldown = 10; + } + } else { self.hurt.last_hurt = damage; + self.hurt.cooldown = 20; self.animate_hurt(); } } diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index e7809055d..a5e3813b1 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -2934,8 +2934,13 @@ mod tests { if client_side { w.player.health.flash_health_change(20.0); assert_eq!(w.player.health.hurt_animation_time, 0); + assert_eq!(w.player.health.hurt.cooldown, 0); w.player.health.flash_health_change(12.0); assert_eq!(w.player.health.hurt_animation_time, 10); + // LocalPlayer.hurtTo's damageCooldownTime: the HUD's hearts blink. + assert_eq!(w.player.health.hurt.cooldown, 20); + w.player.health.flash_health_change(25.0); + assert_eq!(w.player.health.hurt.cooldown, 10); } } } From 61c44c22efe23f9cbc4ac00ef8c8f20a35b00aa4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:35:12 +0100 Subject: [PATCH 17/43] Mod API: capability render (experimental): HUD shapes and camera shake Mods draw through the game's own renderer, never their own shaders: - WIT `render`: set-hud(shapes) with fill, quad (any four corners), sprite (the game's GUI sprites), item (scaled) and text shapes, up to 1024, kept until replaced; gui-size(); shake(strength, seconds). - Drawn over the HUD after the extras, under chat and screens, hidden with F1 (game/mod_render.rs). Colours are 0xAARRGGBB. - shake turns the view, not the player: jolts fade out squared, add up to 1, at most 3 degrees of yaw and 2 of pitch, scaled by Distortion Effects (screenEffectScale; 0 turns it off). - Experimental: the manifest needs experimental = ["render"]. - No mod drawing, no cost: an empty iterator and an is_empty check. - cargo horizon-mod check reports shakes and HUD shapes. The ui test guest gains /render_hud, /render_clear and /render_shake, with a sandbox test; HudBatch gets fill_quad. - Docs: mods.md, stability.md, the changelog, the regenerated reference. Co-Authored-By: Claude Opus 5.5 --- crates/cargo-horizon-mod/src/check.rs | 9 + crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/mod_render.rs | 176 ++++++++++++++++++ crates/horizon-client/src/game/mods.rs | 15 +- crates/horizon-client/src/hud.rs | 6 + crates/horizon-mod-sdk/src/lib.rs | 2 +- crates/horizon-mod-sdk/wit/horizon.wit | 82 ++++++++ crates/horizon-mods/src/manifest.rs | 11 +- crates/horizon-mods/src/runtime.rs | 81 ++++++++ crates/horizon-mods/tests/sandbox.rs | 38 +++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 71 ++++++- docs/api/mods-reference.md | 94 +++++++++- docs/api/mods.md | 2 + docs/api/stability.md | 1 + docs/mods.md | 5 +- 15 files changed, 582 insertions(+), 14 deletions(-) create mode 100644 crates/horizon-client/src/game/mod_render.rs diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 5d4150ab9..dfb9820a2 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -198,6 +198,8 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { game_time: t, day_time: 1000 + t, }), + // The GUI of a 1280 x 720 window at scale 3. + gui_size: (427.0, 240.0), }); mods.tick(t); for _ in 0..FRAMES_PER_TICK { @@ -217,8 +219,15 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), Output::OpenScreen { .. } => "opened a screen".to_string(), Output::CloseScreen { .. } => "closed its screen".to_string(), + Output::Shake { strength, seconds } => { + format!("shook the camera: {strength:.2} for {seconds:.1} s") + } }); } + let shapes = mods.hud_shapes().count(); + if shapes > 0 { + report.output.push(format!("drew {shapes} HUD shape(s)")); + } match failed(&mods) { Some(reason) => Err(format!("it stopped: {reason}")), None => Ok(()), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index eabbc22b8..31bfe74b6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -96,6 +96,7 @@ mod maps; mod minecarts; mod mob_blocks; mod mob_gear; +mod mod_render; mod mods; mod mount_menu; mod mounts; @@ -4894,6 +4895,7 @@ impl Game<'_> { // Hud: the action bar and titles draw over the hotbar (nextStratum). self.draw_boss_bars(&mut batch); self.draw_extras(&mut batch); + self.draw_mod_shapes(&mut batch); } if show_hud { // Hud.nextContextualInfoState: the jump bar, the experience bar or @@ -9865,6 +9867,7 @@ impl Game<'_> { self.pitch, ), }; + let (view_yaw, view_pitch) = self.shaken_view(view_yaw, view_pitch); self.audio .set_listener([camera.x, camera.y, camera.z], view_yaw, view_pitch); let block = [ diff --git a/crates/horizon-client/src/game/mod_render.rs b/crates/horizon-client/src/game/mod_render.rs new file mode 100644 index 000000000..1c3a20621 --- /dev/null +++ b/crates/horizon-client/src/game/mod_render.rs @@ -0,0 +1,176 @@ +//! Capability `render` (docs/mods.md): the shapes mods keep on the HUD, +//! drawn by the game's own HUD renderer, and their camera shakes. Mods +//! never supply shader code. With no mod drawing, each hook here returns +//! after one check. +use super::Game; +use horizon_client::hud::HudBatch; +#[cfg(feature = "mods")] +use { + horizon_client::{hud::rgba, items::ItemStack, text::Text}, + horizon_mods::Shape, + std::time::Instant, +}; + +/// The camera's jolts from `render.shake`, while any is fading. +#[cfg(feature = "mods")] +#[derive(Default)] +pub(super) struct Shake { + jolts: Vec, +} + +#[cfg(feature = "mods")] +struct Jolt { + start: Instant, + strength: f32, + seconds: f32, +} + +/// The HUD batch's colour (ABGR) from a mod's 0xAARRGGBB. +#[cfg(feature = "mods")] +fn argb(color: u32) -> u32 { + let [a, r, g, b] = color.to_be_bytes(); + rgba(r, g, b, a) +} + +/// The view's turn at full strength, in degrees: yaw, then pitch. +#[cfg(feature = "mods")] +const SHAKE_DEGREES: (f32, f32) = (3.0, 2.0); + +#[cfg(feature = "mods")] +impl Shake { + pub(super) fn add(&mut self, strength: f32, seconds: f32) { + self.jolts.push(Jolt { + start: Instant::now(), + strength, + seconds, + }); + } + /// How far the view turns now (yaw, pitch degrees), `scale` being the + /// player's Distortion Effects; fades jolts out and forgets ended ones. + fn offset(&mut self, now: Instant, scale: f32) -> (f32, f32) { + self.jolts + .retain(|j| now.duration_since(j.start).as_secs_f32() < j.seconds); + let mut strength = 0.0; + for j in &self.jolts { + let left = 1.0 - now.duration_since(j.start).as_secs_f32() / j.seconds; + strength += j.strength * left * left; + } + let strength = strength.min(1.0) * scale.clamp(0.0, 1.0); + if strength <= 0.0 { + return (0.0, 0.0); + } + // Smooth noise: sines at unrelated rates, so it never repeats visibly. + let t = self + .jolts + .first() + .map_or(0.0, |j| now.duration_since(j.start).as_secs_f32()); + let wave = |a: f32, b: f32, c: f32| { + ((t * a).sin() * 0.5 + (t * b).sin() * 0.3 + (t * c).sin() * 0.2).clamp(-1.0, 1.0) + }; + ( + strength * SHAKE_DEGREES.0 * wave(23.0, 37.3, 51.7), + strength * SHAKE_DEGREES.1 * wave(29.1, 43.9, 61.3), + ) + } +} + +#[cfg(not(feature = "mods"))] +impl Game<'_> { + pub(super) fn draw_mod_shapes(&self, _batch: &mut HudBatch) {} + pub(super) fn shaken_view(&mut self, yaw: f32, pitch: f32) -> (f32, f32) { + (yaw, pitch) + } +} + +#[cfg(feature = "mods")] +impl Game<'_> { + /// The running mods' HUD shapes, in order, over the HUD. + pub(super) fn draw_mod_shapes(&self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + for shape in self.mods.mods.hud_shapes() { + match shape { + Shape::Fill(f) => { + let r = f.rect; + batch.fill(atlas, r.x, r.y, r.w, r.h, argb(f.color)); + } + Shape::Quad(q) => { + let (a, b, c, d) = q.corners; + let corners = [[a.x, a.y], [b.x, b.y], [c.x, c.y], [d.x, d.y]]; + batch.fill_quad(atlas, corners, argb(q.color)); + } + Shape::Sprite(s) => { + let r = s.rect; + let name = s.sprite.strip_prefix("minecraft:").unwrap_or(&s.sprite); + let name = format!("gui/sprites/{name}"); + batch.sprite_scaled(atlas, &name, r.x, r.y, r.w, r.h, argb(s.color)); + } + Shape::Item(i) => { + if self.res.items().get(&i.item).is_none() { + continue; + } + let start = batch.vertices.len(); + let stack = ItemStack::new(i.item.as_str(), 1); + self.draw_item_model(batch, &stack, i.at.x, i.at.y); + batch.scale_since(start, i.at.x, i.at.y, i.scale, i.scale); + } + Shape::Text(t) => { + let text = Text::literal(t.text.clone()); + let x = if t.centered { + t.at.x - (HudBatch::text_width(atlas, &t.text) / 2.0).floor() + } else { + t.at.x + }; + batch.text_styled( + atlas, + &text, + x, + t.at.y, + argb(t.color | 0xFF00_0000), + t.shadow, + ); + } + } + } + } + /// The view's yaw and pitch after the mods' camera shakes; unchanged + /// while none is fading. + pub(super) fn shaken_view(&mut self, yaw: f32, pitch: f32) -> (f32, f32) { + if self.mods.shake.jolts.is_empty() { + return (yaw, pitch); + } + let scale = self.settings.file.double("screenEffectScale") as f32; + let (dy, dp) = self.mods.shake.offset(Instant::now(), scale); + (yaw + dy, (pitch + dp).clamp(-90.0, 90.0)) + } +} + +#[cfg(all(test, feature = "mods"))] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn a_jolt_fades_out_and_distortion_scales_it() { + let mut shake = Shake::default(); + shake.add(1.0, 2.0); + let start = shake.jolts[0].start; + let at = |s: f32| start + Duration::from_secs_f32(s); + let size = |(y, p): (f32, f32)| y.abs() + p.abs(); + // Off with Distortion Effects at 0, inside the limits otherwise. + assert_eq!(shake.offset(at(0.3), 0.0), (0.0, 0.0)); + let (y, p) = shake.offset(at(0.3), 1.0); + assert!(y.abs() <= SHAKE_DEGREES.0 && p.abs() <= SHAKE_DEGREES.1); + // Fading: the largest turn over a window shrinks. + let mut peak = |from: f32| { + (0..50) + .map(|i| size(shake.offset(at(from + i as f32 * 0.002), 1.0))) + .fold(0.0, f32::max) + }; + let early = peak(0.1); + let late = peak(1.6); + assert!(late < early, "{late} !< {early}"); + // Gone once it ends. + assert_eq!(shake.offset(at(2.1), 1.0), (0.0, 0.0)); + assert!(shake.jolts.is_empty()); + } +} diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 47a3ce07b..2a07cb940 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -33,7 +33,10 @@ use { #[derive(Default)] pub(super) struct ModsState { #[cfg(feature = "mods")] - mods: Mods, + pub(super) mods: Mods, + /// Capability `render`'s camera shakes. + #[cfg(feature = "mods")] + pub(super) shake: super::mod_render::Shake, /// `--dev-mod PATH`: always on, reloaded when rebuilt. pub(super) dev: Vec, /// When dev mods were last checked for a rebuild. @@ -308,7 +311,11 @@ impl Game<'_> { game_time: self.world.game_time.max(0) as u64, day_time: self.world.day_time.max(0) as u64, }); - Snapshot { player, clock } + Snapshot { + player, + clock, + gui_size: self.gui_size(), + } } /// A game tick. pub(super) fn tick_mods(&mut self) { @@ -382,6 +389,10 @@ impl Game<'_> { self.open_mod_screen(owner, false); continue; } + Output::Shake { strength, seconds } => { + self.mods.shake.add(strength, seconds); + continue; + } Output::CloseScreen { owner } => { if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) { self.close_mod_screen(false); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 89d1b1c3c..c3a165792 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -835,6 +835,12 @@ impl HudBatch { r.v1 = cv; self.rect_uv(x, y, w, h, r, color); } + /// Any four-cornered shape in one colour, corners in order round it. + pub fn fill_quad(&mut self, atlas: &HudAtlas, corners: [[f32; 2]; 4], color: u32) { + let w = atlas.white; + let uv = [(w.u0 + w.u1) / 2.0, (w.v0 + w.v1) / 2.0]; + self.quad(corners, [uv; 4], color); + } /// GuiGraphics.fillGradient: `top` to `bottom`, down the rectangle. pub fn fill_gradient( &mut self, diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index aea52339f..8708fb5be 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -38,7 +38,7 @@ wit_bindgen::generate!({ pub use exports::horizon::mods::events::{Guest as __Guest, Registration}; pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest; -pub use horizon::mods::{chat, game, hud, log, storage, ui}; +pub use horizon::mods::{chat, game, hud, log, render, storage, ui}; /// The game's calls into a mod. Only the hooks [`Registration`] asks for /// are called; the others may stay as their defaults. diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 1e49919c3..64bbac592 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -163,6 +163,82 @@ interface ui-events { settings-opened: func(); } +/// Capability `render` (experimental: the manifest needs +/// `experimental = ["render"]`): shapes the game draws for the mod with its +/// own renderer, kept until the mod replaces them (no call per frame). A mod +/// never supplies shader code. +interface render { + /// A rectangle in GUI pixels: the top left corner and the size. + record rect { + x: f32, + y: f32, + w: f32, + h: f32, + } + /// A point in GUI pixels from the screen's top left. + record point { + x: f32, + y: f32, + } + record fill-shape { + rect: rect, + /// 0xAARRGGBB. + color: u32, + } + /// Any four-cornered shape (a wheel's segment, an arrow): the corners + /// in order round it. + record quad-shape { + corners: tuple, + /// 0xAARRGGBB. + color: u32, + } + record sprite-shape { + /// One of the game's GUI sprites, as `gui/sprites/` names them + /// (`hud/heart/full`, `widget/button`), the resource packs' versions + /// included. An unknown one draws nothing. + sprite: string, + rect: rect, + /// A tint, 0xAARRGGBB: 0xFFFFFFFF draws it as it is. + color: u32, + } + record item-shape { + /// `minecraft:diamond`, `:`; an unknown one draws nothing. + item: string, + /// The icon's top left. + at: point, + /// 1.0 is the hotbar's 16 × 16. + scale: f32, + } + record text-shape { + /// Up to 256 characters, one line. + text: string, + at: point, + /// 0xRRGGBB, as `hud`'s lines. + color: u32, + /// Centred on `at.x` instead of starting there. + centered: bool, + shadow: bool, + } + variant shape { + fill(fill-shape), + quad(quad-shape), + sprite(sprite-shape), + item(item-shape), + text(text-shape), + } + /// Replaces the mod's HUD shapes: up to 1024, drawn every frame in + /// order over the HUD (after the hotbar, under chat and screens), hidden + /// with the HUD (F1). An empty list removes them. + set-hud: func(shapes: list); + /// The screen's size in GUI pixels (width, height), as of this tick. + gui-size: func() -> tuple; + /// Shakes the camera: a jolt of `strength` (0 to 1, 1 the hardest) that + /// fades out over `seconds` (at most 10). Jolts add up to 1. The view + /// turns, the player doesn't, and the player's Distortion Effects option + /// scales it (0 turns it off). + shake: func(strength: f32, seconds: f32); +} + /// What the game calls. Only the hooks `init` asks for are ever called. interface events { record registration { @@ -203,6 +279,7 @@ world horizon-mod { world horizon-ui-mod { include horizon-mod; import ui; + import render; export ui-events; } @@ -211,3 +288,8 @@ world ui-host { import ui; export ui-events; } + +/// The game's side of capability `render` (imports only). +world render-host { + import render; +} diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 6070f99bd..1880b9f3e 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -84,15 +84,19 @@ pub enum Capability { /// A screen the mod owns and a settings page in Options > Mods, drawn /// with the menus' own widgets (interface `ui`, calls `ui-events`). Ui, + /// Shapes on the HUD and the camera's shake, drawn by the game's own + /// renderer (interface `render`). + Render, } impl Capability { - pub const ALL: [Capability; 6] = [ + pub const ALL: [Capability; 7] = [ Capability::GameRead, Capability::Chat, Capability::Hud, Capability::Storage, Capability::Registries, Capability::Ui, + Capability::Render, ]; /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { @@ -103,12 +107,13 @@ impl Capability { Capability::Storage => "storage", Capability::Registries => "registries", Capability::Ui => "ui", + Capability::Render => "render", } } /// May change in any release: a mod uses it only with /// `experimental = [""]` in its manifest. pub fn is_experimental(self) -> bool { - matches!(self, Capability::Ui) + matches!(self, Capability::Ui | Capability::Render) } /// What the player reads before turning the mod on: "May ". pub fn describe(self) -> &'static str { @@ -119,6 +124,7 @@ impl Capability { Capability::Storage => "save its own settings to disk", Capability::Registries => "add blocks and items to your worlds", Capability::Ui => "show its own screens and a settings page", + Capability::Render => "draw on your screen and shake the camera", } } /// The capability a component import needs, `Ok(None)` for one every @@ -150,6 +156,7 @@ impl fmt::Display for Capability { Capability::Storage => "storage", Capability::Registries => "registries", Capability::Ui => "ui", + Capability::Render => "render", }; f.write_str(name) } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 1b1795037..e19bfbe3f 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -40,6 +40,19 @@ pub use ui_bindings::horizon::mods::ui::{ ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget, }; use ui_bindings::{UiHost, horizon::mods::ui}; +/// Capability `render`'s imports (docs/mods.md): the game draws the shapes. +mod render_bindings { + wasmtime::component::bindgen!({ + path: "../horizon-mod-sdk/wit", + world: "render-host", + }); +} +/// What capability `render` asks the game to draw (WIT `interface render`). +pub use render_bindings::horizon::mods::render::{ + FillShape, ItemShape, Point as RenderPoint, QuadShape, Rect as RenderRect, Shape, SpriteShape, + TextShape, +}; +use render_bindings::{RenderHost, horizon::mods::render}; /// A mod's linear memory cap. const MEMORY: usize = 64 << 20; @@ -70,6 +83,8 @@ const STORAGE_WRITE_BUDGET: u64 = 1 << 20; pub struct Snapshot { pub player: Option, pub clock: Option, + /// The screen in GUI pixels (capability `render`'s `gui-size`). + pub gui_size: (f32, f32), } /// What mods asked the game to show since the last [`Mods::drain`]. @@ -86,6 +101,8 @@ pub enum Output { OpenScreen { owner: usize }, /// `ui.close-screen`: the mod closed its own screen (no `closed` back). CloseScreen { owner: usize }, + /// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10). + Shake { strength: f32, seconds: f32 }, } /// A mod's text panel, drawn every frame until it changes. @@ -153,6 +170,8 @@ struct State { out: Vec, panel: Option, ui: UiState, + /// Capability `render`'s HUD shapes, drawn until replaced. + shapes: Vec, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, /// Bytes `storage::set` may still write before this hook call ends @@ -231,6 +250,8 @@ impl Mods { .map_err(|e| e.to_string())?; UiHost::add_to_linker::>(&mut linker, |s| s) .map_err(|e| e.to_string())?; + RenderHost::add_to_linker::>(&mut linker, |s| s) + .map_err(|e| e.to_string())?; self.engine = Some((engine, linker)); } Ok(self.engine.as_ref().expect("made above")) @@ -290,6 +311,7 @@ impl Mods { out: Vec::new(), panel: None, ui: UiState::default(), + shapes: Vec::new(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, limits: StoreLimitsBuilder::new() @@ -481,6 +503,14 @@ impl Mods { .iter() .filter_map(|e| e.run.as_ref()?.store.data().panel.as_ref()) } + /// The running mods' HUD shapes (capability `render`), each mod's in + /// its own order, mods in load order. + pub fn hud_shapes(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()) + .flat_map(|r| &r.store.data().shapes) + } /// The screen mod `i` last pushed with `ui.open-screen`, while it is up. pub fn screen(&self, i: usize) -> Option<&UiScreen> { self.entries @@ -668,6 +698,57 @@ impl chat::Host for State { } } } +/// HUD shapes one mod may keep (capability `render`). +const SHAPES: usize = 1024; +/// The longest jolt `render.shake` makes, in seconds. +const SHAKE_SECONDS: f32 = 10.0; + +impl render::Host for State { + fn set_hud(&mut self, shapes: Vec) { + self.shapes = shapes + .into_iter() + .take(SHAPES) + .map(|shape| match shape { + Shape::Sprite(mut s) => { + s.sprite = clip(s.sprite); + Shape::Sprite(s) + } + Shape::Item(mut i) => { + i.item = clip(i.item); + i.scale = if i.scale.is_finite() { + i.scale.clamp(0.0, 16.0) + } else { + 1.0 + }; + Shape::Item(i) + } + Shape::Text(mut t) => { + t.text = clip(t.text); + t.color &= 0xFF_FFFF; + Shape::Text(t) + } + other => other, + }) + .collect(); + } + fn gui_size(&mut self) -> (f32, f32) { + self.snapshot.gui_size + } + fn shake(&mut self, strength: f32, seconds: f32) { + let ok = |v: f32, max: f32| { + if v.is_finite() { + v.clamp(0.0, max) + } else { + 0.0 + } + }; + let (strength, seconds) = (ok(strength, 1.0), ok(seconds, SHAKE_SECONDS)); + if strength > 0.0 && seconds > 0.0 { + self.out.push(Output::Shake { strength, seconds }); + } + } +} + impl hud::Host for State { fn set_panel(&mut self, corner: Corner, lines: Vec) { let lines = lines diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 77f0975f3..dac333fe6 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -1,7 +1,7 @@ //! Loads real mods built with the SDK: the coords-hud example and a guest //! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`. use horizon_mods::{ - Clock, Corner, Mods, Output, Package, Player, Snapshot, Status, manifest::componentize, + Clock, Corner, Mods, Output, Package, Player, Shape, Snapshot, Status, manifest::componentize, }; use std::{ path::{Path, PathBuf}, @@ -22,8 +22,8 @@ id = "test_ui_guest" name = "Test UI Guest" version = "0.1.0" api = "0.1" -capabilities = ["chat", "ui"] -experimental = ["ui"] +capabilities = ["chat", "ui", "render"] +experimental = ["ui", "render"] "#; /// Builds both mods once and writes their `.hmod` files; returns the folder. @@ -89,6 +89,7 @@ fn player() -> Snapshot { game_time: 100, day_time: 24000 + 6000, }), + gui_size: (427.0, 240.0), } } @@ -416,6 +417,37 @@ fn ui_screens_settings_and_events() { assert!(mods.screen(0).is_none()); } +#[test] +fn render_shapes_and_shakes() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + mods.set_snapshot(Snapshot { + gui_size: (427.0, 240.0), + ..Snapshot::default() + }); + assert_eq!(mods.hud_shapes().count(), 0); + assert!(mods.command("render_hud")); + let shapes: Vec<_> = mods.hud_shapes().cloned().collect(); + assert_eq!(shapes.len(), 5); + // The guest read `gui-size`; text is clipped to 256 characters. + let Shape::Text(t) = &shapes[4] else { + panic!("{:?}", shapes[4]) + }; + assert!(t.text.starts_with("gui 427x240 "), "{}", t.text); + assert_eq!(t.text.chars().count(), 256); + assert!(mods.command("render_clear")); + assert_eq!(mods.hud_shapes().count(), 0); + // One jolt, clamped; zero and NaN shake nothing. + mods.drain(); + assert!(mods.command("render_shake")); + assert_eq!( + mods.drain(), + [Output::Shake { + strength: 1.0, + seconds: 10.0 + }] + ); +} + #[test] fn content_only_mods_load_without_an_engine() { let manifest = r#" diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 1af3985a1..146ab6f40 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -1,11 +1,61 @@ //! A mod for the runtime's `ui` tests: `/ui_screen` opens a screen with one //! of each widget, `/ui_settings` sets a settings page, `/ui_close` closes //! the screen; the `ui-events` calls answer in chat so the host sees them. +//! `/render_hud`, `/render_clear` and `/render_shake` test `render`. use horizon_mod_sdk::{ Mod, Registration, chat, + render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, }; +/// One of each shape, the text too long by 44 characters. +fn shapes() -> Vec { + let (w, h) = render::gui_size(); + let p = |x, y| Point { x, y }; + vec![ + Shape::Fill(FillShape { + rect: Rect { + x: 4.0, + y: 4.0, + w: 60.0, + h: 20.0, + }, + color: 0x80FF0000, + }), + Shape::Quad(QuadShape { + corners: ( + p(w / 2.0, 10.0), + p(w / 2.0 + 20.0, 30.0), + p(w / 2.0, 50.0), + p(w / 2.0 - 20.0, 30.0), + ), + color: 0xC000FF00, + }), + Shape::Sprite(SpriteShape { + sprite: "hud/heart/full".into(), + rect: Rect { + x: 70.0, + y: 4.0, + w: 18.0, + h: 18.0, + }, + color: 0xFFFFFFFF, + }), + Shape::Item(ItemShape { + item: "minecraft:diamond".into(), + at: p(92.0, 4.0), + scale: 2.0, + }), + Shape::Text(TextShape { + text: format!("gui {w}x{h} {}", "x".repeat(300)), + at: p(w / 2.0, h / 2.0 - 30.0), + color: 0xFFFF55, + centered: true, + shadow: true, + }), + ] +} + struct Guest; fn widgets() -> Vec { @@ -30,9 +80,16 @@ fn widgets() -> Vec { impl Mod for Guest { fn init() -> Result<(Self, Registration), String> { - let hooks = ["ui_screen", "ui_settings", "ui_close"] - .into_iter() - .fold(Registration::new(), Registration::command); + let hooks = [ + "ui_screen", + "ui_settings", + "ui_close", + "render_hud", + "render_clear", + "render_shake", + ] + .into_iter() + .fold(Registration::new(), Registration::command); Ok((Guest, hooks)) } fn command(&mut self, name: &str, _args: &str) -> Result, String> { @@ -43,6 +100,14 @@ impl Mod for Guest { }), "ui_settings" => ui::set_settings(&widgets()), "ui_close" => ui::close_screen(), + "render_hud" => render::set_hud(&shapes()), + "render_clear" => render::set_hud(&[]), + // Clamped to (1, 10); the two after it shake nothing. + "render_shake" => { + render::shake(2.0, 99.0); + render::shake(0.0, 1.0); + render::shake(f32::NAN, 1.0); + } _ => {} } Ok(None) diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 0812cde54..ef889d599 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -13,6 +13,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `storage` | [`storage`](#storage) | save its own settings to disk | | `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds | | `ui` | [`ui`](#ui) | show its own screens and a settings page | +| `render` | [`render`](#render) | draw on your screen and shake the camera | ## World `horizon-mod` @@ -23,7 +24,7 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, A mod with widgets (capability `ui`): the SDK builds every mod against this world. Mods built for `horizon-mod` alone (no `ui-events` export) still load and simply hear nothing of their widgets. -- Imports (what the game offers): `ui`, `log`, `game`, `chat`, `hud`, `storage` +- Imports (what the game offers): `ui`, `render`, `log`, `game`, `chat`, `hud`, `storage` - Exports (what the mod provides): `ui-events`, `events` ## World `ui-host` @@ -33,6 +34,13 @@ The game's side of `horizon-ui-mod` beyond `horizon-mod`. - Imports (what the game offers): `ui` - Exports (what the mod provides): `ui-events` +## World `render-host` + +The game's side of capability `render` (imports only). + +- Imports (what the game offers): `render` +- Exports (what the mod provides): + ## `log` Access: always granted. @@ -205,6 +213,90 @@ What the game calls on a mod that shows widgets (capability `ui`): what the play | `closed` | `func()` | The player left the mod's screen (Esc or Done); not for a screen the mod closed itself or one that went away with the mod. | | `settings-opened` | `func()` | The player opened the mod's settings page in Options > Mods: call `ui::set-settings` now to fill it with fresh widgets. | +## `render` + +Access: capability `render`. + +Capability `render` (experimental: the manifest needs `experimental = ["render"]`): shapes the game draws for the mod with its own renderer, kept until the mod replaces them (no call per frame). A mod never supplies shader code. + +### record `rect` + +A rectangle in GUI pixels: the top left corner and the size. + +| Field | Type | | +| --- | --- | --- | +| `x` | `f32` | | +| `y` | `f32` | | +| `w` | `f32` | | +| `h` | `f32` | | + +### record `point` + +A point in GUI pixels from the screen's top left. + +| Field | Type | | +| --- | --- | --- | +| `x` | `f32` | | +| `y` | `f32` | | + +### record `fill-shape` + +| Field | Type | | +| --- | --- | --- | +| `rect` | `rect` | | +| `color` | `u32` | 0xAARRGGBB. | + +### record `quad-shape` + +Any four-cornered shape (a wheel's segment, an arrow): the corners in order round it. + +| Field | Type | | +| --- | --- | --- | +| `corners` | `tuple` | | +| `color` | `u32` | 0xAARRGGBB. | + +### record `sprite-shape` + +| Field | Type | | +| --- | --- | --- | +| `sprite` | `string` | One of the game's GUI sprites, as `gui/sprites/` names them (`hud/heart/full`, `widget/button`), the resource packs' versions included. An unknown one draws nothing. | +| `rect` | `rect` | | +| `color` | `u32` | A tint, 0xAARRGGBB: 0xFFFFFFFF draws it as it is. | + +### record `item-shape` + +| Field | Type | | +| --- | --- | --- | +| `item` | `string` | `minecraft:diamond`, `:`; an unknown one draws nothing. | +| `at` | `point` | The icon's top left. | +| `scale` | `f32` | 1.0 is the hotbar's 16 × 16. | + +### record `text-shape` + +| Field | Type | | +| --- | --- | --- | +| `text` | `string` | Up to 256 characters, one line. | +| `at` | `point` | | +| `color` | `u32` | 0xRRGGBB, as `hud`'s lines. | +| `centered` | `bool` | Centred on `at.x` instead of starting there. | +| `shadow` | `bool` | | + +### variant `shape` + +| Case | Payload | | +| --- | --- | --- | +| `fill` | `fill-shape` | | +| `quad` | `quad-shape` | | +| `sprite` | `sprite-shape` | | +| `item` | `item-shape` | | +| `text` | `text-shape` | | + +| Function | Signature | What it does | +| --- | --- | --- | +| `set-hud` | `func(shapes: list)` | Replaces the mod's HUD shapes: up to 1024, drawn every frame in order over the HUD (after the hotbar, under chat and screens), hidden with the HUD (F1). An empty list removes them. | +| `gui-size` | `func() -> tuple` | The screen's size in GUI pixels (width, height), as of this tick. | +| `shake` | `func(strength: f32, seconds: f32)` | Shakes the camera: a jolt of `strength` (0 to 1, 1 the hardest) that fades out over `seconds` (at most 10). Jolts add up to 1. The view turns, the player doesn't, and the player's Distortion Effects option scales it (0 turns it off). | + ## `events` Access: exported by the mod: the game calls it. diff --git a/docs/api/mods.md b/docs/api/mods.md index bec03e84e..cda484c31 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -95,5 +95,7 @@ What real mods need next, in the order modpacks and servers need it: ## Changelog +- Experimental `render` (`experimental = ["render"]`): HUD shapes (fill, quad, sprite, item, text), `gui-size`, camera + `shake`, drawn by the game's own renderer. - API 0.2 (content): data-driven blocks and items, tags, `horizon:add_to`, terrain adaptation. - API 0.1.0: `log`, `game`, `chat`, `hud`, `storage`; `init`, `tick`, `frame`, `command`, `chat`. diff --git a/docs/api/stability.md b/docs/api/stability.md index ffa9d9b11..76c3c4e51 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -88,6 +88,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | --- | --- | --- | | Mod API: `log`, `game`, `chat`, `hud`, `storage`, `events` | preview | 0.1.0 | | Mod API: `ui`, `ui-events` (a mod's screens and settings page) | experimental | manifest `experimental = ["ui"]` | +| Mod API: `render` (HUD shapes, camera shake; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` | | Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` | | Server mods (events, world, server commands) | not started | manifest `api = "0.3"`, experimental first | | Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | | diff --git a/docs/mods.md b/docs/mods.md index 9b3b8aa94..672d6c7fd 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,6 +87,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects. The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | Hook (export) | When | |---|---| @@ -114,7 +115,7 @@ loading. Ordered by what the first native ports need: | `inventory-read` | the player's inventory, held item, open container | AppleSkin, recipe viewers | | `recipes` | the recipe registry and lookups | JEI/EMI-style viewers | | `world-read` | blocks and biomes around the player, within the render distance | minimaps, schematics | -| `render` | world-space lines, boxes and ghost blocks in a per-frame budget | Litematica-style placement, waypoints | +| `render` (world) | world-space lines, boxes and billboards, beside the HUD shapes `render` has | Litematica-style placement, waypoints | | `registries` | new blocks, items, entities and recipes, mostly data: JSON models, textures, loot and recipes in the `.hmod`'s `assets/` and `data/` | server side; see [Multiplayer](#multiplayer) | | `server` | world events (block break/place, entity spawn/death, player join), game rules, server commands | runs where the world is simulated | | `net` | a mod's own client↔server channel (custom payloads) | only between the two halves of the same mod | @@ -288,7 +289,7 @@ experimental = [] # experimental capabilities it uses, e.g. ["ui"] ``` Unknown keys are refused, so a typo is an error, not a silently ignored -permission. An experimental capability (today `ui`) may change in any release +permission. An experimental capability (today `ui` and `render`) may change in any release ([stability](api/stability.md)): a mod uses it only by naming it in `experimental` as well, so nobody depends on it by accident. From 09ff66bfeee243b10396a77381095eaa31670327 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:39:44 +0000 Subject: [PATCH 18/43] Fix stale server digging after instant survival breaks Clear completed guest digging so replanted flowers and crops are not broken again after attack is released. Add a LAN replanting regression for both single-player paths. Co-Authored-By: Codex (gpt-6.1-sol) --- crates/horizon-client/src/game/lan_actions.rs | 11 ++- tools/lan_e2e.py | 68 +++++++++++++++++++ 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 02434d793..ab7803ddd 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1810,14 +1810,13 @@ impl Game<'_> { g.use_delay -= 1; } }); - // ServerPlayerGameMode.handleBlockBreakAction: a creative - // player's START breaks the block once (destroyAndAck) and - // leaves nothing being destroyed; its client sends no STOP. - // Kept, the dig broke whatever was put there next, every - // destroy delay, for as long as the player broke nothing else. + // ServerPlayerGameMode.handleBlockBreakAction: creative and + // instant survival STARTs finish without a STOP from the client. + // tick_mining clears mining on completion; forget the START too, + // so a flower or crop planted here later is not broken again. if digging.is_some() - && host.hub.guests[gi].creative() && let Some(play) = host.play.get_mut(&conn) + && (host.hub.guests[gi].creative() || play.mining.is_none()) { play.digging = None; } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f79e07033..f0333c87b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -250,6 +250,8 @@ 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). +- 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). @@ -6348,5 +6350,71 @@ CHECKS += ['sprint-fov'] CHECK_FNS['sprint-fov'] = check_sprint_fov +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() From 3762ab7cdaa0f67c8cd473a88347098ebc982f92 Mon Sep 17 00:00:00 2001 From: Alexander Krylov Date: Sun, 25 Oct 2026 23:46:43 +0300 Subject: [PATCH 19/43] Enchantments: the name and the level follow the selected language The registry resolved every `description` from the pinned `en_us` map at load and `full_name` took `enchantment.level.` from the same table, so a tooltip showed an English enchantment line whatever language the player picked. Keep the description's translation key and resolve it, and the level, through the current language at display time, with the English text as the fallback for the server thread, the probes and an old resource root. Refs #1774. Co-Authored-By: Hermes Agent (Nous Research) --- crates/horizon-client/src/enchant.rs | 55 +++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index 2fc9ef2fb..f5ddc84c2 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -33,7 +33,11 @@ impl Cost { #[derive(Clone, Debug)] pub struct Enchantment { pub id: Arc, + /// The name the pinned English map gave at load: the fallback for a + /// language that has no entry for the key below. pub description: String, + /// `description`'s translation key (`enchantment.minecraft.`). + pub description_key: String, pub max_level: u32, pub weight: u32, pub anvil_cost: u32, @@ -224,6 +228,7 @@ impl Enchantments { .get(key) .cloned() .unwrap_or_else(|| id.trim_start_matches("minecraft:").replace('_', " ")), + description_key: key.to_owned(), max_level: v["max_level"].as_u64().unwrap_or(1) as u32, weight: v["weight"].as_u64().unwrap_or(1) as u32, anvil_cost: v["anvil_cost"].as_u64().unwrap_or(0) as u32, @@ -329,16 +334,26 @@ impl Enchantments { } /// `Enchantment.getFullname` as plain text and whether it is a curse (red). pub fn full_name(&self, id: &str, level: u32) -> (String, bool) { + let language = crate::lang::current(); + self.full_name_in(language.as_deref(), id, level) + } + /// `full_name` against `language`; `None` keeps the English names loaded + /// above, which is what the server thread and the probes see. + pub fn full_name_in( + &self, + language: Option<&crate::lang::Language>, + id: &str, + level: u32, + ) -> (String, bool) { + let tr = |key: &str| language.and_then(|l| l.get(key).map(str::to_owned)); let Some(e) = self.get(id) else { return (format!("{id} {}", level_name(level)), false); }; - let mut name = e.description.clone(); + let mut name = tr(&e.description_key).unwrap_or_else(|| e.description.clone()); if level != 1 || e.max_level != 1 { name.push(' '); name.push_str( - self.lang - .get(&format!("enchantment.level.{level}")) - .map_or(&level_name(level), |s| s), + &tr(&format!("enchantment.level.{level}")).unwrap_or_else(|| level_name(level)), ); } (name, self.is_curse(id)) @@ -771,7 +786,7 @@ pub(crate) mod tests { let defs = [ ( "minecraft:sharpness", - json!({"anvil_cost":1,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}), + json!({"anvil_cost":1,"description":{"translate":"enchantment.minecraft.sharpness"},"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}), ), ( "minecraft:smite", @@ -795,6 +810,7 @@ pub(crate) mod tests { .map(|(id, v)| Enchantment { id: Arc::from(*id), description: id.trim_start_matches("minecraft:").into(), + description_key: v["description"]["translate"].as_str().unwrap_or("").into(), max_level: v["max_level"].as_u64().unwrap() as u32, weight: v["weight"].as_u64().unwrap() as u32, anvil_cost: v["anvil_cost"].as_u64().unwrap() as u32, @@ -1088,4 +1104,33 @@ pub(crate) mod tests { assert!(!e.compatible("minecraft:sharpness", "minecraft:smite")); assert!(e.compatible("minecraft:sharpness", "minecraft:unbreaking")); } + + /// The enchantment's name and its level come from the selected language, + /// with the English name loaded above as the fallback. + #[test] + fn names_follow_the_language() { + struct Mem(HashMap>); + impl crate::lang::ResourceSource for Mem { + fn read(&self, path: &str) -> Option> { + self.0.get(path).cloned() + } + } + let ru = Mem(HashMap::from([( + "assets/minecraft/lang/ru_ru.json".to_owned(), + r#"{"enchantment.minecraft.sharpness":"Острота","enchantment.level.5":"V"}"# + .as_bytes() + .to_vec(), + )])); + let ru = crate::lang::Language::load(&[&ru], "ru_ru"); + let e = sample(); + assert_eq!( + e.full_name_in(Some(&ru), "minecraft:sharpness", 5).0, + "Острота V" + ); + // mending carries no key in the fixture: the English name stays. + assert_eq!( + e.full_name_in(Some(&ru), "minecraft:mending", 1).0, + "mending" + ); + } } From 95c336a3870b003b6da5b7baae01d87e8cddee4b Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:50:57 +0000 Subject: [PATCH 20/43] fix(threads): lower helper thread priority on Android Co-Authored-By: Codex (gpt-6.1-sol) --- crates/horizon-threads/Cargo.toml | 2 +- crates/horizon-threads/src/lib.rs | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/horizon-threads/Cargo.toml b/crates/horizon-threads/Cargo.toml index 3d7581fe9..d43b3e4fc 100644 --- a/crates/horizon-threads/Cargo.toml +++ b/crates/horizon-threads/Cargo.toml @@ -6,7 +6,7 @@ license.workspace = true rust-version = "1.85" description = "Scheduling hints for the game's threads: the OS calls the crates that forbid unsafe code can't make" -[target.'cfg(any(target_vendor = "apple", target_os = "linux"))'.dependencies] +[target.'cfg(any(target_vendor = "apple", target_os = "linux", target_os = "android"))'.dependencies] libc = "0.2" [target.'cfg(windows)'.dependencies] diff --git a/crates/horizon-threads/src/lib.rs b/crates/horizon-threads/src/lib.rs index ae4cc753f..7e9146ce7 100644 --- a/crates/horizon-threads/src/lib.rs +++ b/crates/horizon-threads/src/lib.rs @@ -45,8 +45,8 @@ fn favour() -> bool { /// behind the server thread and the render thread (`behind_server`). static HELPERS_BEHIND: AtomicBool = AtomicBool::new(false); -/// How many nice levels a helper thread goes below the process on Linux. -#[cfg(target_os = "linux")] +/// How many nice levels a helper thread goes below the process on Linux and Android. +#[cfg(any(target_os = "linux", target_os = "android"))] const BEHIND: i32 = 10; /// From now on, the helper threads that call `behind_server` as they start @@ -58,7 +58,7 @@ pub fn put_helpers_behind() { /// Called by a helper thread as it starts (world generation, lighting and /// meshing, a connection's packet writer): work no tick or frame waits for. -/// Once `put_helpers_behind` was called, on Linux, where the server and +/// Once `put_helpers_behind` was called, on Linux and Android, where the server and /// render threads can't be raised (`favour_current`), the helper lowers /// itself instead, which an unprivileged thread may: 10 nice levels below /// the process, or, where nice runs out (a game started under nice 10 or @@ -69,10 +69,10 @@ pub fn behind_server() -> bool { HELPERS_BEHIND.load(Ordering::Relaxed) && behind() } -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", target_os = "android"))] fn behind() -> bool { // SAFETY: these read and set the calling thread's own nice value or - // policy (who 0, pid 0 is the calling thread on Linux); `param` lives + // policy (who 0, pid 0 is the calling thread on Linux and Android); `param` lives // across the call. unsafe { let nice = libc::getpriority(libc::PRIO_PROCESS as _, 0); @@ -85,7 +85,7 @@ fn behind() -> bool { } } -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", target_os = "android")))] fn behind() -> bool { false } @@ -117,12 +117,12 @@ mod tests { } /// A helper goes behind only once a dedicated server asks for it, and - /// then, on Linux, 10 nice levels below the process or in the idle class. + /// then, on Linux and Android, 10 nice levels below the process or in the idle class. #[test] fn helpers_go_behind_only_when_asked() { assert!(!std::thread::spawn(super::behind_server).join().unwrap()); super::put_helpers_behind(); - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_os = "android"))] std::thread::spawn(|| { // SAFETY: reads the calling thread's own nice value. let before = unsafe { libc::getpriority(libc::PRIO_PROCESS as _, 0) }; @@ -142,7 +142,7 @@ mod tests { }) .join() .unwrap(); - #[cfg(not(target_os = "linux"))] + #[cfg(not(any(target_os = "linux", target_os = "android")))] assert!(!std::thread::spawn(super::behind_server).join().unwrap()); } } From 40b3c1e3d68bf0c96d9eeb5b7c75cd207d0cf51d Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:08:55 +0000 Subject: [PATCH 21/43] Preserve requested GUI scale across temporary small surfaces Keep framebuffer limits in rendering and explicit option cycling rather than overwriting the saved choice during startup or settings application. Co-Authored-By: Codex gpt-6.1-sol --- crates/horizon-client/src/game.rs | 10 ------ .../horizon-client/src/game/startup_menu.rs | 2 -- crates/horizon-client/src/options_ui.rs | 3 -- crates/horizon-client/src/settings.rs | 33 +++++++++++++++---- 4 files changed, 26 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f5803ad08..7b69a2ee3 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9194,10 +9194,6 @@ impl Game<'_> { ) } fn apply_settings(&mut self) { - if let Some(r) = &self.renderer { - self.settings - .clamp_gui_scale([r.config.width as i32, r.config.height as i32]); - } self.streaming.radius = self.settings.render_distance; // Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves: // LevelExtractor.allChanged when they change. @@ -13094,10 +13090,6 @@ impl Loading { return; } } - if let Some(r) = &self.renderer { - self.settings - .clamp_gui_scale([r.config.width as i32, r.config.height as i32]); - } horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed); self.window = Some(window); } @@ -13136,8 +13128,6 @@ impl Loading { self.settings.horizon.api, ) { Ok(r) => { - self.settings - .clamp_gui_scale([r.config.width as i32, r.config.height as i32]); horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed); self.renderer = Some(r); } diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index a5d658a4d..f7be6241f 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -272,8 +272,6 @@ impl Loading { } pub(super) fn apply_menu_settings(&mut self) { if let Some(renderer) = &mut self.renderer { - self.settings - .clamp_gui_scale([renderer.config.width as i32, renderer.config.height as i32]); renderer.gamma = self.settings.gamma; renderer.set_present_mode(self.settings.vsync, self.settings.horizon.present_mode); } diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 1d1f099eb..9f91254bd 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -3403,9 +3403,6 @@ mod tests { assert_eq!(s.gui_scale, expected); } s.gui_scale = u32::MAX; - s.clamp_gui_scale(framebuffer); - assert_eq!(s.gui_scale, max); - s.gui_scale = u32::MAX; Opt::GuiScale.cycle(&mut s, false, framebuffer); assert_eq!(s.gui_scale, 0); s.gui_scale = u32::MAX; diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 5fc09e35b..2a53e1702 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -104,7 +104,7 @@ pub struct Settings { pub master_volume: f32, /// Volumes of every other sound source, indexed like SOUND_SOURCES. pub volumes: [f32; 11], - /// 0 = auto. + /// Requested scale (0 = auto); rendering caps it to the current framebuffer. pub gui_scale: u32, pub view_bobbing: bool, /// Brightness 0..1 (gamma). @@ -284,12 +284,6 @@ fn put_s(f: &mut OptionsFile, key: &str, v: &str) { } } impl Settings { - /// `ClampingLazyMaxIntRange.validateValue`: clamp once the framebuffer is known. - pub fn clamp_gui_scale(&mut self, framebuffer: [i32; 2]) { - let max = crate::window::calculate_scale(framebuffer, 0, self.force_unicode) as u32; - self.gui_scale = self.gui_scale.min(max); - } - pub fn load(path: &Path) -> Self { let horizon = path .parent() @@ -597,6 +591,31 @@ impl Settings { #[cfg(test)] mod tests { use super::*; + #[test] + fn gui_scale_survives_temporary_small_framebuffer() { + for requested in [0, 1, 2, 6] { + let settings = Settings::parse(&format!("guiScale:{requested}\n")); + // Hyprland's initial surface can be smaller than the fullscreen one. + for (framebuffer, maximum) in [([715, 860], 2), ([3400, 1913], 7)] { + let effective = crate::window::calculate_scale( + framebuffer, + settings.gui_scale as i32, + settings.force_unicode, + ); + assert_eq!( + effective, + if requested == 0 { + maximum + } else { + (requested as i32).min(maximum) + } + ); + let saved = Settings::parse(&settings.serialize()); + assert_eq!(saved.gui_scale, requested); + } + } + } + #[test] fn round_trips_vanilla_options_txt() { let text = "version:4000\nfov:0.5\nrenderDistance:16\nmaxFps:260\nrenderClouds:\"fast\"\nkey_key.jump:key.keyboard.j\nsoundCategory_music:0.25\nresourcePacks:[\"vanilla\",\"file/x.zip\"]\nlang:fr_fr\nsomeFutureOption:42\n"; From 2cdb6362cae1e4d88894f4fda3a4dc3b49ada9bb Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 22:38:40 +0100 Subject: [PATCH 22/43] Particles keep their sprites over a resource reload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The particle engine copied the GUI atlas's sprite rects once at start; a pack or server-pack change rebuilt the atlas but not the engine, so every named and set sprite then drew a stale region — break crumbs showed other blocks and campfire smoke showed random items (#1923). The engine now re-reads the rects and the packs' sprite sets on reload, and a particle whose sprite-set index outlived the rebuild keeps its sprite instead of indexing past the new list. The reload also layers content mods over the root again, which startup does but reload forgot, so the first reload silently dropped their assets and data. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game/packs.rs | 6 ++++ crates/horizon-client/src/particles.rs | 46 +++++++++++++++++++------ 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 7629a5d25..b35eff564 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -142,6 +142,8 @@ impl Game<'_> { } let server = &self.server_packs.active; let root = startup_root(&vanilla, &self.settings.resource_packs, server)?; + let root = + super::mods::content_root(&root, &self.settings.mods.enabled, &self.options.dev_mods); self.reload_resources(&root) } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { @@ -192,6 +194,10 @@ impl Game<'_> { let context = pack.context.clone(); self.pack = pack; self.gui = gui; + // The atlas's sprites moved: the particle engine re-reads every rect + // and the packs' sprite sets, or every particle draws a stale region. + self.particles + .reload(root, &self.gui.atlas.sprites, &self.gui.atlas.translucent); horizon_client::ui_theme::reset_atlas(); // Villager hats come from the pack's texture metadata (shared data, swapped in place). *self diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index be7f32551..fa9dc9c6e 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1212,10 +1212,7 @@ impl ParticleEngine { requested: None, names: Vec::new(), rects: Vec::new(), - atlas: atlas - .iter() - .map(|(name, &rect)| (name.clone(), (rect, translucent.contains(name)))) - .collect(), + atlas: HashMap::new(), sets: HashMap::new(), set_sprites: Vec::new(), emitters: Vec::new(), @@ -1225,6 +1222,34 @@ impl ParticleEngine { made: Default::default(), item_sprites: HashMap::new(), }; + engine.reload(root, atlas, translucent); + engine + } + /// `onResourceManagerReload`: sprite rects and sets come from the + /// reloaded atlas and pack; a live particle keeps drawing its sprite by + /// name or index. + pub fn reload( + &mut self, + root: &Path, + atlas: &HashMap, + translucent: &HashSet, + ) { + self.atlas = atlas + .iter() + .map(|(name, &rect)| (name.clone(), (rect, translucent.contains(name)))) + .collect(); + self.rects = self + .names + .iter() + .map(|name| self.atlas.get(name).map(|&(rect, _)| rect)) + .collect(); + self.sets.clear(); + self.set_sprites.clear(); + self.item_sprites.clear(); + self.load_sprites(root); + } + /// The sprite sets of every `particles/*.json` under `root`. + fn load_sprites(&mut self, root: &Path) { let dir = root.join("assets/minecraft/particles"); for &ty in ParticleType::ALL { let Ok(bytes) = std::fs::read(dir.join(format!("{}.json", ty.name()))) else { @@ -1239,18 +1264,16 @@ impl ParticleEngine { a.iter() .filter_map(|t| t.as_str()) .map(|t| { - engine - .intern(&format!("particle/{}", t.trim_start_matches("minecraft:"))) + self.intern(&format!("particle/{}", t.trim_start_matches("minecraft:"))) }) .collect() }) .unwrap_or_default(); if !sprites.is_empty() { - engine.sets.insert(ty, engine.set_sprites.len() as u32); - engine.set_sprites.push(sprites); + self.sets.insert(ty, self.set_sprites.len() as u32); + self.set_sprites.push(sprites); } } - engine } fn intern(&mut self, name: &str) -> u32 { if let Some(i) = self.names.iter().position(|n| n == name) { @@ -1601,7 +1624,10 @@ impl ParticleEngine { return; } if let Some(set) = p.set { - let sprites = &self.set_sprites[set as usize]; + // A sprite set's index can outlive the reload that rebuilt them. + let Some(sprites) = self.set_sprites.get(set as usize) else { + return; + }; let lifetime = p.lifetime.max(1); let index = (p.age.max(0) as i64 * (sprites.len() as i64 - 1) / i64::from(lifetime)) .clamp(0, sprites.len() as i64 - 1); From b6efebc87908e113cbf555496e61e61f1c685d16 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:39:14 +0000 Subject: [PATCH 23/43] Play anvil result sounds once for every player MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deliver anvil level events to the acting player and keep their local sound out of positional sound capture. Extend the anvil LAN check to count sounds for both players using either player’s anvil result. Co-Authored-By: OpenAI Codex --- crates/horizon-client/src/game.rs | 8 +++++++- crates/horizon-client/src/game/lan.rs | 6 +++--- tools/lan_e2e.py | 20 +++++++++++++++----- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f5803ad08..08abb2d2b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2764,7 +2764,13 @@ impl Game<'_> { } _ => 1.0, }; - self.audio.play(name, c, volume, pitch); + if matches!(id, 1029 | 1030) { + // Clients play the anvil sound from its level event; + // capturing it also sends a duplicate sound packet. + self.audio.play_unshared(name, c, volume, pitch); + } else { + self.audio.play(name, c, volume, pitch); + } } } LevelEvent::Sound { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index ddb959cf3..9b6754661 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1114,9 +1114,9 @@ impl Game<'_> { for e in events { if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e { // The acting guest does not predict the egg's teleport - // particles, nor bone meal's growth (BoneMealItem.useOn's - // levelEvent names no player). - let except = if matches!(*id, 2015 | 1505) { + // particles, bone meal's growth, or anvil result sounds + // (these levelEvent calls name no excluded player). + let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { None } else { self.lan_acting diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0ec7218d8..8e7985862 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -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); @@ -1620,6 +1620,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 +1644,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 +1663,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): From 116a7f7dcafc4e36d14b75600f402446ec8056ac Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:48:43 +0100 Subject: [PATCH 24/43] horizon-prepare: OUTPUT_VERSION, the number of what it prepares, checked by CI Launchers copy a player's prepared resources to a new release while its preparer declares the same OUTPUT_VERSION (the launcher side is its own pull request). The number is bumped by hand; CI keeps it honest: the parity job already prepares with every change to the preparer, and tools/prepare_output.py check now fails when that preparation's digest is not the one crates/horizon-prepare/output-versions.txt gives the current number, or when the file changed other than by appending a version. The digest canonicalises what differs between two runs of the same preparer (JSON key order, creative tab tag order, lambda class addresses, logs, the sounds): 10 preparations by 5 preparer versions on the three Mac runners give one digest, and a Linux preparation by an older preparer gives the Mac runners' digest for it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/parity.yml | 4 + crates/horizon-prepare/output-versions.txt | 3 + crates/horizon-prepare/src/lib.rs | 32 ++++ docs/release-flow.md | 4 + tests/test_prepare_output.py | 64 ++++++++ tools/prepare_output.py | 176 +++++++++++++++++++++ 6 files changed, 283 insertions(+) create mode 100644 crates/horizon-prepare/output-versions.txt create mode 100644 tests/test_prepare_output.py create mode 100755 tools/prepare_output.py diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index a18fc5019..0588c12a3 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -37,6 +37,10 @@ jobs: run: bash tools/ci/runner-env.sh - name: Vanilla data, and resources prepared by this preparer run: bash tools/ci/vanilla-data.sh + - name: The prepared output is the one the preparer's OUTPUT_VERSION says + env: + BASE_SHA: ${{ inputs.base }} + run: python3 tools/prepare_output.py check --cache --base "$BASE_SHA" - name: The version constants are the pinned jar's run: python3 tools/gen_version_consts.py --check - name: The harnesses this change can affect diff --git a/crates/horizon-prepare/output-versions.txt b/crates/horizon-prepare/output-versions.txt new file mode 100644 index 000000000..71a531fab --- /dev/null +++ b/crates/horizon-prepare/output-versions.txt @@ -0,0 +1,3 @@ +# OUTPUT_VERSION (src/lib.rs) and the digest of what it prepares (python3 tools/prepare_output.py digest), +# one line per version, never edited: a change to the prepared files appends the next version. +1 0a608bf4115a8ed2e2c4f5f2b2609dc10c54e63479af8e56fabaa10af1060389 diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index c7e443c7d..5ea1121df 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -31,6 +31,15 @@ pub type Log<'a> = &'a dyn Fn(&str); /// The manifest's `schema`: the prepared files' layout, which the launcher compares. pub const SCHEMA: i64 = 7; +/// What this preparer makes. The launcher copies a prepared version's resources to a newly installed +/// version whose preparer has the same number (and the same pinned jars), so a release that changes +/// this crate without changing its output asks nobody to prepare again. Bump it, and append the new +/// digest to output-versions.txt, when the prepared files change: CI prepares with every change to +/// the preparer and fails when the output is not the one output-versions.txt gives this number +/// (`python3 tools/prepare_output.py check`). The launcher reads this line from the version +/// folder's sources: keep it on one line, as it is. +pub const OUTPUT_VERSION: u32 = 1; + /// Digest of this crate's sources (build.rs): the launcher prepares a version in-process when /// that version ships these same sources, and runs the version's own binary otherwise. pub const SOURCES_SHA256: &str = env!("HORIZON_PREPARE_SOURCES_SHA256"); @@ -1209,6 +1218,29 @@ mod tests { fs::remove_dir_all(dir).unwrap(); } + #[test] + fn output_versions_end_at_the_output_version() { + let text = include_str!("../output-versions.txt"); + let versions: Vec<(u32, &str)> = text + .lines() + .filter(|l| !l.trim().is_empty() && !l.starts_with('#')) + .map(|l| { + let (n, digest) = l.split_once(' ').unwrap(); + (n.parse().unwrap(), digest.trim()) + }) + .collect(); + let numbers: Vec = versions.iter().map(|v| v.0).collect(); + assert_eq!(numbers, (1..=OUTPUT_VERSION).collect::>()); + for (i, (_, digest)) in versions.iter().enumerate() { + assert_eq!(digest.len(), 64); + assert!(!versions[..i].iter().any(|(_, d)| d == digest)); + } + // The launcher finds the number with this line in a version folder's sources. + let lib = include_str!("lib.rs"); + let line = format!("pub const OUTPUT_VERSION: u32 = {OUTPUT_VERSION};"); + assert!(lib.lines().any(|l| l == line)); + } + #[test] fn the_source_digest_is_the_one_build_rs_computed() { assert_eq!( diff --git a/docs/release-flow.md b/docs/release-flow.md index 4fb0209d9..1413cde01 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -39,6 +39,10 @@ copy is: the Mac mini. Its runner runs as the maintainer's account and keeps its depend only on the Minecraft version, are kept once in `shared-local/sounds//` (copied from a folder `horizon-prepare sounds` made from the maintainer's own game; the Mac mini has no official launcher of its own) and cloned into each preparation (not linked: vanilla's packs refuse symbolic links), for the audio harnesses. + `tools/prepare_output.py check` then compares what was prepared with `crates/horizon-prepare/output-versions.txt`: + launchers keep a player's prepared resources across releases whose preparer declares the same `OUTPUT_VERSION` + (`crates/horizon-prepare/src/lib.rs`), so a change to the prepared files fails here until it bumps the number + and appends the new digest (the error gives both lines). 3. `tools/parity.py --changed ` picks the harnesses whose traced dependencies (their script, Python modules, Java oracles and every Rust source their probes compile) changed since the merge base, plus any harness nothing is recorded about yet, and runs those that have no pass for their current inputs. A change to diff --git a/tests/test_prepare_output.py b/tests/test_prepare_output.py new file mode 100644 index 000000000..00c489fbb --- /dev/null +++ b/tests/test_prepare_output.py @@ -0,0 +1,64 @@ +import json +import tempfile +import unittest +from pathlib import Path + +from tools import prepare_output + + +class PrepareOutputTests(unittest.TestCase): + def preparation(self, root: Path, files: dict[str, bytes]) -> Path: + for rel, data in files.items(): + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return root + + def test_what_varies_between_runs_does_not_count(self): + manifest = {'schema': 7, 'data_version': 5023, 'render_files_sha256': {'a.json': 'x'}} + a = { + 'horizon-resources.json': json.dumps(manifest).encode(), + 'render-definitions.json': b'{"a": 1, "b": [1, 2]}', + 'creative-inventory.json': b'{"tags": [["b", "a"]]}', + 'block-behaviours.json': b'{"c": "Foo$$Lambda/0x0000012a"}', + 'export.log': b'run 1', + 'assets/minecraft/sounds/a.ogg': b'one', + } + manifest['render_files_sha256'] = {'a.json': 'y'} + b = { + 'horizon-resources.json': json.dumps(manifest).encode(), + 'render-definitions.json': b'{"b": [1, 2], "a": 1}', + 'creative-inventory.json': b'{"tags": [["a", "b"]]}', + 'block-behaviours.json': b'{"c": "Foo$$Lambda/0x00000ff0"}', + 'export.log': b'run 2', + 'assets/minecraft/sounds/a.ogg': b'two', + } + with tempfile.TemporaryDirectory() as tmp: + first = prepare_output.digest(self.preparation(Path(tmp) / 'a', a)) + second = prepare_output.digest(self.preparation(Path(tmp) / 'b', b)) + self.assertEqual(first, second) + # The data does, and so do the manifest's schema and the files there are. + (Path(tmp) / 'b/render-definitions.json').write_bytes(b'{"b": [2, 1], "a": 1}') + self.assertNotEqual(first, prepare_output.digest(Path(tmp) / 'b')) + (Path(tmp) / 'b/render-definitions.json').write_bytes(b'{"b": [1, 2], "a": 1}') + (Path(tmp) / 'b/horizon-resources.json').write_text(json.dumps({**manifest, 'schema': 8})) + self.assertNotEqual(first, prepare_output.digest(Path(tmp) / 'b')) + (Path(tmp) / 'b/horizon-resources.json').write_text(json.dumps(manifest)) + (Path(tmp) / 'b/new.nbt').write_bytes(b'') + self.assertNotEqual(first, prepare_output.digest(Path(tmp) / 'b')) + + def test_the_versions_file_ends_at_the_constant(self): + versions = prepare_output.parse_versions('# comment\n1 aa\n2 bb\n') + self.assertEqual(versions, [(1, 'aa'), (2, 'bb')]) + self.assertEqual(prepare_output.problems(versions, 2), []) + self.assertTrue(prepare_output.problems(versions, 1)) + self.assertTrue(prepare_output.problems([(1, 'aa'), (3, 'bb')], 3)) + self.assertTrue(prepare_output.problems([(1, 'aa'), (2, 'aa')], 2)) + root = Path(prepare_output.__file__).resolve().parent.parent + current = prepare_output.parse_versions((root / prepare_output.VERSIONS).read_text()) + constant = prepare_output.CONSTANT.search((root / prepare_output.LIB).read_text()) + self.assertEqual(prepare_output.problems(current, int(constant.group(1))), []) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/prepare_output.py b/tools/prepare_output.py new file mode 100755 index 000000000..81ed156cb --- /dev/null +++ b/tools/prepare_output.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""The prepared output's version: what keeps `OUTPUT_VERSION` (crates/horizon-prepare/src/lib.rs) honest. + +The launcher copies a prepared version's resources (`.local/horizon-client/`) to a newly installed +one when both pin the same Minecraft jars and their preparers declare the same `OUTPUT_VERSION`, so a release +that changes the preparer's code without changing what it makes asks nobody to prepare again. The number is +bumped by hand; this tool catches a change to the output without a bump. + +crates/horizon-prepare/output-versions.txt lists every `OUTPUT_VERSION` with the digest of what it prepares. +It only grows: the last line is the current version, and a change to the output appends a line. + + python3 tools/prepare_output.py digest [RESOURCES] the digest of a preparation + python3 tools/prepare_output.py check [--base SHA] [--cache] [RESOURCES] + fails when RESOURCES (default: this checkout's .local/horizon-client/, as CI prepares it) is + not what the last line says, or when the file changed other than by appending since SHA. --cache keeps + the digest beside RESOURCES (CI: a preparation never changes once made; it takes ~30 s to compute) + +The digest covers every file of the preparation, canonicalised where the preparer is not deterministic between +runs (verified across the CI runners): JSON is compared as data (key order, the order of each `tags` list of +creative-inventory.json, and the addresses in `$$Lambda/0x...` class names don't count); logs, compiled classes, +the sounds (copied from the player's launcher by another step) and the manifest's file hashes (raw bytes) don't +count. The manifest's own scalar fields (schema, data version, jar hashes, file count) do. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +VERSIONS = 'crates/horizon-prepare/output-versions.txt' +LIB = 'crates/horizon-prepare/src/lib.rs' +MANIFEST = 'horizon-resources.json' +LAMBDA = re.compile(r'\$\$Lambda/0x[0-9a-fA-F]+') +CONSTANT = re.compile(r'^pub const OUTPUT_VERSION: u32 = (\d+);', re.M) + + +def canonical_json(value, key=''): + if isinstance(value, dict): + return {k: canonical_json(v, k) for k, v in value.items()} + if isinstance(value, list): + items = [canonical_json(v, key) for v in value] + if key == 'tags' and all(isinstance(x, list) and all(isinstance(t, str) for t in x) for x in items): + items = [sorted(x) for x in items] + return items + if isinstance(value, str): + return LAMBDA.sub('$$Lambda', value) + return value + + +def canonical(rel: str, data: bytes) -> bytes: + if rel == MANIFEST: + manifest = json.loads(data) + scalars = {k: v for k, v in manifest.items() if not isinstance(v, (dict, list))} + return json.dumps(scalars, sort_keys=True).encode() + if rel.endswith('.json'): + try: + value = json.loads(data) + except ValueError: + return data + return json.dumps(canonical_json(value), sort_keys=True).encode() + return data + + +def skipped(rel: str) -> bool: + parts = rel.split('/') + return rel.endswith(('.log', '.class')) or parts[:3] == ['assets', 'minecraft', 'sounds'] \ + or rel == 'assets/minecraft/sounds.json' + + +def digest(resources: Path) -> tuple[str, int]: + """The digest of a preparation, and how many files it covers.""" + if not (resources / MANIFEST).is_file(): + raise SystemExit(f'{resources} is not a preparation: no {MANIFEST}') + files = [] + for dirpath, dirs, names in os.walk(resources): + dirs.sort() + for name in names: + path = Path(dirpath) / name + rel = path.relative_to(resources).as_posix() + if path.is_symlink() or skipped(rel): + continue + files.append(rel) + total = hashlib.sha256() + for rel in sorted(files): + data = hashlib.sha256(canonical(rel, (resources / rel).read_bytes())).hexdigest() + total.update(f'{rel}\0{data}\n'.encode()) + return total.hexdigest(), len(files) + + +def parse_versions(text: str) -> list[tuple[int, str]]: + out = [] + for line in text.splitlines(): + line = line.strip() + if not line or line.startswith('#'): + continue + number, value = line.split() + out.append((int(number), value)) + return out + + +def problems(versions: list[tuple[int, str]], constant: int | None) -> list[str]: + found = [] + if not versions: + return [f'{VERSIONS} lists no version'] + if [n for n, _ in versions] != list(range(1, len(versions) + 1)): + found.append(f'{VERSIONS}: the versions must be 1, 2, 3... in order') + if len({d for _, d in versions}) != len(versions): + found.append(f'{VERSIONS}: two versions with the same digest') + if constant != versions[-1][0]: + found.append(f'{LIB} says OUTPUT_VERSION = {constant}, {VERSIONS} ends at {versions[-1][0]}') + return found + + +def default_resources() -> Path: + lock = json.loads((ROOT / 'research-lock.json').read_text()) + return ROOT / '.local/horizon-client' / lock['minecraft']['version'] + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0]) + parser.add_argument('command', choices=['digest', 'check']) + parser.add_argument('resources', nargs='?', type=Path) + parser.add_argument('--base', help='the commit the change is based on (check: the file only grew since)') + parser.add_argument('--cache', action='store_true', help='keep the digest beside the preparation') + args = parser.parse_args() + resources = (args.resources or default_resources()).resolve() + tool = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()[:16] + cache = resources.parent / f'.output-digest-{resources.name}-{tool}' + if args.cache and cache.is_file(): + value, count = cache.read_text().split() + else: + value, count = digest(resources) + if args.cache: + cache.write_text(f'{value} {count}\n') + if args.command == 'digest': + print(value) + return 0 + + versions = parse_versions((ROOT / VERSIONS).read_text()) + match = CONSTANT.search((ROOT / LIB).read_text()) + found = problems(versions, int(match.group(1)) if match else None) + if args.base: + shown = subprocess.run(['git', 'show', f'{args.base}:{VERSIONS}'], cwd=ROOT, capture_output=True, text=True) + if shown.returncode == 0: + before = parse_versions(shown.stdout) + if versions[:len(before)] != before: + found.append(f'{VERSIONS} changed lines it already had (since {args.base[:12]}): ' + 'a new output gets a new version, appended') + current = versions[-1] if versions else (0, '') + if value != current[1]: + known = [n for n, d in versions if d == value] + if known: + found.append(f'the preparation is OUTPUT_VERSION {known[0]}\'s output, but OUTPUT_VERSION is {current[0]}') + else: + found.append( + f'the prepared output changed ({count} files, digest {value}) but OUTPUT_VERSION is still ' + f'{current[0]}. Players would keep resources prepared by the old preparer. Bump it:\n' + f' set `pub const OUTPUT_VERSION: u32 = {current[0] + 1};` in {LIB}\n' + f' append `{current[0] + 1} {value}` to {VERSIONS}\n' + ' (if the change is only a nondeterminism this tool should ignore, teach canonical() instead)') + for problem in found: + print(f'::error::{problem}' if os.environ.get('GITHUB_ACTIONS') else f'error: {problem}', file=sys.stderr) + if not found: + print(f'prepared output: OUTPUT_VERSION {current[0]} ({count} files, {value[:16]})') + return 1 if found else 0 + + +if __name__ == '__main__': + sys.exit(main()) From 0b49da246674bef76848ffe3ecb7517db48f0faf Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:07:58 +0000 Subject: [PATCH 25/43] Fix lead drops when leashed mobs die Follow Leashable.tickLeash for dying mobs and cover trader/player-held llama leads through the death animation. Co-Authored-By: Codex --- .../examples/probe/mob_ai_probe.rs | 16 ++++++++++++++++ crates/horizon-client/src/game/leads.rs | 2 ++ crates/horizon-client/src/mobs/leash.rs | 9 +++++++++ .../horizonlab/parity/VanillaMobAiOracle.java | 8 ++++++++ tools/test_mob_ai_parity.py | 15 ++++++++++++++- 5 files changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index 157baa74c..49f56c250 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -598,6 +598,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool, now: i6 let _ = writeln!(out, " removed {reason}"); return; } + let _ = write!(out, "\tleashed {}", u8::from(m.extra.leash.is_some())); let p = m.position; let v = m.velocity; let _ = write!( @@ -977,6 +978,7 @@ pub fn main() -> horizon_client::Result<()> { } // Set once the brain exists (below). x if x.starts_with("cooldown=") => {} + "dead" => m.health = 0.0, "leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player), x if x.starts_with("leashto=") => { let n: u32 = x[8..].parse().unwrap(); @@ -1097,6 +1099,7 @@ pub fn main() -> horizon_client::Result<()> { } }; } + let mut dropped_leads = 0; for t in 1..=s.ticks { world.game_time += 1; if s.daycycle { @@ -1208,6 +1211,16 @@ pub fn main() -> horizon_client::Result<()> { if !alive { m.removed = true; } + // Apply the same detach/drop event as Game::break_leash. + for event in &events[from..] { + if let MobEvent::LeashBreak { mob, drop, .. } = event + && let Some(m) = mobs.iter_mut().find(|m| m.id == *mob) + && horizon_client::mobs::leash::remove(m).is_some() + && *drop + { + dropped_leads += 1; + } + } horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); villager_events( &mut mobs, @@ -1427,6 +1440,9 @@ pub fn main() -> horizon_client::Result<()> { world.game_time, ); } + if s.name.starts_with("leash_death_") { + let _ = writeln!(out, "{t} leads {dropped_leads}"); + } for e in &events { if let MobEvent::Sound(name, _, volume, pitch) = e { let _ = writeln!( diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index 3a5112967..8867157ee 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -79,6 +79,8 @@ impl Game<'_> { if horizon_client::mobs::leash::remove(m).is_none() { return; } + // Leashable.tickLeash gates a dying entity's lead drop on entity_drops. + let drop = drop && (m.alive() || self.ui.rules.bool("entity_drops")); let at = [m.position.x, m.position.y, m.position.z]; if sound { self.lead_sound("break", at); diff --git a/crates/horizon-client/src/mobs/leash.rs b/crates/horizon-client/src/mobs/leash.rs index b7c5011ba..3bd0513d7 100644 --- a/crates/horizon-client/src/mobs/leash.rs +++ b/crates/horizon-client/src/mobs/leash.rs @@ -198,6 +198,15 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.extra.leash_spin = 0.0; return; }; + // Leashable.tickLeash: a dying entity cannot interact with the level. + if !m.alive() { + events.push(MobEvent::LeashBreak { + mob: m.id, + drop: true, + sound: false, + }); + return; + } let Some(state) = holder_state(w, holder) else { // The holder is gone: the lead drops. if !matches!(holder, Holder::Player) { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 5808fec0d..eb5235adf 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -604,6 +604,7 @@ public final class VanillaMobAiOracle { case "tame" -> { if (mob instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true); } case "strength" -> method(net.minecraft.world.entity.animal.equine.Llama.class, "setStrength", int.class) .invoke(mob, Integer.parseInt(v)); + case "dead" -> mob.setHealth(0.0F); case "leashed", "leashto" -> { // Leashed once every mob exists (below). } @@ -807,6 +808,12 @@ public final class VanillaMobAiOracle { for (BlockPos h : heartPositions) printHeart(t, level, h); for (String[] b : s.blocks) if (b[0].equals("chest")) printChest(t, s, level, b); for (String[] b : s.blocks) if (isHive(b)) printHive(t, level, b); + if (s.name.startsWith("leash_death_")) { + int leads = level.getEntitiesOfClass(ItemEntity.class, ENTS.get(0).getBoundingBox().inflate(32.0), + item -> item.getItem().is(net.minecraft.world.item.Items.LEAD)) + .stream().mapToInt(item -> item.getItem().getCount()).sum(); + out.println(t + " leads " + leads); + } for (String sound : SOUNDS) out.println(t + " sound " + sound); for (var w : watched.entrySet()) { BlockState now = level.getBlockState(w.getKey()); @@ -1008,6 +1015,7 @@ public final class VanillaMobAiOracle { return; } Mob m = (Mob) e; + sb.append("\tleashed ").append(((net.minecraft.world.entity.Leashable) m).isLeashed() ? 1 : 0); sb.append("\tp ").append(d(m.getX())).append(',').append(d(m.getY())).append(',').append(d(m.getZ())); Vec3 v = m.getDeltaMovement(); sb.append("\tv ").append(d(v.x)).append(',').append(d(v.y)).append(',').append(d(v.z)); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 3e6ce74df..87a7a1403 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -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, []): From 8463325648f90045f83808dd201c07bfad2a264f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:28:03 +0100 Subject: [PATCH 26/43] 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 --- tools/ci/linux-runner.sh | 191 +++++++++++++++++++++++++++++++++++++++ tools/ci/runner-env.sh | 32 ++++++- tools/ci/runner-pause.py | 167 ++++++++++++++++++++++++++++++++++ tools/ci/vanilla-data.sh | 8 +- 4 files changed, 392 insertions(+), 6 deletions(-) create mode 100755 tools/ci/linux-runner.sh create mode 100755 tools/ci/runner-pause.py diff --git a/tools/ci/linux-runner.sh b/tools/ci/linux-runner.sh new file mode 100755 index 000000000..0cb677c87 --- /dev/null +++ b/tools/ci/linux-runner.sh @@ -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 '' -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" <> "$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" < "$units/horizon-runner.service" < "$units/horizon-runner-pause.service" </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 diff --git a/tools/ci/runner-env.sh b/tools/ci/runner-env.sh index 49158ac91..39828b7d7 100755 --- a/tools/ci/runner-env.sh +++ b/tools/ci/runner-env.sh @@ -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_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 '' --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" diff --git a/tools/ci/runner-pause.py b/tools/ci/runner-pause.py new file mode 100755 index 000000000..4a88c6ae4 --- /dev/null +++ b/tools/ci/runner-pause.py @@ -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() diff --git a/tools/ci/vanilla-data.sh b/tools/ci/vanilla-data.sh index 5276c54e9..a7bd4a407 100755 --- a/tools/ci/vanilla-data.sh +++ b/tools/ci/vanilla-data.sh @@ -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. From d81aa97e842a753e231ae34b181bc1bd2654c589 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:12:08 +0100 Subject: [PATCH 27/43] CI: the desktop runner works only while nobody is at the screen; desktop as a parity host runner_pause.py pauses on any seat0 session (locked too), games, GPU use or a pause file, and is the only thing that starts the runner; a job under way is throttled, then the runner stops. The desktop host in parity_hosts.json refuses work while paused and its workers stop on a pause. The nightly audit stays on the Mac mini. Docs and a unit test of the watcher. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/nightly.yml | 3 +- docs/parity-workflow.md | 2 +- docs/release-flow.md | 28 +++- tests/test_runner_pause.py | 82 ++++++++++++ tools/ci/linux-runner.sh | 52 +++++--- tools/ci/{runner-pause.py => runner_pause.py} | 125 +++++++++++------- tools/parity_hosts.json | 9 ++ 7 files changed, 230 insertions(+), 71 deletions(-) create mode 100644 tests/test_runner_pause.py rename tools/ci/{runner-pause.py => runner_pause.py} (51%) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 51f9e89cd..60bbbf057 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -29,7 +29,8 @@ env: jobs: audit: - runs-on: [self-hosted, horizon-game] + # The Mac mini's runners only: the audit compares with the previous one, so it stays on one platform. + runs-on: [self-hosted, horizon-game, macOS] timeout-minutes: 150 steps: - name: 03:00 in Paris diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index f9f222071..80426fa59 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -38,7 +38,7 @@ The game logs into `HORIZON_HOME` and falls back to the player's own game folder ### Other machines -Harnesses can also run on the Mac mini and the ThinkPad (`tools/parity_hosts.json` describes them; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 3 and only those under 800 MB. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. +Harnesses can also run on the Mac mini, the ThinkPad and the desktop (`tools/parity_hosts.json` describes them; `desktop` uses its CI runner's environment and vanilla data, and refuses work, or stops it, while someone is at it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 3 and only those under 800 MB. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad helps too, gently: Linux, 2 harnesses at `nice 19`, since it hosts the Claude account pool; it finds ALSA through `~/code/horizon-parity/alsa-dev` like the desktop. diff --git a/docs/release-flow.md b/docs/release-flow.md index 4fb0209d9..e72bebc73 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -13,7 +13,7 @@ reopened; labels never start it): | Job | Runs on | What | Time | | --- | --- | --- | --- | | `verify` | GitHub `ubuntu-latest` | Public-tree check, Python tests, rustfmt, clippy with warnings denied, Rust tests. Dependencies and the workspace build come from a cache saved by main's runs | ~4 min cold, less warm | -| `parity / parity` | The Mac mini's runner (`ludovics-mac-mini`, label `horizon-game`) | The vanilla harnesses the change can affect (`tools/parity.py --changed `) | seconds when nothing is affected; minutes per affected harness | +| `parity / parity` | A runner with the label `horizon-game`: the Mac mini's two, and the desktop's when no game runs there (below) | The vanilla harnesses the change can affect (`tools/parity.py --changed `) | seconds when nothing is affected; minutes per affected harness | Pushes to main run `verify` only; the nightly audit covers main's harnesses. @@ -28,10 +28,13 @@ The job is `.github/workflows/parity.yml`, a reusable workflow: `checks` calls i repository, `run-parity.yml` for a fork's pull request a maintainer labels `run-parity`. Horizon never downloads the game, so harnesses that compare with vanilla run only where the maintainer's own -copy is: the Mac mini. Its runner runs as the maintainer's account and keeps its checkout between runs -(`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes stand. +copy is: the Mac mini and his Linux desktop. Their runners run as the maintainer's account and keep their checkout +between runs (`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes +stand. -1. `tools/ci/runner-env.sh` puts the machine's Python 3.13 and the JDK `research-lock.json` pins on the PATH. +1. `tools/ci/runner-env.sh` puts the machine's Python 3.13 and the JDK `research-lock.json` pins on the PATH + (Homebrew and `java_home` on the Mac; on NixOS what `linux-runner.sh` pinned, else nixpkgs), and sccache when + the machine has it. 2. `tools/ci/vanilla-data.sh` links `.local/` to the runner's copy of the vanilla data, cloned once from `~/code/horizon-parity/shared-local` into `~/.actions-runners/horizon/_work/horizon/shared-local`, and prepares `.local/horizon-client` with the pull request's own `horizon-prepare` once per preparer version @@ -64,6 +67,23 @@ release's macOS build back. Each keeps its own checkout, `target/` and Rust inst `_work/horizon/shared-local` links to the first's, so they share the vanilla data, the preparations (one at a time, under a lock) and the parity passes and slots. +**The desktop's runner.** `ludodesktop-horizon` (labels `self-hosted`, `Linux`, `X64`, `ludodesktop`, and +`horizon-game` once a full trial has passed there) runs on the maintainer's Linux desktop, only while nobody is +at it. `tools/ci/linux-runner.sh install`, run there as him, registers it and installs two systemd user services: +`horizon-runner` (the runner, in `~/.actions-runners/horizon`, nice 19, in `horizon-ci.slice` with CPU and I/O +weight 20 and memory capped at two thirds of the RAM; `CARGO_BUILD_JOBS` and the harness slots at 8, after the +machine froze under ~7 cold cargo builds on 2026-10-14; its own Rust install; the JDK, sccache and the build +libraries from nixpkgs; its own `vscreen` so no game it starts reaches his screen) and `horizon-runner-pause` +(`tools/ci/runner_pause.py`), the only thing that starts the runner. The watcher stops it while a graphical +session is open on the machine, locked or not (`~/fleet/power status` says "IN USE"), while a game runs (Steam, +gamescope, Wine, Proton or Minecraft processes, fleet-load's own detection, or a process outside the CI slice +using the GPU at 50 % or more), or while `~/.actions-runners/horizon/pause` exists, and starts it again 5 minutes +after the last such sign. A job already under way is throttled to 2 threads at the lowest weight and the runner +stops after it: freezing the job would make GitHub drop it as lost and the harnesses time out. Old pull requests' +`runner-env.sh` know only the Mac: the runner's `.env` and `.path` give their jobs Python, the JDK and the +vanilla data (`HORIZON_SHARED_SOURCE`) all the same. The nightly audit stays on the Mac mini's runners, so its +comparison with the previous night is always made on one platform. + ## Merging Pull requests merge with a merge commit. The orchestrator sessions review a pull request, then turn on diff --git a/tests/test_runner_pause.py b/tests/test_runner_pause.py new file mode 100644 index 000000000..c6df08b82 --- /dev/null +++ b/tests/test_runner_pause.py @@ -0,0 +1,82 @@ +"""tools/ci/runner_pause.py: the Linux CI runner works only while nobody is at the screen or playing.""" +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from tools.ci import runner_pause + + +class Machine: + """A fake desktop: a clock, who is there, and the runner service. The watcher samples every 15 s.""" + + def __init__(self, signs): + self.signs = signs # (from, until, reason): a sign of someone at the screen or playing + self.clock = 0.0 + self.active = False + self.job_until = None # the runner is in a job until then + self.throttles = [] # (clock, on) + self.calls = [] + + def reason(self, hot): + return next((reason for start, end, reason in self.signs if start <= self.clock < end), None) + + def systemctl(self, *arguments): + self.calls.append((self.clock, arguments)) + if arguments[1:] == (runner_pause.SERVICE,): + self.active = {"start": True, "stop": False}.get(arguments[0], self.active) + return mock.Mock(returncode=0 if arguments[:2] != ("is-active", "--quiet") or self.active else 3) + + def busy(self): + return self.job_until is not None and self.clock < self.job_until + + def sleep(self, seconds): + self.clock += seconds + if self.clock > 2000: + raise StopIteration + + def run(self): + with tempfile.TemporaryDirectory() as directory, \ + mock.patch.multiple(runner_pause, MANUAL=Path(directory, "pause"), STATE=Path(directory, "paused"), + LOG=Path(directory, "pause.log"), INTERVAL=15, RESUME_AFTER=300, + pause_reason=self.reason, systemctl=self.systemctl, runner_busy=self.busy, + throttle=lambda on: self.throttles.append((self.clock, on))), \ + mock.patch.object(runner_pause.time, "monotonic", lambda: self.clock), \ + mock.patch.object(runner_pause.time, "sleep", self.sleep): + try: + runner_pause.main() + except StopIteration: # the clock ran out + pass + + def first(self, verb, after=0): + return next(clock for clock, arguments in self.calls + if arguments == (verb, runner_pause.SERVICE) and clock >= after) + + +class RunnerPauseTests(unittest.TestCase): + def test_starts_only_after_nobody_was_there_for_resume_after(self): + machine = Machine([(0, 600, "session 3 of ludovic at the screen (seat0)")]) + machine.run() + self.assertEqual(machine.first("start"), 585 + 300) # the last sample that saw him + + def test_a_game_stops_an_idle_runner_at_once(self): + machine = Machine([(1000, 1300, "process 42: wine64-preloader game.exe")]) + machine.run() + self.assertEqual(machine.first("start"), 300) + self.assertEqual(machine.first("stop", after=300), 1005) + self.assertEqual(machine.first("start", after=1005), 1290 + 300) + + def test_a_job_under_way_is_throttled_then_stopped_when_it_ends(self): + machine = Machine([(1000, 1300, "GPU busy: process 7 (game)")]) + machine.job_until = 1200 + machine.run() + self.assertIn((1005, True), machine.throttles) # the game started: the job slows down at once, + self.assertIn((1005, ("stop", "horizon-parity-worker-*.scope")), machine.calls) # other machines' work goes + stop = machine.first("stop", after=300) + self.assertGreaterEqual(stop, 1200) # and the runner stops once it ends, not before + self.assertLess(stop, 1215) + self.assertEqual(machine.throttles[-1], (1290 + 300, False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ci/linux-runner.sh b/tools/ci/linux-runner.sh index 0cb677c87..adc2b0130 100755 --- a/tools/ci/linux-runner.sh +++ b/tools/ci/linux-runner.sh @@ -8,12 +8,14 @@ # 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), +# 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 is +# at the screen or playing, 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. runner-pause.py pauses it while a game runs (horizon-runner-pause.service). +# 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 2/3 of the threads). +# ~/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 @@ -30,6 +32,18 @@ export LD_LIBRARY_PATH=/run/current-system/sw/share/nix-ld/lib${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 + [ -L "$entry" ] && ln -sfn "$entry" "$shared/$(basename "$entry")" + 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 @@ -40,7 +54,9 @@ display_env() { } install() { - local name=${RUNNER_NAME:-$(hostname)-horizon} jobs=${RUNNER_JOBS:-$(( $(nproc) * 2 / 3 ))} + 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 @@ -49,7 +65,7 @@ install() { 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/" + 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 @@ -66,11 +82,11 @@ install() { fi # Libraries for building (pkg-config) and running (dlopen) the game, the JDK pinned by research-lock.json, sccache. - local alsa udev java 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 - sccache=$(nix_out sccache sccache) + 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 @@ -91,6 +107,7 @@ 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 @@ -118,27 +135,25 @@ MemoryMax=$(( $(awk '/MemTotal/ {print int($2 / 1048576)}' /proc/meminfo) * 2 / EOF cat > "$units/horizon-runner.service" < "$units/horizon-runner-pause.service" < /dev/null + # 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 - [ -e "$dir/paused" ] || systemctl --user start horizon-runner.service status } run() { cd "$dir" fix_shebangs + parity_host_links if command -v vscreen > /dev/null; then eval "$(display_env)" else diff --git a/tools/ci/runner-pause.py b/tools/ci/runner_pause.py similarity index 51% rename from tools/ci/runner-pause.py rename to tools/ci/runner_pause.py index 4a88c6ae4..57f304f1f 100755 --- a/tools/ci/runner-pause.py +++ b/tools/ci/runner_pause.py @@ -1,19 +1,22 @@ #!/usr/bin/env python3 -"""Pauses the Horizon CI runner (tools/ci/linux-runner.sh) while the maintainer plays a game on this machine. +"""Pauses the Horizon CI runner (tools/ci/linux-runner.sh) while the maintainer is at this machine or plays on it. -A game is running when any of these holds: - - fleet-load says so (~/fleet/load: Steam, gamescope, Wine or Proton processes); +The runner works only while nobody is at the screen (rule of 2026-10-25, after ludodesktop was restarted under a +CI load while he used it). It pauses when any of these holds: + - a graphical session is open on seat0, locked or not: what `~/fleet/power status` calls "IN USE"; + - 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 % twice in a row); + - 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. 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. +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 @@ -27,7 +30,7 @@ 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)) +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)) @@ -50,6 +53,16 @@ def ci_process(pid): return True # gone +def at_the_screen(): + """A graphical login on seat0, as ~/fleet/power status counts it (a locked screen counts too).""" + 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: + return f"session {fields[0]} of {fields[2] if len(fields) > 2 else '?'} at the screen (seat0)" + return None + + def fleet_load_gaming(): status = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "fleet-load" / "status.json" try: @@ -82,7 +95,8 @@ def game_process(): 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, + # 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 {} @@ -92,7 +106,7 @@ def gpu_users(): 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]) + users[int(fields[1])] = max(users.get(int(fields[1]), 0), int(fields[3])) return users @@ -119,47 +133,60 @@ def throttle(on): systemctl("set-property", "--runtime", SLICE, "CPUWeight=20", "IOWeight=20", "CPUQuota=") +def pause_reason(hot): + """Why the runner may not work now, or None. hot: the GPU users seen busy at the last sample (updated).""" + if MANUAL.exists(): + return f"paused by hand ({MANUAL})" + reason = at_the_screen() 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 = {} # GPU users seen busy at the last sample - last_game = 0.0 - paused = STATE.exists() + hot = {} + # A boot (or a restart of this watcher) counts as a sign: the runner starts RESUME_AFTER seconds later at the + # earliest, which leaves time to log in after switching the machine on. + last_sign = time.monotonic() + paused = None 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})" + reason = pause_reason(hot) 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: + 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(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") + 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) diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index 0aa013a5b..5d561175d 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -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 is at the screen (tools/ci/runner_pause.py: 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", From 072f5ce2ee412f735e9b2ec70c29126695dc15b0 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:43:07 +0000 Subject: [PATCH 28/43] Fix custom item names above targeted item frames Show the framed item's custom name through the existing world name-label renderer, matching vanilla's HUD and crosshair conditions. Extend the LAN frame check for normal and glow frames. Co-Authored-By: Codex --- crates/horizon-client/src/game/names.rs | 36 +++++++++++++++++++++++++ tools/lan_e2e.py | 17 ++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 7655fb489..d5e8446c3 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -240,6 +240,42 @@ impl Game<'_> { discrete: false, }); } + // ItemFrameRenderer.shouldShowName/getNameTag: only the targeted + // frame's custom-named item, with the HUD visible (also glow frames). + if !self.ui.hide_gui + && let Some((i, distance)) = self.frame_hit() + && self.before_block(distance) + && self.mob_hit().is_none_or(|(_, d)| d > distance) + && let Some(name) = self.item_frames[i] + .item + .as_ref() + .and_then(|item| item.custom_name()) + { + let frame = &self.item_frames[i]; + let (lo, hi) = frame.bounds(); + let center = glam::DVec3::from_array(std::array::from_fn(|a| (lo[a] + hi[a]) / 2.0)); + if center.distance_squared(camera) < 64.0 * 64.0 { + // NAME_TAG is at the entity height (0.5), then the name + // submitter lifts it 0.5. ItemFrameRenderer offsets rendering + // 0.3 toward its facing and -0.25 vertically. + let step = frame.step(); + tags.push(NameTag { + at: center + + glam::DVec3::new( + f64::from(step[0] as f32 * 0.3), + 0.75, + f64::from(step[2] as f32 * 0.3), + ), + lines: vec![(Text::literal(name).resolve_legacy(), 0.0)], + light: self.world.light( + center.x.floor() as i32, + center.y.floor() as i32, + center.z.floor() as i32, + ), + discrete: false, + }); + } + } tags } /// `SubmitNodeCollection.submitNameTag`: a discrete name is drawn once, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0ec7218d8..df78489f9 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -3762,17 +3762,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 +3784,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, \ From b7629cf6560ac31557d751638910acdc8bf7e0f8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:46:36 +0100 Subject: [PATCH 29/43] Enchantments: say which callers have no language full_name reads the process's language, which the server thread shares with its window; only a process with no language loaded (a dedicated server, the probes) keeps the English names. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/enchant.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index f5ddc84c2..2f418ae82 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -337,8 +337,8 @@ impl Enchantments { let language = crate::lang::current(); self.full_name_in(language.as_deref(), id, level) } - /// `full_name` against `language`; `None` keeps the English names loaded - /// above, which is what the server thread and the probes see. + /// `full_name` against `language`; `None` (no language loaded: a + /// dedicated server, the probes) keeps the English names loaded above. pub fn full_name_in( &self, language: Option<&crate::lang::Language>, From 4be53ee28a64f126a1ab08b929eae354cba138c4 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:58:00 +0000 Subject: [PATCH 30/43] Reduce resource preparation filesystem work Share the asset index and verification state, stage checked imports while hashing, preserve indexed replacements, and clone independent resource copies where supported. Co-Authored-By: Codex (GPT-6.1) --- Cargo.lock | 2 + crates/horizon-prepare/Cargo.toml | 4 + crates/horizon-prepare/src/artifacts.rs | 78 +++-- crates/horizon-prepare/src/files.rs | 180 ++++++++++++ crates/horizon-prepare/src/lib.rs | 105 +++++-- crates/horizon-prepare/src/sounds.rs | 362 +++++++++++++++++++----- docs/prepare-performance.md | 44 +++ launcher/Cargo.lock | 2 + launcher/src/backend.rs | 2 +- 9 files changed, 637 insertions(+), 142 deletions(-) create mode 100644 crates/horizon-prepare/src/files.rs create mode 100644 docs/prepare-performance.md diff --git a/Cargo.lock b/Cargo.lock index 4d749add6..bb4e72446 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1408,6 +1408,8 @@ dependencies = [ name = "horizon-prepare" version = "0.1.0" dependencies = [ + "crc32fast", + "libc", "regex", "sha1", "sha2", diff --git a/crates/horizon-prepare/Cargo.toml b/crates/horizon-prepare/Cargo.toml index 3d62202bd..9bcf5464d 100644 --- a/crates/horizon-prepare/Cargo.toml +++ b/crates/horizon-prepare/Cargo.toml @@ -6,11 +6,15 @@ license = "MIT" description = "Prepares Horizon's resources from the player's own Minecraft: imports and checks the pinned jars, runs the vanilla exporters, writes the resource folder" [dependencies] +crc32fast = "1" regex = { version = "1", default-features = false, features = ["std", "unicode-perl"] } sha1 = "0.10" sha2 = "0.10" zip = { version = "2", default-features = false, features = ["deflate"] } +[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies] +libc = "0.2" + [build-dependencies] sha2 = "0.10" diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index 805dd80d4..a3bf945d5 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -143,31 +143,17 @@ pub(crate) fn import_copy( algorithm: &str, hint: &str, ) -> Result { - fs::create_dir_all(destination.parent().unwrap()).map_err(|e| e.to_string())?; - if destination.exists() && digest(destination, algorithm)? == checksum { - return Ok(destination.to_path_buf()); - } - if !source.is_file() { - return Err(format!("Missing {}. {hint}", source.display()) - .trim() - .to_string()); - } - let actual = digest(source, algorithm)?; - if actual != checksum { - return Err(format!( - "{} is not the pinned file: expected {algorithm} {checksum}, got {actual}", - source.display() - )); - } - let temporary = destination.with_file_name(format!( - ".{}.partial-{}", - destination.file_name().unwrap().to_string_lossy(), - std::process::id() - )); - let copied = fs::copy(source, &temporary).and_then(|_| fs::rename(&temporary, destination)); - let _ = fs::remove_file(&temporary); - copied.map_err(|e| format!("{}: {e}", destination.display()))?; - Ok(destination.to_path_buf()) + crate::files::Import::stage(source, destination, checksum, algorithm, false) + .map_err(|error| { + if !source.is_file() { + format!("Missing {}. {hint}", source.display()) + .trim() + .to_string() + } else { + error + } + })? + .commit() } /// The pinned version JSON from the launcher's versions/ directory. The launcher's copy wins @@ -653,9 +639,17 @@ pub struct Artifacts { /// Reuses checked imports from this root or another installed version beside it. pub fn reuse_imported(root: &Path, log: Log) -> Result { + Ok(reuse_verified(root, log)?.is_some()) +} + +/// Keep this preparation's verified artifacts and client libraries for the exporters. +pub(crate) fn reuse_verified( + root: &Path, + log: Log, +) -> Result)>, String> { let root = fs::canonicalize(root).map_err(|e| format!("{}: {e}", root.display()))?; let lock = Lock::read(&root)?; - let checked = |directory: PathBuf| -> Result, String> { + let checked = |directory: PathBuf| -> Result<(Artifacts, Vec), String> { let candidate = Lock { json: lock.json.clone(), version: lock.version.clone(), @@ -664,17 +658,9 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result { }; let found = verify(&candidate)?; let client = client_libraries(&candidate, &found.manifest)?; - let mut files = vec![ - candidate.directory.join("manifest.json"), - candidate.directory.join("jars/client.jar"), - candidate.directory.join("jars/server.jar"), - found.jars["server"].clone(), - ]; - files.extend(found.libraries); - files.extend(client); - Ok(files) + Ok((found, client)) }; - if checked(lock.directory.clone()).is_ok() { + if let Ok((found, client_libraries)) = checked(lock.directory.clone()) { if [ "prepared.json", "reports/client-inventory.json", @@ -683,8 +669,6 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result { .iter() .any(|path| !lock.directory.join(path).is_file()) { - let found = verify(&lock)?; - let client_libraries = client_libraries(&lock, &found.manifest)?; write_import_metadata( &root, &lock, @@ -696,10 +680,10 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result { )?; } log(&format!("Using imported Minecraft {}", lock.version)); - return Ok(true); + return Ok(Some((found, client_libraries))); } let Some(versions) = root.parent() else { - return Ok(false); + return Ok(None); }; // Sibling discovery is intended for the launcher's versions/ folder. let mut siblings: Vec<_> = fs::read_dir(versions) @@ -711,9 +695,17 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result { siblings.sort(); for sibling in siblings { let source = sibling.join(".local/minecraft").join(&lock.version); - let Ok(files) = checked(source.clone()) else { + let Ok((found, client)) = checked(source.clone()) else { continue; }; + let mut files = vec![ + source.join("manifest.json"), + source.join("jars/client.jar"), + source.join("jars/server.jar"), + found.jars["server"].clone(), + ]; + files.extend(found.libraries); + files.extend(client); for file in files { let relative = file.strip_prefix(&source).map_err(|e| e.to_string())?; import_copy( @@ -740,9 +732,9 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result { lock.version, sibling.display() )); - return Ok(true); + return Ok(Some((found, client_libraries))); } - Ok(false) + Ok(None) } pub fn verify(lock: &Lock) -> Result { diff --git a/crates/horizon-prepare/src/files.rs b/crates/horizon-prepare/src/files.rs new file mode 100644 index 000000000..484c7bf7b --- /dev/null +++ b/crates/horizon-prepare/src/files.rs @@ -0,0 +1,180 @@ +//! Independent copies, using filesystem cloning when available. Never hard links: exporters +//! rewrite prepared resources in place. Checked imports publish only after verifying the copy. + +use crate::{digest, hex}; +use sha2::Digest; +use std::fs; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn clone_file(from: &Path, to: &Path) -> io::Result<()> { + #[cfg(target_os = "linux")] + { + use std::os::fd::AsRawFd; + let source = fs::File::open(from)?; + let target = fs::File::create(to)?; + // SAFETY: FICLONE takes a source fd, both descriptors stay open for the call. + if unsafe { libc::ioctl(target.as_raw_fd(), libc::FICLONE, source.as_raw_fd()) } == 0 { + return Ok(()); + } + Err(io::Error::last_os_error()) + } + #[cfg(target_os = "macos")] + { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + let path = |p: &Path| { + CString::new(p.as_os_str().as_bytes()) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e)) + }; + let (source, target) = (path(from)?, path(to)?); + // SAFETY: both paths are valid NUL-terminated strings for the duration of the call. + if unsafe { libc::clonefile(source.as_ptr(), target.as_ptr(), 0) } == 0 { + return Ok(()); + } + Err(io::Error::last_os_error()) + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + { + let _ = (from, to); + Err(io::ErrorKind::Unsupported.into()) + } +} + +/// Copies an independent file, attempting a reflink first. The destination may be replaced. +pub fn clone_or_copy(from: &Path, to: &Path) -> io::Result<()> { + clone_file(from, to).or_else(|_| fs::copy(from, to).map(|_| ())) +} + +fn copy_hash(from: &Path, to: &Path) -> io::Result { + let mut source = fs::File::open(from)?; + let mut target = fs::File::create(to)?; + let mut hash = D::new(); + let mut buffer = vec![0; 64 * 1024]; + loop { + let n = source.read(&mut buffer)?; + if n == 0 { + return Ok(hex(&hash.finalize())); + } + target.write_all(&buffer[..n])?; + hash.update(&buffer[..n]); + } +} + +/// A verified replacement staged beside its destination. Dropping an unfinished set cleans +/// every temporary file, so a corrupt late panorama face cannot replace earlier placeholders. +pub(crate) struct Import { + temporary: Option, + destination: PathBuf, +} + +impl Import { + pub(crate) fn stage( + source: &Path, + destination: &Path, + checksum: &str, + algorithm: &str, + verified: bool, + ) -> Result { + let mut import = Self { + temporary: None, + destination: destination.into(), + }; + if verified || (destination.is_file() && digest(destination, algorithm)? == checksum) { + return Ok(import); + } + fs::create_dir_all(destination.parent().unwrap()).map_err(|e| e.to_string())?; + static COPIES: AtomicUsize = AtomicUsize::new(0); + let temporary = destination.with_file_name(format!( + ".{}.partial-{}-{}", + destination.file_name().unwrap().to_string_lossy(), + std::process::id(), + COPIES.fetch_add(1, Ordering::Relaxed) + )); + import.temporary = Some(temporary.clone()); + let actual = if clone_file(source, &temporary).is_ok() { + digest(&temporary, algorithm)? + } else { + match algorithm { + "sha1" => copy_hash::(source, &temporary), + _ => copy_hash::(source, &temporary), + } + .map_err(|e| format!("{}: {e}", source.display()))? + }; + if actual != checksum { + return Err(format!( + "{} is not the pinned file: expected {algorithm} {checksum}, got {actual}", + source.display() + )); + } + Ok(import) + } + + pub(crate) fn commit(mut self) -> Result { + if let Some(temporary) = &self.temporary { + fs::rename(temporary, &self.destination) + .map_err(|e| format!("{}: {e}", self.destination.display()))?; + } + self.temporary = None; + Ok(self.destination.clone()) + } +} + +impl Drop for Import { + fn drop(&mut self) { + if let Some(temporary) = &self.temporary { + let _ = fs::remove_file(temporary); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn copies_are_independent_and_checked_before_publication() { + let dir = std::env::temp_dir().join(format!("horizon-file-copy-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let source = dir.join("source"); + let target = dir.join("target"); + let data = vec![42; 200_000]; // More than one streaming buffer. + fs::write(&source, &data).unwrap(); + for algorithm in ["sha1", "sha256"] { + let checksum = digest(&source, algorithm).unwrap(); + Import::stage(&source, &target, &checksum, algorithm, false) + .unwrap() + .commit() + .unwrap(); + assert_eq!(digest(&target, algorithm).unwrap(), checksum); + fs::write(&target, b"old destination").unwrap(); + assert_eq!(fs::read(&source).unwrap(), data); + assert!(Import::stage(&source, &target, "bad hash", algorithm, false).is_err()); + assert_eq!(fs::read(&target).unwrap(), b"old destination"); + // Explicitly exercise ordinary streaming copies even on a reflink filesystem. + let streamed = if algorithm == "sha1" { + copy_hash::(&source, &target).unwrap() + } else { + copy_hash::(&source, &target).unwrap() + }; + assert_eq!(streamed, checksum); + assert_eq!(fs::read(&target).unwrap(), data); + } + clone_or_copy(&source, &target).unwrap(); + fs::write(&target, b"rewrite").unwrap(); + assert_eq!(fs::read(&source).unwrap(), data); + let staged = Import::stage( + &source, + &target, + &digest(&source, "sha1").unwrap(), + "sha1", + false, + ) + .unwrap(); + assert_eq!(fs::read_dir(&dir).unwrap().count(), 3); + drop(staged); + assert_eq!(fs::read_dir(&dir).unwrap().count(), 2); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index c7e443c7d..daee30444 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -11,12 +11,14 @@ //! run, keyed by the sha256 of their inputs and outputs recorded in the manifest, as before. pub mod artifacts; +mod files; mod inventory; pub mod java; pub mod pyjson; mod sounds; mod survival; +pub use files::clone_or_copy; pub use sounds::{fonts, languages, packs, panorama, sounds, BUILT_IN_PACKS}; use pyjson::Value; @@ -410,16 +412,28 @@ pub fn prepare(options: &Options, log: Log) -> Result { &artifacts::minecraft_dir(options.minecraft_dir.as_deref()).join("runtime"), )); let jdk = java::find(lock.java_major, &homes)?; - if options.import && !artifacts::reuse_imported(root, log)? { - artifacts::import( - root, - &lock, - options.minecraft_dir.as_deref(), - options.server_jar.as_deref(), - log, - )?; - } - let found = artifacts::verify(&lock)?; + let reused = if options.import { + artifacts::reuse_verified(root, log)? + } else { + None + }; + let (found, client_libraries) = match reused { + Some(checked) => checked, + None => { + if options.import { + artifacts::import( + root, + &lock, + options.minecraft_dir.as_deref(), + options.server_jar.as_deref(), + log, + )?; + } + let found = artifacts::verify(&lock)?; + let libraries = artifacts::client_libraries(&lock, &found.manifest)?; + (found, libraries) + } + }; let local = root.join(".local"); let resources = local.join("horizon-client").join(&lock.version); mkdir(&resources)?; @@ -445,7 +459,6 @@ pub fn prepare(options: &Options, log: Log) -> Result { } else { Value::Object(Vec::new()) }; - let client_libraries = artifacts::client_libraries(&lock, &found.manifest)?; let run = Run { root: root.clone(), local, @@ -679,25 +692,9 @@ fn steps( // and every data-pack resource (worldgen, recipes, loot tables, tags), and // the vanilla pack's icon (`pack.png`) for the pack screen. (run.log)("Copying the client's assets and data"); - let mut count = 0usize; - let mut client = open_zip(&run.client)?; - let version = pyjson::loads(&zip_text(&mut client, "version.json")?)?; - for name in zip_names(&client) { - let wanted = name.starts_with("assets/") || name.starts_with("data/") || name == "pack.png"; - if !wanted || name.ends_with('/') { - continue; - } - let relative = member_path(&name, "Invalid resource path")?; - let data = zip_bytes(&mut client, &name)?; - write_if_changed(&root.join(relative), &data)?; - count += 1; - } - - // The JAR holds only gray 1x1 panorama placeholders and an empty Unifont - // include, and none of the built-in packs. Import the indexed ones afterwards, including on reruns that just - // extracted the JAR again. They are optional when preparing from - // already-imported JARs. - sounds::optional_assets(repo, minecraft, run.log); + let mut indexed = sounds::Assets::load(repo, minecraft, run.log); + let (version, count) = extract_client_resources(&run.client, root, indexed.as_mut().ok())?; + sounds::optional_imports(indexed.as_mut().map_err(|e| e.as_str()), run.log); // One file each, exported again when the exporter or the jar it reads changed. let single = |what: &str, @@ -931,6 +928,54 @@ fn steps( ) } +/// Check existing JAR assets by their ZIP size/CRC without inflating every member again. +/// Indexed panorama/font/language replacements have stronger SHA-1 checks and take precedence. +fn extract_client_resources( + jar: &Path, + root: &Path, + mut indexed: Option<&mut sounds::Assets>, +) -> Result<(Value, usize), String> { + let mut client = open_zip(jar)?; + let version = pyjson::loads(&zip_text(&mut client, "version.json")?)?; + let mut count = 0; + for name in zip_names(&client) { + if !(name.starts_with("assets/") || name.starts_with("data/") || name == "pack.png") + || name.ends_with('/') + { + continue; + } + let relative = member_path(&name, "Invalid resource path")?; + count += 1; + if let Some(assets) = &mut indexed { + if assets.imported(&name)? { + continue; + } + } + let target = root.join(relative); + let member = client.by_name(&name).map_err(|e| e.to_string())?; + let (size, crc) = (member.size(), member.crc32()); + drop(member); + if target.is_file() && fs::metadata(&target).map_err(|e| e.to_string())?.len() == size { + let mut file = fs::File::open(&target).map_err(|e| e.to_string())?; + let mut hash = crc32fast::Hasher::new(); + let mut buffer = [0; 16 * 1024]; + loop { + let n = file.read(&mut buffer).map_err(|e| e.to_string())?; + if n == 0 { + break; + } + hash.update(&buffer[..n]); + } + if hash.finalize() == crc { + continue; + } + } + mkdir(target.parent().unwrap())?; + write(&target, &zip_bytes(&mut client, &name)?)?; + } + Ok((version, count)) +} + fn datagen_reports_missing(root: &Path) -> bool { ["items.json", "registries.json", "commands.json"] .iter() diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index 15d4a7a08..fd171ec12 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -5,7 +5,8 @@ use crate::artifacts::{self, Lock}; use crate::pyjson::Value; -use crate::{digest, read_json, Log}; +use crate::{digest, Log}; +use std::collections::{HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; @@ -18,8 +19,9 @@ fn launcher_assets( lock: &Lock, manifest: &Value, minecraft: &Path, + cached_index: &Path, log: Log, -) -> Result<(PathBuf, PathBuf), String> { +) -> Result<(PathBuf, PathBuf, Vec), String> { let assets = minecraft.join("assets"); let info = manifest .get("assetIndex") @@ -33,7 +35,10 @@ fn launcher_assets( if artifacts::safe_relative(id).is_none_or(|p| p.components().count() != 1) { return Err(format!("Unsafe asset index id {id:?}")); } - let index = assets.join("indexes").join(format!("{id}.json")); + let mut index = assets.join("indexes").join(format!("{id}.json")); + if !index.is_file() && cached_index.is_file() { + index = cached_index.to_path_buf(); + } if !index.is_file() { let version = manifest.get("id").and_then(Value::as_str).unwrap_or(""); return Err(format!( @@ -42,7 +47,8 @@ fn launcher_assets( artifacts::launcher_hint(version) )); } - let checksum = digest(&index, "sha1")?; + let bytes = fs::read(&index).map_err(|e| format!("{}: {e}", index.display()))?; + let checksum = crate::hex(&::digest(&bytes)); if checksum != sha1 && !lock.asset_index_accepted(&checksum) { log(&format!( "{} is an asset index Horizon does not know yet (sha1 {checksum}); Mojang may have \ @@ -50,7 +56,7 @@ fn launcher_assets( index.display() )); } - Ok((assets, index)) + Ok((assets, index, bytes)) } /// Where the launcher's asset store keeps the object with this SHA-1. @@ -61,24 +67,6 @@ fn object_path(assets: &Path, checksum: &str) -> Result { Ok(assets.join("objects").join(&checksum[..2]).join(checksum)) } -/// One verified object from the launcher's asset store (tools/lab.py `launcher_object`). -fn launcher_object(assets: &Path, checksum: &str) -> Result { - let path = object_path(assets, checksum)?; - if !path.is_file() { - return Err(format!( - "Missing asset object {}. Play the pinned version once in your launcher.", - path.display() - )); - } - if digest(&path, "sha1")? != checksum { - return Err(format!( - "Corrupt asset object {}; let the launcher repair it", - path.display() - )); - } - Ok(path) -} - /// Whether the game plays this asset: sounds.json and everything under sounds/. fn is_sound(name: &str) -> bool { name == "minecraft/sounds.json" || name.starts_with("minecraft/sounds/") @@ -127,26 +115,56 @@ fn is_language(name: &str) -> bool { } /// Full preparation can run from cached JARs without an official launcher install. -pub(crate) fn optional_assets(root: &Path, minecraft: Option<&Path>, log: Log) { - if let Err(error) = panorama(root, minecraft, log) { - log(&format!( - "Title panorama not imported: {error}; run horizon-prepare panorama later" - )); - } - if let Err(error) = fonts(root, minecraft, log) { - log(&format!( - "Unifont glyphs not imported: {error}; run horizon-prepare fonts later" - )); - } - if let Err(error) = packs(root, minecraft, log) { - log(&format!( - "Programmer Art and High Contrast not imported: {error}; run horizon-prepare packs later" - )); - } - if let Err(error) = languages(root, minecraft, log) { - log(&format!( - "Languages not imported: {error}; run horizon-prepare languages later" - )); +#[cfg(test)] +fn optional_assets(root: &Path, minecraft: Option<&Path>, log: Log) { + optional_imports( + Assets::load(root, minecraft, log) + .as_mut() + .map_err(|e| e.as_str()), + log, + ); +} + +pub(crate) fn optional_imports(mut assets: Result<&mut Assets, &str>, log: Log) { + for (wanted, label, required, failure, command) in [ + ( + is_panorama as fn(&str) -> bool, + "Panorama", + PANORAMA.as_slice(), + "Title panorama", + "panorama", + ), + ( + is_font, + "Font", + UNIFONT.as_slice(), + "Unifont glyphs", + "fonts", + ), + ( + is_built_in_pack, + "Built-in pack", + BUILT_IN_PACKS.as_slice(), + "Programmer Art and High Contrast", + "packs", + ), + ( + is_language, + "Language", + LANGUAGES.as_slice(), + "Languages", + "languages", + ), + ] { + let result = match &mut assets { + Ok(assets) => assets.copy(wanted, label, required, log).map(|_| ()), + Err(error) => Err(error.to_string()), + }; + if let Err(error) = result { + log(&format!( + "{failure} not imported: {error}; run horizon-prepare {command} later" + )); + } } } @@ -207,29 +225,98 @@ fn copy_assets( label: &str, required: &[&str], ) -> Result { - let lock = Lock::read(root)?; - let minecraft = artifacts::minecraft_dir(minecraft); - let manifest = artifacts::import_manifest(&lock, &minecraft)?; - let (store, index) = launcher_assets(&lock, &manifest, &minecraft, log)?; - let id = manifest - .get("id") - .and_then(Value::as_str) - .ok_or("The version JSON has no id")?; - let target = root.join(".local/horizon-client").join(id); - fs::create_dir_all(&target).map_err(|e| format!("{}: {e}", target.display()))?; - fs::copy(&index, target.join("asset-index.json")) - .map_err(|e| format!("{}: {e}", target.join("asset-index.json").display()))?; - let objects = read_json(&index)?; - let objects = objects - .get("objects") - .and_then(Value::as_object) - .ok_or_else(|| format!("{} has no objects", index.display()))?; + Assets::load(root, minecraft, log)?.copy(wanted_asset, label, required, log) +} + +/// A preparation's index and verified destinations. Never persisted: a later invocation +/// checks the bytes again, including when repairing a corrupt prepared file. +pub(crate) struct Assets { + store: PathBuf, + target: PathBuf, + objects: Vec<(String, Value)>, + verified: HashSet, +} + +impl Assets { + pub(crate) fn load(root: &Path, minecraft: Option<&Path>, log: Log) -> Result { + let lock = Lock::read(root)?; + let minecraft = artifacts::minecraft_dir(minecraft); + let manifest = artifacts::import_manifest(&lock, &minecraft)?; + let target = root.join(".local/horizon-client").join(&lock.version); + let (store, index, bytes) = launcher_assets( + &lock, + &manifest, + &minecraft, + &target.join("asset-index.json"), + log, + )?; + let text = std::str::from_utf8(&bytes).map_err(|e| e.to_string())?; + let objects = crate::pyjson::loads(text)?; + let objects = objects + .get("objects") + .and_then(Value::as_object) + .ok_or_else(|| format!("{} has no objects", index.display()))? + .to_vec(); + fs::create_dir_all(&target).map_err(|e| e.to_string())?; + crate::write_if_changed(&target.join("asset-index.json"), &bytes)?; + Ok(Self { + store, + target, + objects, + verified: HashSet::new(), + }) + } + + /// Preserve indexed replacements instead of overwriting them with JAR placeholders. + pub(crate) fn imported(&mut self, name: &str) -> Result { + let Some(name) = name.strip_prefix("assets/") else { + return Ok(false); + }; + if !(is_panorama(name) || is_font(name) || is_language(name)) { + return Ok(false); + } + let Some((_, info)) = self.objects.iter().rev().find(|(n, _)| n == name) else { + return Ok(false); + }; + let Some(hash) = info.get("hash").and_then(Value::as_str) else { + return Ok(false); + }; + let destination = self.target.join("assets").join(name); + if destination.is_file() && digest(&destination, "sha1")? == hash { + self.verified.insert(destination); + return Ok(true); + } + Ok(false) + } + + fn copy( + &mut self, + wanted_asset: fn(&str) -> bool, + label: &str, + required: &[&str], + log: Log, + ) -> Result { + copy_indexed(self, wanted_asset, label, required, log) + } +} + +fn copy_indexed( + assets: &mut Assets, + wanted_asset: fn(&str) -> bool, + label: &str, + required: &[&str], + log: Log, +) -> Result { + let objects = &assets.objects; // A repeated name keeps its first place and its last value, as a Python dict does. let mut wanted: Vec<(&str, &Value)> = Vec::new(); + let mut positions = HashMap::new(); for (name, info) in objects.iter().filter(|(name, _)| wanted_asset(name)) { - match wanted.iter_mut().find(|(n, _)| n == name) { - Some(entry) => entry.1 = info, - None => wanted.push((name, info)), + if let Some(&position) = positions.get(name.as_str()) { + wanted[position] = (name.as_str(), info); + } else { + positions.insert(name.as_str(), wanted.len()); + wanted.push((name, info)); } } for name in required { @@ -251,21 +338,45 @@ fn copy_assets( .ok_or_else(|| format!("{name} has no size in the asset index"))?; let relative = artifacts::safe_relative(name) .ok_or_else(|| format!("Unsafe asset name {name:?} in the asset index"))?; - let source = launcher_object(&store, hash)?; - copies.push((source, target.join("assets").join(relative), hash)); + let source = object_path(&assets.store, hash)?; + let destination = assets.target.join("assets").join(relative); + let import = crate::files::Import::stage( + &source, + &destination, + hash, + "sha1", + assets.verified.contains(&destination), + ) + .map_err(|error| { + if !source.is_file() { + format!( + "Missing asset object {}. Play the pinned version once in your launcher.", + source.display() + ) + } else if error.contains(" is not the pinned file:") { + format!( + "Corrupt asset object {}; let the launcher repair it: {error}", + source.display() + ) + } else { + error + } + })?; + copies.push((import, destination)); total += size; } // Check the entire set before replacing any placeholders: a missing late face // must not leave a mixture of real textures and gray faces in either entry point. - for (source, destination, hash) in copies { - artifacts::import_copy(&source, &destination, hash, "sha1", "")?; + for (import, destination) in copies { + import.commit()?; + assets.verified.insert(destination); } log(&format!( "{label} assets ready: {} files, {:.1} MB", wanted.len(), total as f64 / 1e6 )); - Ok(target) + Ok(assets.target.clone()) } #[cfg(test)] @@ -680,6 +791,7 @@ mod tests { "minecraft/sounds.json is missing from the asset index" ); fs::remove_file(&index).unwrap(); + fs::remove_file(f.root.join(".local/horizon-client/9.9/asset-index.json")).unwrap(); let error = f.run().unwrap_err(); assert!( error.starts_with("Missing ") && error.contains("play 9.9 once"), @@ -687,6 +799,120 @@ mod tests { ); } + #[test] + fn late_corruption_discards_all_staged_replacements() { + let f = Fixture::new("late-corruption"); + let target = f.root.join(".local/horizon-client/9.9/assets"); + for name in PANORAMA { + let path = target.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"placeholder").unwrap(); + } + fs::write(f.object(FIRST_FACE + 6), b"bad overlay").unwrap(); + assert!(panorama(&f.root, Some(&f.minecraft), &|_| {}).is_err()); + for name in PANORAMA { + assert_eq!(fs::read(target.join(name)).unwrap(), b"placeholder"); + } + assert_eq!( + fs::read_dir(target.join("minecraft/textures/gui/title/background")) + .unwrap() + .count(), + 7 + ); + } + + #[test] + fn one_index_snapshot_serves_every_import_and_reruns_repair_corruption() { + let f = Fixture::with_extras("snapshot", &PANORAMA, &[("pack.mcmeta", b"{}")]); + let mut assets = Assets::load(&f.root, Some(&f.minecraft), &|_| {}).unwrap(); + fs::remove_file(f.minecraft.join("assets/indexes/7.json")).unwrap(); + let lines = std::cell::RefCell::new(Vec::new()); + optional_imports(Ok(&mut assets), &|line| { + lines.borrow_mut().push(line.to_string()) + }); + assert_eq!(lines.borrow().len(), 4); + assert!(lines + .borrow() + .iter() + .all(|line| line.contains("assets ready"))); + assets + .copy(is_sound, "Sound", &["minecraft/sounds.json"], &|_| {}) + .unwrap(); + let sound = assets + .target + .join("assets/minecraft/sounds/ambient/cave1.ogg"); + let time = fs::metadata(&sound).unwrap().modified().unwrap(); + fs::remove_file(f.object(1)).unwrap(); + f.run().unwrap(); // A verified destination works even without the source object/index. + assert_eq!(fs::metadata(&sound).unwrap().modified().unwrap(), time); + fs::write(&sound, b"corrupt").unwrap(); + assert!(f.run().is_err()); // Verification never carries over to another invocation. + fs::write(f.object(1), &f.objects[1].1).unwrap(); + f.run().unwrap(); + assert_eq!(fs::read(sound).unwrap(), f.objects[1].1); + } + + #[test] + fn jar_reruns_preserve_indexed_assets_and_repair_missing_or_corrupt_members() { + use std::io::Write; + let f = Fixture::with_extras( + "extract", + &PANORAMA, + &[ + ("pack.mcmeta", b"{}"), + ("minecraft/lang/en_us.json", b"{\"indexed\":true}"), + ], + ); + optional_assets(&f.root, Some(&f.minecraft), &|_| {}); + let target = f.root.join(".local/horizon-client/9.9"); + let jar = f.root.join("client.jar"); + let mut zip = zip::ZipWriter::new(fs::File::create(&jar).unwrap()); + for (name, data) in [ + ("version.json", "{\"world_version\": 1}"), + ( + "assets/minecraft/textures/gui/title/background/panorama_0.png", + "gray", + ), + ("assets/minecraft/font/include/unifont.json", "{}"), + ("assets/minecraft/lang/en_us.json", "{}"), + ("data/minecraft/test.json", "data"), + ("pack.png", "icon"), + ] { + zip.start_file(name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(data.as_bytes()).unwrap(); + } + zip.finish().unwrap(); + let face = target.join("assets").join(PANORAMA[0]); + let time = fs::metadata(&face).unwrap().modified().unwrap(); + // Preparing from cached JARs must also preserve full imports without the launcher. + fs::remove_dir_all(f.minecraft.join("assets")).unwrap(); + for _ in 0..2 { + let mut assets = Assets::load(&f.root, Some(&f.minecraft), &|_| {}).unwrap(); + let (_, count) = + crate::extract_client_resources(&jar, &target, Some(&mut assets)).unwrap(); + assert_eq!(count, 5); + optional_imports(Ok(&mut assets), &|_| {}); + assert_eq!(fs::read(&face).unwrap(), PANORAMA[0].as_bytes()); + assert_eq!(fs::metadata(&face).unwrap().modified().unwrap(), time); + assert_eq!( + fs::read(target.join("assets").join(UNIFONT[0])).unwrap(), + f.objects[4].1 + ); + assert_eq!( + fs::read(target.join("assets/minecraft/lang/en_us.json")).unwrap(), + b"{\"indexed\":true}" + ); + assert_eq!( + fs::read(target.join("data/minecraft/test.json")).unwrap(), + b"data" + ); + assert_eq!(fs::read(target.join("pack.png")).unwrap(), b"icon"); + fs::write(target.join("data/minecraft/test.json"), b"oops").unwrap(); + fs::remove_file(target.join("pack.png")).unwrap(); + } + } + #[test] fn object_paths_come_from_real_hashes() { let store = Path::new("assets"); diff --git a/docs/prepare-performance.md b/docs/prepare-performance.md new file mode 100644 index 000000000..3a3587111 --- /dev/null +++ b/docs/prepare-performance.md @@ -0,0 +1,44 @@ +# Resource preparation and filesystem work + +The reported preparation timings put sounds at 20–29 seconds with little CPU use, versus +0.9–1.4 seconds for fresh client asset extraction. Prefer fewer file opens, reads and writes +over parallelizing decompression. + +Preparation now shares one parsed asset index between panorama, font, pack and language imports. +Its destination verification results live only for that preparation. A subsequent invocation +checks bytes again, so it can repair corrupt resources. Existing valid destination files do not +require the original asset objects to remain installed. A saved asset index also lets preparation +preserve full imports when only cached Minecraft JARs remain. + +New imports are staged beside their destination. On Linux, FICLONE is attempted first; other +filesystems fall back to copying while hashing. Cloned copies are hashed before publication. +macOS attempts clonefile with the same checked streaming fallback. A whole asset group is staged and +verified before any replacement is published; corrupt late panorama faces leave placeholders +alone. Temporary files are cleaned up on errors. This is not a transaction for rename failures +or process termination during publication: a later run repairs incomplete groups. + +Unchanged JAR resources are checked by the ZIP member's size and CRC, avoiding repeated +decompression. Valid indexed replacements take precedence over JAR placeholders. Reusing checked +Minecraft imports also passes the verified artifact/library results directly to the exporters. + +## An immutable store across releases + +The official launcher's SHA-1 object store already provides an immutable source for indexed +assets. Independent filesystem clones let installed Horizon releases share physical blocks +where supported, without sharing writable inodes. Ordinary copies remain the fallback. + +A separate Horizon store could additionally share complete preparations on filesystems without +cloning. Its key would need the pinned client/server hashes, the preparer's output version (or +the legacy source/exporter fingerprint), and the actual asset-index digest: Mojang republishes +translations without changing the Minecraft release. Two preparations with different optional +asset availability must not claim the same complete snapshot. + +Before adopting that store, separate immutable runtime resources from mutable exporter scratch, +classes and logs. Publish snapshots through a temporary directory and atomic rename, give each +release an explicit reference, and define locking, corruption repair, migration and garbage +collection. Exporters must never receive a shared writable directory or hard-linked files. +The existing launcher compatibility check should choose reuse; the store should only supply its +bytes. Keep this separate from the open work on output-version compatibility (#1946/#1947). + +For now, retain independent release directories and clone their resource files. This reduces +copying where the filesystem supports it without introducing a second ownership/cleanup scheme. diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 1e8a5aee2..ee0cb882a 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2726,6 +2726,8 @@ dependencies = [ name = "horizon-prepare" version = "0.1.0" dependencies = [ + "crc32fast", + "libc", "regex", "sha1", "sha2 0.10.9", diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 7e5c4babb..dadef73d3 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -719,7 +719,7 @@ fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> { if entry.file_type()?.is_dir() { copy_dir(&entry.path(), &target)?; } else { - fs::copy(entry.path(), target)?; + horizon_prepare::clone_or_copy(&entry.path(), &target)?; } } Ok(()) From 5e9d45bc9afe0bf91feb22e49a5232cb00f38287 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:11:39 +0100 Subject: [PATCH 31/43] /pregen: off unless the server turns it on Vanilla has no /pregen, so with it always registered /help and the command tree differed from vanilla's (the command_exec harness failed on /help). Horizon's own commands are now added to the game's tree only when the owner asks: `horizon-pregen=true` in server.properties (`horizon-pregen = true` under [properties] in server.toml) for a dedicated server, `--pregen` for the game (single player, LAN). Off, the trees are vanilla's own, unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/command/tests.rs | 18 ++++++++ crates/horizon-client/src/command/vanilla.rs | 45 ++++++++++++++------ crates/horizon-client/src/game.rs | 4 +- crates/horizon-client/src/game/dedicated.rs | 8 ++++ docs/hosting.md | 5 ++- docs/pregeneration.md | 6 +++ 6 files changed, 70 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index 2bdea1aba..d61fd8ae1 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -592,3 +592,21 @@ fn mod_commands_join_the_tree_for_every_player() { // The game's own tree is left as it was. assert!(vanilla::game_dispatcher().find("where").is_none()); } + +#[test] +fn horizon_commands_are_off_unless_the_server_turns_them_on() { + // By default the game runs vanilla's tree: /help lists no /pregen. + assert!(vanilla::game_dispatcher().find("pregen").is_none()); + for dev in [false, true] { + let vanilla_tree = vanilla::game_tree(dev, false); + assert!(vanilla_tree.find("pregen").is_none()); + let d = vanilla::game_tree(dev, true); + let parse = d.parse("pregen start 100 circle", ®()); + assert_eq!(parse.executable().unwrap().1, "pregen.start"); + // Vanilla's commands are the same with or without it. + assert_eq!( + d.nodes[0].children.len(), + vanilla_tree.nodes[0].children.len() + 1 + ); + } +} diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index cba5a5d5b..2ce892077 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -538,20 +538,39 @@ fn apply_vanilla_order(d: &mut Dispatcher) { } /// The tree the game runs: a release integrated server's, or with /// `HORIZON_DEV_COMMANDS` set the development one -/// (SharedConstants.DEBUG_DEV_COMMANDS), plus Horizon's own commands. +/// (SharedConstants.DEBUG_DEV_COMMANDS), plus Horizon's own commands when +/// the server turned them on (`set_horizon_commands`). pub fn game_dispatcher() -> &'static Dispatcher { - static DEV: std::sync::OnceLock = std::sync::OnceLock::new(); - static RELEASE: std::sync::OnceLock = std::sync::OnceLock::new(); - let (tree, dev) = if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() { - (&DEV, true) - } else { - (&RELEASE, false) - }; - tree.get_or_init(|| { - let mut d = build_with(dev); - horizon_commands(&mut d, 0); - d - }) + game_tree( + std::env::var_os("HORIZON_DEV_COMMANDS").is_some(), + HORIZON_COMMANDS.load(std::sync::atomic::Ordering::Relaxed), + ) +} +/// Whether this process's server has Horizon's own commands (`/pregen`). Off +/// by default, so `/help` and the command tree are vanilla's; a dedicated +/// server turns them on with `horizon-pregen=true` in server.properties, the +/// game with `--pregen` (docs/pregeneration.md). +static HORIZON_COMMANDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// Turns Horizon's own commands on or off for the trees `game_dispatcher` +/// returns from now on. +pub fn set_horizon_commands(on: bool) { + HORIZON_COMMANDS.store(on, std::sync::atomic::Ordering::Relaxed); +} +/// The server.properties key that turns `/pregen` on (Horizon's own; vanilla +/// ignores keys it doesn't know). +pub const PREGEN_PROPERTY: &str = "horizon-pregen"; +pub(crate) fn game_tree(dev: bool, horizon: bool) -> &'static Dispatcher { + static HORIZON: [std::sync::OnceLock; 2] = + [const { std::sync::OnceLock::new() }; 2]; + match (dev, horizon) { + (true, false) => dispatcher(), + (false, false) => release_dispatcher(), + (dev, true) => HORIZON[usize::from(dev)].get_or_init(|| { + let mut d = build_with(dev); + horizon_commands(&mut d, 0); + d + }), + } } /// Commands vanilla doesn't have, after its own: `/pregen` /// (docs/pregeneration.md). diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index fa00e3804..08e1ff68b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -360,7 +360,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", + "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", horizon_core::VANILLA_VERSION ); return Ok(None); @@ -377,6 +377,8 @@ impl Options { "--control" => o.control = Some(horizon_client::control::default_path()), "--server-thread" => o.server_thread = true, "--in-frame" | "--no-server-thread" => o.server_thread = false, + // Horizon's own commands (/pregen), off by default as on vanilla. + "--pregen" => horizon_client::command::vanilla::set_horizon_commands(true), _ => { let value = args .next() diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index edea0e800..fa5365195 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -155,6 +155,14 @@ pub(super) fn preflight(options: &mut Options) -> Result { for w in &props.warnings { log("WARN", w); } + // Horizon's own commands are the owner's choice, off as on vanilla. + if props + .raw + .get(horizon_client::command::vanilla::PREGEN_PROPERTY) + .is_some_and(|v| v.trim().eq_ignore_ascii_case("true")) + { + horizon_client::command::vanilla::set_horizon_commands(true); + } props.store(&settings)?; let eula_file = PathBuf::from("eula.txt"); let agreed = match eula::agreed(&eula_file) { diff --git a/docs/hosting.md b/docs/hosting.md index 4c4c954bc..a9624dc2c 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -218,8 +218,9 @@ horizon-server rollback back to the release before While the server runs, `op`, `whitelist` and `cmd` go to the game's console, so they act exactly as vanilla's console commands do. While it's stopped, they edit vanilla's files directly. Any console command works through `cmd`: `horizon-server cmd ban Griefer`, `horizon-server cmd say Restarting in 5 minutes`. -To generate the world around spawn ahead of the players, Horizon has its own `pregen` command: -`horizon-server cmd pregen start 2500` ([pregeneration](pregeneration.md)). +To generate the world around spawn ahead of the players, Horizon has its own `pregen` command, off until +`server.toml` has `horizon-pregen = true` under `[properties]`: `horizon-server cmd pregen start 2500` +([pregeneration](pregeneration.md)). `config set` changes `server.toml` without opening it: `horizon-server config set world.difficulty=hard server.max_players=10`. Each key is a section and a name from the file (`properties.spawn-protection=0` for any diff --git a/docs/pregeneration.md b/docs/pregeneration.md index a8ca228b3..706527661 100644 --- a/docs/pregeneration.md +++ b/docs/pregeneration.md @@ -5,6 +5,12 @@ Chunky does on a Java server. It is Horizon's own command (vanilla has none), av with cheats on and to operators (level 2) on a server, from the chat or the server console (`horizon-server cmd pregen start 2500`). +It is off until you turn it on, so `/help` and the command tree stay vanilla's: + +- a server: `horizon-pregen = true` under `[properties]` in `server.toml` (or `horizon-pregen=true` in a + vanilla folder's `server.properties`), then restart it; +- single player and LAN: start the game with `--pregen`. + ```text /pregen start [square|circle] [ ] radius in blocks; the centre defaults to where you stand (the world spawn from the console) From 21d8e530346f3e05c0256e2c085bceb0103f823d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:14:51 +0100 Subject: [PATCH 32/43] parity: pick harnesses by the Rust items their probes reach, not whole crates `--changed` / `--changed-files` now narrow each harness's recorded Rust sources to those its probes can reach (tools/parity_reach.py): an item-level reachability walk from the probe modules a harness ran (or the binary it built) over free items, inherent methods, trait impls and macros, matched by name so it only over-approximates. Parent modules count through their `mod` declarations, compared with the merge base. A harness whose probe can't be placed keeps every source; `--by-crate` turns the narrowing off. On the last 20 PRs merged on 2026-10-25: 2255 -> 1061 harnesses picked, 2384 -> 1592 harness-minutes. Replaying the week's 61 failed CI parity runs, every failed harness the old selection picked is still picked; LLVM coverage of six harnesses' probes executes only kept files. Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 4 + tests/test_parity_reach.py | 111 ++++++ tools/parity.py | 49 ++- tools/parity_reach.py | 768 +++++++++++++++++++++++++++++++++++++ 4 files changed, 925 insertions(+), 7 deletions(-) create mode 100644 tests/test_parity_reach.py create mode 100644 tools/parity_reach.py diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index f9f222071..d794b9c71 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -49,6 +49,10 @@ A harness can declare, at the top level of its script: - `PARITY_SHARDS = N`: it runs as `NAME#1` to `NAME#N`, in parallel, each told its share in `PARITY_SHARD=i/N` (`test_datafix_parity.py` upgrades every sixth world). `NAME` on the command line or in `--known-failures` means all of them. - `PARITY_RUST_SCOPE = [...]`: the Rust sources its probes can reach, as path prefixes. Cargo's dep-info names every file of every crate a probe links, so without it a probe of `horizon-world` depends on all 350 of its files. The runner keeps only the scope's files if the scope is closed: nothing in it names a module, crate-root re-export or macro outside it (`crate::`, `super::`, other workspace crates; comments and strings ignored), declares a module it doesn't cover, or includes source, and nothing outside it implements anything for a type it defines. Crate roots then count without their declarations of other modules, so adding a module elsewhere doesn't rerun the harness. If the scope isn't closed the runner says why and keeps every file. `datafix` depends on 41 files this way, not 354. +### Which harnesses a change affects + +`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `.local/parity-runner/reach-cache.json`. `--by-crate` turns the narrowing off. On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. + ## The gate `tools/gate.py` is what a branch must pass before it is integrated: the public-tree check, rustfmt, clippy with warnings denied, the Rust and Python tests, then the harnesses whose inputs changed. It stops at the first failure and writes `.local/gate.json`. `--known-failures a,b` lets harnesses that already fail on the integration branch keep failing. `--quick` checks formatting, lints and Python tests only; `--no-parity` skips the harnesses. diff --git a/tests/test_parity_reach.py b/tests/test_parity_reach.py new file mode 100644 index 000000000..9b7464b47 --- /dev/null +++ b/tests/test_parity_reach.py @@ -0,0 +1,111 @@ +"""tools/parity_reach.py: which workspace sources a harness's probe can reach.""" +from pathlib import Path +import tempfile +import textwrap +import unittest + +from tools import parity, parity_reach + +PROBE = [["example", "world_probe", "release", ["-p", "a"], True]] + + +def workspace(root, files): + for path, text in files.items(): + (root / path).parent.mkdir(parents=True, exist_ok=True) + (root / path).write_text(textwrap.dedent(text), encoding="utf-8") + + +class ReachTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) + workspace(self.root, { + "crates/a/Cargo.toml": '[package]\nname = "a"\n\n[[example]]\nname = "world_probe"\npath = "examples/probe/main.rs"\n', + "crates/a/src/lib.rs": """ + pub mod used; + pub mod unused; + mod methods; + mod display; + mod table; + #[cfg(test)] + mod tests; + """, + "crates/a/src/used.rs": """ + pub struct Thing; + pub fn helper() -> u32 { 1 } + """, + # Same names as used.rs, but nothing names this module. + "crates/a/src/unused.rs": "pub struct Thing;\npub fn helper() -> u32 { 2 }\n", + "crates/a/src/methods.rs": """ + use crate::used::Thing; + impl Thing { + pub fn method(&self) -> u32 { 3 } + pub fn never_called(&self) -> u32 { 4 } + } + """, + "crates/a/src/display.rs": """ + impl std::fmt::Display for crate::used::Thing { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "thing") } + } + """, + "crates/a/src/table.rs": """ + macro_rules! table { () => { pub struct Table; }; } + table!(); + """, + "crates/a/src/tests.rs": "use crate::used::Thing;\nimpl Thing { pub fn method_in_tests(&self) {} }\n", + "crates/a/examples/probe/main.rs": "mod dispatch;\nmod p;\n", + "crates/a/examples/probe/dispatch.rs": "pub fn args() {}\n", + "crates/a/examples/probe/p.rs": """ + use a::used::{helper, Thing}; + pub fn main() { println!("{} {} {}", helper(), Thing.method(), Thing); } + """, + }) + self.dependencies = sorted(str(path.relative_to(self.root)) for path in self.root.rglob("*") if path.is_file()) + self.dependencies.remove("crates/a/examples/probe/main.rs") # parity.only_probes_run leaves it out + + def tearDown(self): + self.directory.cleanup() + + def narrowed(self, changed=(), artifacts=PROBE): + graph = parity_reach.SourceGraph(self.root, parity.rust_code) + return parity_reach.narrow(self.dependencies, artifacts, graph, set(changed)) + + def test_keeps_what_the_probe_reaches(self): + kept = {path for path, (whole, _) in self.narrowed().items() if whole} + self.assertIn("crates/a/src/used.rs", kept) + self.assertIn("crates/a/src/methods.rs", kept) # Thing.method() + self.assertIn("crates/a/src/display.rs", kept) # std's Display for a reached type + self.assertIn("crates/a/Cargo.toml", kept) + self.assertNotIn("crates/a/src/unused.rs", kept) # its names match, but nothing names its module + self.assertNotIn("crates/a/src/table.rs", kept) + self.assertNotIn("crates/a/src/tests.rs", kept) # compiled into tests only + + def test_module_parents_count_through_their_declarations(self): + self.assertEqual(self.narrowed()["crates/a/src/lib.rs"], (False, {"used", "methods", "display"})) + text = (self.root / "crates/a/src/lib.rs").read_text() + self.assertEqual(parity_reach.declarations(text, {"used"}, False), "pub mod used;") + self.assertEqual(parity_reach.declarations(text, {"tests"}, False), "#[cfg(test)]\nmod tests;") + # Adding or dropping a module beside the reached ones changes neither view. + other = text.replace("mod table;", "mod table2;\nmod more;") + self.assertEqual(parity_reach.declarations(other, {"used"}, False), "pub mod used;") + self.assertEqual(parity_reach.declarations(other, {"used"}, True), parity_reach.declarations(text, {"used"}, True)) + self.assertNotEqual(parity_reach.declarations(text + "pub fn f() {}\n", {"used"}, True), + parity_reach.declarations(text, {"used"}, True)) + + def test_a_new_file_counts_once_it_is_reached(self): + (self.root / "crates/a/src/lib.rs").write_text("pub mod used;\nmod extra;\n") + workspace(self.root, {"crates/a/src/extra.rs": "impl crate::used::Thing { pub fn method(&self) -> u32 { 5 } }\n"}) + self.assertIn("crates/a/src/extra.rs", self.narrowed(changed={"crates/a/src/extra.rs"})) + + def test_a_deleted_dependency_counts(self): + (self.root / "crates/a/src/unused.rs").unlink() + self.assertIn("crates/a/src/unused.rs", self.narrowed()) + + def test_unknown_probes_keep_everything(self): + self.assertEqual(set(self.narrowed(artifacts=[])), set(self.dependencies)) + self.assertEqual(set(self.narrowed(artifacts=[["example", "missing", "release", ["-p", "a"], True]])), + set(self.dependencies)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/parity.py b/tools/parity.py index 503a5f3bf..dc5fdb1c9 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -45,6 +45,11 @@ import subprocess import sys import time +try: + from . import parity_reach +except ImportError: + import parity_reach + ROOT = Path(__file__).resolve().parents[1] LOCAL = ROOT / ".local" STATE_DIR = LOCAL / "parity-runner" @@ -1224,20 +1229,44 @@ def changed_harnesses(found, records, ref): return found_changed -def affected_harnesses(found, records, changed): +def affected_harnesses(found, records, changed, reach=True, base=None): """Harnesses the changed files can affect: their script or a recorded dependency (here, or in the shared - dependency lists) changed, a file every harness depends on changed, or nothing is recorded about them yet.""" + dependency lists) changed, a file every harness depends on changed, or nothing is recorded about them yet. + With reach, a harness's workspace Rust sources count only if its probes can reach them (tools/parity_reach.py); + a harness whose probes can't be placed keeps them all. A changed file counts unless, compared with base (a + commit), only declarations of modules the harness doesn't reach changed (tools/parity_reach.py).""" if changed & SHARED_INPUTS: return set(found) + graph = None + if reach and any(path.startswith("crates/") for path in changed): + cache_path = STATE_DIR / "reach-cache.json" + try: + cache = json.loads(cache_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + cache = {} + graph = parity_reach.SourceGraph(ROOT, rust_code, cache) affected = set() for name, script in found.items(): - dependencies = records.get(name, {}).get("dependencies") + record = records.get(name) or {} + dependencies = record.get("dependencies") template = SHARED / "dependencies" / f"{name}.json" if dependencies is None and template.exists(): - dependencies = json.loads(template.read_text(encoding="utf-8")).get("dependencies") - if dependencies is None or Path(script).relative_to(ROOT).as_posix() in changed or \ - any(path.split(KEEP)[0] in changed for path in dependencies): + record = json.loads(template.read_text(encoding="utf-8")) + dependencies = record.get("dependencies") + if dependencies is None or Path(script).relative_to(ROOT).as_posix() in changed: affected.add(name) + continue + plain = {path.split(KEEP)[0] for path in dependencies} + if graph is not None and plain & changed: + narrowed = parity_reach.narrow(dependencies, recorded_artifacts(record), graph, changed) + if any(path.split(KEEP)[0] in changed and (children is None or parity_reach.declarations_changed( + ROOT, path.split(KEEP)[0], children, base, whole)) for path, (whole, children) in narrowed.items()): + affected.add(name) + elif plain & changed: + affected.add(name) + if graph is not None: + STATE_DIR.mkdir(parents=True, exist_ok=True) + cache_path.write_text(json.dumps(graph.saved_cache()), encoding="utf-8") return affected @@ -1280,6 +1309,8 @@ def main(): parser.add_argument("--flake-rounds", type=int, default=3, help="runs required by --flake-check (default 3)") parser.add_argument("--changed", metavar="REF", help="only harnesses the changes since the merge base with REF can " "affect (and that have not passed with their current inputs): the pull-request check") + parser.add_argument("--by-crate", action="store_true", help="with --changed: count every Rust source a probe " + "links, not only those it can reach (tools/parity_reach.py)") parser.add_argument("--changed-files", metavar="FILE", help="like --changed, for the changed paths listed in FILE, " "one per line: for a copy without Git history (tools/pr_ready.py on another machine)") args = parser.parse_args() @@ -1316,7 +1347,11 @@ def main(): changed, since = changed_files(args.changed), f" since the merge base with {args.changed}" if changed is None: parser.error(f"no merge base with {args.changed}") - affected = affected_harnesses(found, records, changed) + base = None + if args.changed: + merge_base = subprocess.run(["git", "merge-base", "HEAD", args.changed], cwd=ROOT, capture_output=True, text=True) + base = merge_base.stdout.strip() or None + affected = affected_harnesses(found, records, changed, reach=not args.by_crate, base=base) chosen = [name for name in found if name in affected and stale(name, state, hasher, environment)] print(f"{len(changed)} files changed{since}: {len(affected)} harnesses " f"depend on them, {len(chosen)} without a pass for their current inputs.", flush=True) diff --git a/tools/parity_reach.py b/tools/parity_reach.py new file mode 100644 index 000000000..0c3051b86 --- /dev/null +++ b/tools/parity_reach.py @@ -0,0 +1,768 @@ +"""Which of a harness's Rust sources its probes can reach, for `parity.py --changed`. + +Cargo's dep-info names every source file of every crate a probe links, so a change anywhere in horizon-client +selected every harness whose probe links horizon-client. This module narrows a harness's recorded dependencies to +the files holding an item its entry points (the probe modules it ran, the binaries it built) can reach, over a graph +of the workspace's current sources whose nodes are items: + +- everything in an entry is reached, and so is everything in a Rust file the module tree doesn't place (an + `include!`d source); +- a module is open when it is a crate root, holds reached code, or is named in a path (`name::`, `use ...name`) by + reached code while its parent is open; +- a free item (fn, struct, enum, union, trait, type, const, static, an item-level macro call's items) is reached when + reached code in its own module or below it mentions its name, or when its module is open and reached code names + it in a path or an import, or when its module is glob-imported (`use m::*`) and its name is mentioned; +- an inherent impl's methods and constants are reached one by one, by name, once their type is; a trait impl once + its trait and its type are (a std or outside name always is, a generic parameter needs nothing); a macro once + invoked; a `pub use` like a free item named by everything it imports; +- "a crate's reached code" covers the crates it names (`horizon_world::`), directly or through one that does, and + code under `#[cfg(test)]` or `#[test]` is left out (probes are never test builds). + +Names match by spelling, so a file can be kept for a name it never meant: the graph only over-approximates. A +reached file's parent modules count through their `mod` declarations of it (parity.py compares those with the merge +base). Everything that isn't a workspace Rust source stays a dependency, except a crate's non-Rust files (shaders, +assets, fonts) that only unreached sources name; a dependency that no longer exists counts as changed, and Rust files +a change adds take part. +""" + +import hashlib +from pathlib import Path, PurePosixPath +import re +import subprocess + +IDENT = r"[A-Za-z_]\w*" +WORD = re.compile(rf"\b({IDENT})\b") +MOD_DECLARATION = re.compile(rf"\bmod\s+({IDENT})\s*;") +INLINE_MOD = re.compile(rf"\bmod\s+({IDENT})\s*\{{") +PATH_ATTRIBUTE = re.compile(r'#\[\s*path\s*=\s*"([^"]+)"\s*\]\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*;$') +BRACE = re.compile(r"[{}]") +TEST_ONLY = re.compile(r"#\[\s*(?:cfg\s*\(\s*test\s*\)|test)\s*\]") +TEST_MODULE = re.compile(r"#\[\s*cfg\s*\(\s*test\s*\)\s*\]\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*;$") +SPLIT = re.compile(r"[{}()\[\];]") +ITEM = re.compile(rf"(?:pub(?:\s*\([^)]*\))?\s+)?(?:(?:unsafe|async|const|extern|default|auto)\s+)*" + rf"(fn|struct|enum|union|trait|type|const|static|impl|mod|use|macro_rules\s*!|extern\s+crate)" + rf"(?!\w)\s*(?:mut\s+)?({IDENT})?") +PATH_BEFORE = re.compile(rf"\b({IDENT})\s*::") +PATH_AFTER = re.compile(rf"::\s*({IDENT})") +MACRO_USE = re.compile(rf"\b({IDENT})\s*!\s*[(\[{{]") +MACRO_CALL = re.compile(rf"({IDENT}(?:\s*::\s*{IDENT})*)\s*!") +DEFINED_INSIDE = re.compile(rf"\b(?:fn|struct|enum|union|trait|type|const|static)\s+({IDENT})") +NESTED_IMPL = re.compile(r"^[ \t]*(?:unsafe\s+)?impl\b([^{;]*)\{", re.MULTILINE) +QUALIFIED = re.compile(rf"{IDENT}(?:\s*::\s*{IDENT})*") +GLOB_IMPORT = re.compile(r"\buse\s[^;]*::\s*\*") +# File names a source may name in a literal (include_str!, include_bytes!, a path it reads). A file of another kind +# is never "named", so it always counts. +FILE_NAME = re.compile(r"[\w-]+\.(?:wgsl|glsl|json|png|ttf|otf|svg|txt|toml|ogg|wav|nbt|bin|dat|csv|mcmeta|wit|wasm)\b") +TYPE_KINDS = {"struct", "enum", "union", "trait", "type", "macro_call"} +# Names an impl header can take from outside the workspace: std's prelude and primitive types, and the std and serde +# traits a glob import may bring. A glob-imported name outside this list is taken to be the workspace's. +STD_NAMES = {"Display", "Error", "Read", "Write", "Seek", "BufRead", "Deref", "DerefMut", "Index", "IndexMut", "Add", + "Sub", "Mul", "Div", "Rem", "Neg", "Not", "BitAnd", "BitOr", "BitXor", "Shl", "Shr", "AddAssign", + "SubAssign", "MulAssign", "DivAssign", "RemAssign", "BitAndAssign", "BitOrAssign", "BitXorAssign", + "Borrow", "BorrowMut", "Future", "Any", "FromStr", "Hasher", "BuildHasher", "Formatter", "Ordering", + "Serialize", "Deserialize", "Serializer", "Deserializer", "Visitor", "Termination", "Sum", "Product", + "Wake", "Cow", "Rc", "Arc", "Mutex", "RwLock", "Cell", "RefCell", "HashMap", "HashSet", "BTreeMap", + "BTreeSet", "VecDeque"} +PRELUDE = {"Option", "Some", "None", "Result", "Ok", "Err", "Vec", "String", "Box", "ToString", "ToOwned", "Clone", + "Copy", "Send", "Sync", "Sized", "Unpin", "Drop", "Fn", "FnMut", "FnOnce", "From", "Into", "TryFrom", + "TryInto", "AsRef", "AsMut", "Default", "Eq", "PartialEq", "Ord", "PartialOrd", "Iterator", "Extend", + "IntoIterator", "DoubleEndedIterator", "ExactSizeIterator", "FromIterator", "Debug", "Hash", + "bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", + "isize", "f32", "f64"} +STD_NAMES |= PRELUDE +KEYWORDS = {"crate", "self", "super", "Self", "pub", "in", "as", "use", "for", "where", "dyn", "mut", "const", "fn", + "unsafe", "impl", "std", "core", "alloc", "let", "if", "else", "match", "return", "struct", "enum", "mod", + "type", "static", "trait", "true", "false", "loop", "while", "move", "ref", "break", "continue", "async", + "await", "extern", "union"} + + +def segments(code, start, end): + """The item-level pieces of code[start:end]: each ends at a `;` or a `}` outside any bracket.""" + found, begin, depth = [], start, 0 + for match in SPLIT.finditer(code, start, end): + character = match.group() + if character in "{([": + depth += 1 + elif character in "})]": + depth -= 1 + if character == "}" and depth == 0: + found.append((begin, match.end())) + begin = match.end() + elif depth == 0: + found.append((begin, match.end())) + begin = match.end() + if code[begin:end].strip(): + found.append((begin, end)) + return found + + +def skip_attributes(code, index, end): + """The offset of the first non-space character after the attributes (`#[...]`, `#![...]`) starting at index.""" + while True: + while index < end and code[index].isspace(): + index += 1 + if not code.startswith("#", index) or not re.match(r"#!?\[", code[index:index + 3]): + return index + depth = 0 + for position in range(code.index("[", index), end): + depth += {"[": 1, "]": -1}.get(code[position], 0) + if depth == 0: + index = position + 1 + break + else: + return end + + +def body_of(code, start, end): + """The range inside an item's outermost `{ }` block, or None.""" + opening = code.find("{", start, end) + closing = code.rfind("}", start, end) + return (opening + 1, closing) if 0 <= opening < closing else None + + +def words(text): + return set(WORD.findall(text)) - KEYWORDS + + +def qualified_words(text): + """Names a piece of code reaches through a path (`a::b`: b), the way items of other modules are named.""" + return set(PATH_AFTER.findall(text)) - KEYWORDS + + +def path_words(text): + """Names a piece of code uses as path segments (`a::`, `::b`), where module names appear.""" + return set(PATH_BEFORE.findall(text)) | set(PATH_AFTER.findall(text)) + + +def parse_items(code, start, end, items): + """Append the items of code[start:end] (a file or an inline module's body) to items, as dicts.""" + for begin, finish in segments(code, start, end): + head = skip_attributes(code, begin, finish) + text = code[head:finish] + if not text.strip(" \n\t;") or TEST_ONLY.search(code[begin:head]): + continue # compiled into tests only, never into a probe + match = ITEM.match(text) + kind = re.sub(r"\s+", "", match.group(1)) if match else None + name = match.group(2) if match else None + if kind == "mod": + body = body_of(code, head, finish) + if body: + parse_items(code, body[0], body[1], items) + continue + if kind in ("externcrate", None) and not MACRO_CALL.match(text): + if kind is None: + items.append({"kind": "glue", "mentions": sorted(words(text)), "paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))}) + continue + if kind is None: # an item-level macro call: it may define items + items.append({"kind": "macro_call", "names": sorted(set(DEFINED_INSIDE.findall(text))), + "macro": MACRO_CALL.match(text).group(1).split("::")[-1].strip(), + "mentions": sorted(words(text)), "paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))}) + elif kind == "use": + head_word = re.match(rf"\s*(?:::\s*)?({IDENT})", text[match.end(1):]) + items.append({"kind": "use", "public": text.startswith("pub"), "names": sorted(words(text)), + "head": head_word.group(1) if head_word else "", "glob": bool(re.search(r"::\s*\*", text)), + "mentions": sorted(words(text)), "paths": sorted(words(text)), "qualified": sorted(words(text)), + "invokes": []}) + elif kind == "impl": + body = body_of(code, head, finish) + subject = code[head + match.end(1) - match.start(): body[0] - 1 if body else finish] + inherent = not re.search(r"\bfor\b", impl_subject(subject)[1]) + if inherent and body: + members = [] + for member_begin, member_end in segments(code, body[0], body[1]): + member = code[skip_attributes(code, member_begin, member_end):member_end] + found = ITEM.match(member) + members.append({"name": found.group(2) if found else None, "mentions": sorted(words(member)), + "paths": sorted(path_words(member)), "qualified": sorted(qualified_words(member)), "invokes": sorted(set(MACRO_USE.findall(member)))}) + items.append({"kind": "impl", "subject": subject, "inherent": True, "members": members, + "mentions": sorted(words(subject)), "paths": sorted(path_words(subject)), "qualified": sorted(qualified_words(subject)), "invokes": sorted(set(MACRO_USE.findall(subject)))}) + else: + items.append({"kind": "impl", "subject": subject, "inherent": False, "mentions": sorted(words(text)), + "paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))}) + else: + kind = "macro" if kind.startswith("macro_rules") else kind + items.append({"kind": kind, "names": [name] if name else [], "mentions": sorted(words(text)), + "defines": sorted(set(DEFINED_INSIDE.findall(text))) if kind == "macro" else [], + "paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))}) + if kind in ("fn", "const", "static"): + # An impl inside a function body still holds for the whole program. + for header in NESTED_IMPL.findall(text): + items.append({"kind": "impl", "subject": header, "inherent": False, + "mentions": sorted(words(text)), "paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))}) + + +def crate_roots(crate_dir): + """A crate's root files: its library, binaries and examples.""" + roots = [crate_dir / "src" / "lib.rs", crate_dir / "src" / "main.rs"] + for folder in (crate_dir / "src" / "bin", crate_dir / "examples"): + if folder.is_dir(): + roots += sorted(folder.glob("*.rs")) + sorted(folder.glob("*/main.rs")) + return [root for root in roots if root.is_file()] + + +class SourceGraph: + """The workspace's Rust sources, parsed once: what each file names, defines and declares.""" + + def __init__(self, root, rust_code, cache=None): + """cache: a dict of earlier parses by content digest, which the graph reuses and adds to (parity.py keeps it + in .local/parity-runner/reach-cache.json).""" + self.root = Path(root) + self.rust_code = rust_code + self.cache = {} if cache is None else cache + self.used = set() + self.files = {} + self.parent = {} # module file -> the file declaring it + self.module_name = {} + self.roots = set() + self.target_cache = {} + self.workspace_heads = None + self.test_only = set() # modules compiled into tests only + self.tables = None + self.root_of = {} # source -> the root of its target (lib.rs, a bin's or an example's main file) + self.results = {} # (entries, universe) -> reachable files + for manifest in sorted((self.root / "crates").glob("*/Cargo.toml")): + for crate_root in crate_roots(manifest.parent): + path = self.relative(crate_root) + self.roots.add(path) + self.root_of[path] = path + self.place(path, crate_root.parent, set()) + + def entries(self, artifacts, rust): + """The root files of the probes and binaries a harness built (its record's artifacts), among its Rust + dependencies: for a crate's probe binary, the probe modules it ran (parity.only_probes_run kept only those). + None when an artifact can't be placed.""" + found = set() + for kind, name, *rest in artifacts: + selection = rest[1] if len(rest) > 1 else [] + packages = [value for flag, value in zip(selection, selection[1:]) if flag == "-p"] or \ + [manifest.parent.name for manifest in sorted((self.root / "crates").glob("*/Cargo.toml"))] + roots = set() + for package in packages: + crate = self.root / "crates" / package + targets = self.targets(crate) + if kind in ("example", "examples"): + candidates = [path for target, (target_kind, path) in targets.items() + if target_kind == "example" and (not name or target == name)] + else: + candidates = [path for target, (target_kind, path) in targets.items() + if target_kind == "bin" and (not name or target == name)] + for path in candidates: + if path.endswith("/examples/probe/main.rs"): + # The probes it ran, and the dispatch and support modules they use (only_probes_run kept + # those); the binary's root, which only declares them, so their own submodules are placed. + folder = path.removesuffix("main.rs") + roots |= {dependency for dependency in rust if dependency.startswith(folder) + and "/" not in dependency.removeprefix(folder).removeprefix("support/")} + if roots: + roots.add(path) + elif path in rust: + roots.add(path) + if not roots: + return None + found |= roots + return found or None + + def targets(self, crate): + """A crate's bins and examples: {target name: (kind, root file)}, from its Cargo.toml and Cargo's defaults.""" + if crate in self.target_cache: + return self.target_cache[crate] + found = {} + manifest = (crate / "Cargo.toml").read_text(encoding="utf-8") if (crate / "Cargo.toml").is_file() else "" + package = re.search(r'^\[package\][^\[]*?^name\s*=\s*"([^"]+)"', manifest, re.MULTILINE | re.DOTALL) + if (crate / "src" / "main.rs").is_file() and package: + found[package.group(1)] = ("bin", self.relative(crate / "src" / "main.rs")) + for kind, folder in (("bin", crate / "src" / "bin"), ("example", crate / "examples")): + for path in sorted(folder.glob("*.rs")) + sorted(folder.glob("*/main.rs")): + found[path.stem if path.name != "main.rs" else path.parent.name] = (kind, self.relative(path)) + for kind, table in re.findall(r"^\[\[(bin|example)\]\]([^\[]*)", manifest, re.MULTILINE): + name = re.search(r'^name\s*=\s*"([^"]+)"', table, re.MULTILINE) + path = re.search(r'^path\s*=\s*"([^"]+)"', table, re.MULTILINE) + if name and path and (crate / path.group(1)).is_file(): + found[name.group(1)] = (kind, self.relative(crate / path.group(1))) + self.target_cache[crate] = found + return found + + def target(self, path): + """The Cargo target a source belongs to: the root file of the library, bin or example whose module tree + holds it (a file nothing places is its own).""" + return self.root_of.get(path, path) + + def is_library(self, path): + return self.target(path).endswith("/src/lib.rs") + + def relative(self, path): + return Path(path).resolve().relative_to(self.root.resolve()).as_posix() + + def place(self, path, module_dir, seen): + """Walk the module tree from a file: record each declared module's file, parent and name.""" + if path in seen: + return + seen.add(path) + parsed = self.parse(path) + if parsed is None: + return + for name, nesting, attribute, test in parsed["declarations"]: + if attribute is not None: + if nesting: + continue # a #[path] inside an inline module: unplaced, so always kept + candidates = [(self.root / path).parent / attribute] + else: + folder = module_dir.joinpath(*nesting) + candidates = [folder / f"{name}.rs", folder / name / "mod.rs"] + for candidate in candidates: + if candidate.is_file(): + child = self.relative(candidate) + self.parent.setdefault(child, path) + self.module_name.setdefault(child, name) + self.root_of.setdefault(child, self.root_of[path]) + if test or path in self.test_only: + self.test_only.add(child) + child_dir = candidate.parent if candidate.name == "mod.rs" or attribute is not None \ + else candidate.parent / candidate.stem + self.place(child, child_dir, seen) + break + + def parse(self, path): + if path in self.files: + return self.files[path] + try: + data = (self.root / path).read_bytes() + except OSError: + self.files[path] = None + return None + digest = hashlib.sha256(data).hexdigest() + self.used.add(digest) + if digest in self.cache: + self.files[path] = parsed = self.cache[digest] + return parsed + raw = data.decode("utf-8", errors="replace") + code = self.rust_code(raw) # same length as raw: literals and comments blanked + opening = {match.end() - 1: match.group(1) for match in INLINE_MOD.finditer(code)} + events = sorted([(match.start(), match) for match in BRACE.finditer(code)] + + [(match.start(), match) for match in MOD_DECLARATION.finditer(code)], key=lambda event: event[0]) + declarations, stack, depth = [], [], 0 + for index, match in events: + if match.group() == "{": + depth += 1 + if index in opening: + stack.append((opening[index], depth)) + elif match.group() == "}": + if stack and stack[-1][1] == depth: + stack.pop() + depth -= 1 + else: + window = " ".join(raw[max(0, index - 300):match.end()].split()) + attribute = PATH_ATTRIBUTE.search(window) + declarations.append([match.group(1), [name for name, _ in stack], attribute.group(1) if attribute else None, + bool(TEST_MODULE.search(window))]) + items = [] + parse_items(code, 0, len(code), items) + self.files[path] = parsed = { + "declarations": declarations, + "items": items, + "glob": bool(GLOB_IMPORT.search(code)), + "file_names": sorted(set(FILE_NAME.findall(raw))), + } + self.cache[digest] = parsed + return parsed + + def saved_cache(self): + """The parses of the files this graph read, to keep for the next run.""" + return {digest: self.cache[digest] for digest in self.used if digest in self.cache} + + def requirement(self, path, item): + """For an impl: for its trait and for its type, [names the file defines, other workspace names], one of + which must be a reached type or trait (of this file, of a crate it sees) before the impl can matter; both + empty: nothing of the workspace is needed. A name is the workspace's when the path naming it starts in the + workspace, or the file defines it, imports it from the workspace or may glob-import it; otherwise (std's, + another crate's, the prelude's) it needs nothing.""" + if "requires" in item: + return item["requires"] + if self.workspace_heads is None: + self.workspace_heads = {"crate", "self", "super"} | set(self.module_name.values()) | { + manifest.parent.name.replace("-", "_") for manifest in (self.root / "crates").glob("*/Cargo.toml")} + parsed = self.parse(path) + defined = {name for other in parsed["items"] for name in other.get("names", ()) if other["kind"] != "use"} + workspace_imports = {name for other in parsed["items"] if other["kind"] == "use" + and other["head"] in self.workspace_heads for name in other["names"]} + parameters, subject = impl_subject(item["subject"]) + parts = [] + for part in re.split(r"\bfor\b", subject, maxsplit=1): + names, own = set(), set() + for match in QUALIFIED.finditer(part): + segments_ = [segment.strip() for segment in match.group().split("::")] + name = segments_[-1] + if name in parameters or name in KEYWORDS: + continue + if len(segments_) > 1: + if segments_[0] in self.workspace_heads: + names.add(name) + elif name in defined: + own.add(name) + elif name in workspace_imports or (parsed["glob"] and name not in STD_NAMES): + names.add(name) + parts.append([sorted(own), sorted(names)]) + item["requires"] = parts + return parts + + def index(self): + """Lookup tables over every placed source, built once: which crates each crate sees, the nodes (items, an + inherent impl's members) by the names they define and the types they need, the modules by name.""" + if self.tables is not None: + return self.tables + idents = {manifest.parent.name.replace("-", "_"): manifest.parent.name + for manifest in (self.root / "crates").glob("*/Cargo.toml")} + paths = [path for path in self.files if self.files[path] is not None and path not in self.test_only] + sees = {} + for path in paths: + named = {word for item in self.files[path]["items"] for word in item["mentions"]} & idents.keys() + sees.setdefault(crate_of(path), {crate_of(path)}).update(idents[name] for name in named) + changed = True + while changed: + changed = False + for crate, seen in sees.items(): + wider = set().union(*(sees.get(other, {other}) for other in seen)) + if not wider <= seen: + seen |= wider + changed = True + seen_by = {} # crate -> the crates that see it + for crate, seen in sees.items(): + for other in seen: + seen_by.setdefault(other, set()).add(crate) + # What a call of a workspace macro defines: what its definition's body defines. + expands = {} + for path in paths: + for item in self.files[path]["items"]: + if item["kind"] == "macro": + for name in item["names"]: + expands.setdefault(name, set()).update(item["defines"]) + names_of, by_name, by_file_name, by_type, by_module, children, seeds = {}, {}, {}, {}, {}, {}, [] + for path in paths: + crate = crate_of(path) + if path in self.module_name: + by_module.setdefault((crate, self.module_name[path]), []).append(path) + children.setdefault(self.parent[path], []).append(path) + for index, item in enumerate(self.files[path]["items"]): + node = (path, index, None) + names = set(item.get("names", ())) + if item["kind"] == "macro_call": + names |= expands.get(item["macro"], set()) + names_of[node] = names + if item["kind"] == "glue": + seeds.append(node) + elif item["kind"] == "macro_call" and not names: + # A macro call defining nothing by name may still expand to impls: it counts once a type or + # trait it mentions is reached. + for name in item["mentions"]: + by_type.setdefault(name, []).append(node) + elif item["kind"] == "impl": + required = {name for own, foreign in self.requirement(path, item) for name in own + foreign} + members = [(path, index, member) for member in range(len(item["members"]))] if item["inherent"] else [] + for member_node in members: + name = item["members"][member_node[2]]["name"] + names_of[member_node] = set() + if name: + by_name.setdefault(name, []).append(member_node) + for name in required: + for other in [node] + members: + by_type.setdefault(name, []).append(other) + if not required: + seeds.append(node) + seeds += [member_node for member_node in members if not item["members"][member_node[2]]["name"]] + else: + for name in names: + by_name.setdefault(name, []).append(node) + by_file_name.setdefault((path, name), []).append(node) + self.tables = dict(idents=idents, sees=sees, seen_by=seen_by, names_of=names_of, by_name=by_name, + by_file_name=by_file_name, by_type=by_type, by_module=by_module, children=children, + seeds=seeds, node_sets={}) + return self.tables + + def reachable(self, entries, universe, reasons=None): + """The files of universe (workspace Rust sources) holding an item reachable from entries (by the rules in + this module's doc), and the entries. reasons, a dict, gets why each file was reached (for debugging).""" + # Searching every source of the crates involved (not only those Cargo listed) only adds reach, and lets + # harnesses with the same entries (the game binary's) share one search. + crates = frozenset(crate_of(path) for path in universe) + key = (frozenset(entries), crates) + if reasons is None and key in self.results: + return self.results[key] & set(universe) + everything = {path for path in self.files if crate_of(path) in crates} | set(universe) + files = self.search(entries, everything, reasons) + self.results[key] = files + return files & set(universe) + + def search(self, entries, universe, reasons): + targets = {self.target(path) for path in entries} + universe = {path for path in universe if (self.is_library(path) or self.target(path) in targets) + and path not in self.test_only} + tables = self.index() + idents, sees, seen_by, names_of = tables["idents"], tables["sees"], tables["seen_by"], tables["names_of"] + node_sets = tables["node_sets"] + by_name, by_file_name, by_type = tables["by_name"], tables["by_file_name"], tables["by_type"] + by_module, children = tables["by_module"], tables["children"] + seeds = [node for node in tables["seeds"] if node[0] in universe] + for path in universe: + if (path in entries or (path not in self.parent and path not in self.roots)) and self.parse(path): + seeds += [(path, index, None) for index in range(len(self.parse(path)["items"]))] + + def names(node): + return names_of.get(node, set()) + + def sets_of(node, item): + """A node's mentions, path words, qualified names and macro calls, as sets (parses keep lists).""" + if node not in node_sets: + source = item["members"][node[2]] if node[2] is not None else item + node_sets[node] = {key: set(source.get(key, ())) for key in ("mentions", "paths", "qualified", "invokes")} + return node_sets[node] + + def item_of(node): + return self.parse(node[0])["items"][node[1]] + + reached, opened, globbed, files, queue = set(), set(), set(), set(), [] + # name -> the crates whose reached code mentions it plainly, names it in a path or an import, invokes it. + mentioned, qualified, invoked = {}, {}, {} + done = {"mentions": {}, "qualified": {}, "invokes": {}, "paths": {}} # crate -> names already handled + path_names, types = {}, {} # by crate + local = {} # file -> plain mentions by reached code in it or below it (child modules may `use super::*`) + local_types = {} # file -> its reached types and traits + + def heard(table, name, crate): + """Whether a crate that can see crate's items has name in table.""" + sources = table.get(name) + return bool(sources) and not sources.isdisjoint(seen_by.get(crate, {crate})) + + def ready(node): + path, index, member = node + item = item_of(node) + crate = crate_of(path) + if item["kind"] == "impl": + visible = visible_types(crate) + here = local_types.get(path, set()) + if not all((not own and not foreign) or here.intersection(own) or visible.intersection(foreign) + for own, foreign in self.requirement(path, item)): + return False + name = item["members"][member]["name"] if member is not None else None + return name is None or heard(mentioned, name, crate) # a method: called by its name + if item["kind"] == "macro_call" and not names(node): + return not visible_types(crate).isdisjoint(item["mentions"]) + names_ = names(node) + if item["kind"] == "macro": + return any(heard(invoked, name, crate) for name in names_) + if item["kind"] == "use" and item["glob"]: + return path in opened + nearby = local.get(path, ()) + if any(name in nearby for name in names_): + return True # named in its own module, or below it + if item["kind"] == "use" and not item["public"]: + return False + if path in opened and any(heard(qualified, name, crate) for name in names_): + return True # named through a path, or imported + return path in globbed and any(heard(mentioned, name, crate) for name in names_) + + visible_cache = {} + + def visible_types(crate): + """The reached types and traits of the crates a crate sees (cached until a type is reached).""" + if crate not in visible_cache: + visible_cache[crate] = set().union(*(types.get(other, set()) for other in sees.get(crate, {crate}))) + return visible_cache[crate] + + def wake(nodes, why): + for other in nodes: + if other not in reached and other[0] in universe and ready(other): + reach(other, why) + + def open_module(path, why): + pending = [path] + while pending: + current = pending.pop() + if current in opened: + continue + opened.add(current) + crate = crate_of(current) + pending += [child for child in children.get(current, ()) + if child in universe and self.module_name[child] in path_names.get(crate, ())] + parsed = self.parse(current) + wake([(current, index, None) for index, item in enumerate(parsed["items"] if parsed else ()) + if item["kind"] != "impl"], f"{current} opened ({why})") + + def reach(node, why): + if node in reached: + return + reached.add(node) + queue.append(node) + path, _, member = node + item = item_of(node) + if (item["kind"] == "use" and not item["public"]) or (item["kind"] == "impl" and item["inherent"] and member is None): + return + if path not in files: + files.add(path) + if reasons is not None: + reasons[path] = why + + for path in universe: + if path.endswith("/src/lib.rs") or path in entries or path not in self.parent: + open_module(path, "crate root or entry") + for node in seeds: + reach(node, "entry" if node[0] in entries else "always counted") + for path in entries & universe: + files.add(path) + if reasons is not None: + reasons.setdefault(path, "entry") + while queue: + node = queue.pop() + path, index, member = node + item = item_of(node) + crate = crate_of(path) + label = (item.get("names") or [item["kind"]])[0] if member is None else item["members"][member]["name"] + source = sets_of(node, item) + why = f"{path} ({label})" + # Plain mentions reach items of this file and of the modules above it. + ancestor, new = path, source["mentions"] + while ancestor is not None and new: + known = local.setdefault(ancestor, set()) + new = new - known + known |= new + for name in new: + wake(by_file_name.get((ancestor, name), ()), f"{why} mentions {name}") + ancestor = self.parent.get(ancestor) + if item["kind"] == "use" and item["glob"]: + for name in item["names"]: + for target in sees.get(crate, {crate}): + for module in list(by_module.get((target, name), ())) + \ + ([f"crates/{idents[name]}/src/lib.rs"] if name in idents else []): + if module not in globbed and module in universe: + globbed.add(module) + wake([(module, index, None) for index in range(len(self.parse(module)["items"]))] + if self.parse(module) else [], f"{why} glob-imports {name}") + visible_to = sees.get(crate, {crate}) + new = source["paths"] - done["paths"].setdefault(crate, set()) + done["paths"][crate] |= new + for name in new: + for target in visible_to: + path_names.setdefault(target, set()).add(name) + for module in by_module.get((target, name), ()): + if module in universe and self.parent[module] in opened: + open_module(module, f"{why} names {name}") + for key, table, wanted in (("qualified", qualified, lambda other: True), + ("invokes", invoked, lambda other: item_of(other)["kind"] == "macro"), + ("mentions", mentioned, lambda other: other[2] is not None or other[0] in globbed)): + new = source[key] - done[key].setdefault(crate, set()) + done[key][crate] |= new + for name in new: + table.setdefault(name, set()).add(crate) + wake([other for other in by_name.get(name, ()) if crate_of(other[0]) in visible_to and wanted(other)], + f"{why} {key} {name}") + if item["kind"] in TYPE_KINDS and member is None: + own = types.setdefault(crate, set()) + local_types.setdefault(path, set()).update(names(node)) + if not names(node) <= own: + own |= names(node) + visible_cache.clear() + seeing = seen_by.get(crate, {crate}) + for name in names(node): # also when the crate has one by that name already: impls of this one + wake([other for other in by_type.get(name, ()) if crate_of(other[0]) in seeing], + f"implements for {name}, defined in {path}") + return files + + +def impl_subject(header): + """An impl header (the text after `impl`): its generic parameters' names, and the rest without its where clause + (the trait and the type it is for).""" + header, parameters = header.strip(), set() + if header.startswith("<"): + depth = 0 + for index, character in enumerate(header): + depth += {"<": 1, ">": -1}.get(character, 0) + if depth == 0: + generics, header = header[1:index], header[index + 1:] + parameters = {match.group(1) for match in re.finditer(rf"(?:^|,)\s*(?:const\s+)?({IDENT})", generics)} + break + return parameters, re.split(r"\bwhere\b", header)[0] + + +def crate_of(path): + return path.split("/", 2)[1] + + +def is_workspace_rust(path): + parts = PurePosixPath(path).parts + return len(parts) > 2 and parts[0] == "crates" and path.endswith(".rs") + + +DECLARATION_LINE = re.compile(rf"\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+({IDENT})\s*;") + + +def declarations(text, names, keep_rest): + """A Rust file's `mod` declarations of names, each with the attribute lines just above it; with keep_rest, the + whole text except the declarations of other modules instead.""" + lines, found, attributes = text.splitlines(), [], [] + for line in lines: + if line.strip().startswith("#[") and not line.strip().startswith("#!["): + attributes.append(line.strip()) + continue + match = DECLARATION_LINE.match(line) + if match and match.group(1) in names: + found += attributes + [line.strip()] + elif keep_rest and not match: + found += attributes + [line] + attributes = [] + return "\n".join(found + attributes) + + +def declarations_changed(root, path, children, base, whole): + """Whether a changed file differs from the commit base in what a harness depends on: for a module parent, its + `mod` declarations of the reached children; for a whole file (whole), everything but its declarations of other + modules (adding a module beside reached ones changes nothing). True without a base, or if either side is + missing.""" + if base is None: + return True + try: + head = (Path(root) / path).read_text(encoding="utf-8", errors="replace") + before = subprocess.run(["git", "show", f"{base}:{path}"], cwd=root, capture_output=True, text=True, check=True).stdout + except (OSError, subprocess.CalledProcessError): + return True + return declarations(head, children, whole) != declarations(before, children, whole) + + +def narrow(dependencies, artifacts, graph, changed=()): + """A harness's dependencies narrowed to what its entry points can reach: {dependency: (whole, children)}, where + whole says the file counts for its own content (else only through its `mod` declarations of children, as a + module ancestor of a reached file) and children are its reached child modules. Without known entry points (a + probe or binary the harness built that isn't found here), every dependency is kept whole.""" + plain = [dependency.split("#keep:")[0] for dependency in dependencies] + crates = {PurePosixPath(path).parts[1] for path in plain if path.startswith("crates/")} + rust = {path for path in plain if is_workspace_rust(path)} + added = {path for path in changed if is_workspace_rust(path) and PurePosixPath(path).parts[1] in crates + and path not in rust and (graph.root / path).is_file()} + entries = graph.entries(artifacts, rust) + if entries is None: + return {dependency: (True, None) for dependency in dependencies} + missing = {path for path in rust if graph.parse(path) is None} + reached = graph.reachable(entries, rust | added | entries) | missing + named, named_in_crate = set(), {} + for path in rust | added: + parsed = graph.parse(path) + file_names = set(parsed["file_names"]) if parsed else set() + if path in reached: + named |= file_names + named_in_crate.setdefault(PurePosixPath(path).parts[1], set()).update(file_names) + kept = {} + for dependency, path in zip(dependencies, plain): + if is_workspace_rust(path): + if path in reached: + kept[dependency] = (True, set()) + elif not path.startswith("crates/") or path.endswith(("Cargo.toml", "build.rs")) \ + or PurePosixPath(path).name in named \ + or PurePosixPath(path).name not in named_in_crate.get(PurePosixPath(path).parts[1], ()): + kept[dependency] = (True, None) + for path in sorted(added & reached): + kept[path] = (True, set()) + for path in sorted(reached): + child = path + while child in graph.parent: + parent = graph.parent[child] + kept.setdefault(parent, (False, set()))[1].add(graph.module_name[child]) + child = parent + return kept From 0baf6cbd62e5dc053732354b5ebd356aae3ffd83 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:27:22 +0100 Subject: [PATCH 33/43] CI: the desktop runner works while its screen is locked or untouched for 15 min MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ludovic's rule (2026-10-26): runner_pause.py pauses at once on keyboard, mouse or gamepad input (read from /dev/input, only whether bytes came), on an unlocked session touched in the last 15 min, at 90 °C, on a game or the GPU. Fixes the service start: the link loop's last test failed the script under set -e. Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 2 +- docs/release-flow.md | 32 +++++++------- tests/test_runner_pause.py | 13 +++++- tools/ci/linux-runner.sh | 12 +++--- tools/ci/runner_pause.py | 88 ++++++++++++++++++++++++++++++++------ tools/parity_hosts.json | 2 +- 6 files changed, 113 insertions(+), 36 deletions(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 80426fa59..7eecdd8bb 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -38,7 +38,7 @@ The game logs into `HORIZON_HOME` and falls back to the player's own game folder ### Other machines -Harnesses can also run on the Mac mini, the ThinkPad and the desktop (`tools/parity_hosts.json` describes them; `desktop` uses its CI runner's environment and vanilla data, and refuses work, or stops it, while someone is at it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 3 and only those under 800 MB. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. +Harnesses can also run on the Mac mini, the ThinkPad and the desktop (`tools/parity_hosts.json` describes them; `desktop` uses its CI runner's environment and vanilla data, and refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad helps too, gently: Linux, 2 harnesses at `nice 19`, since it hosts the Claude account pool; it finds ALSA through `~/code/horizon-parity/alsa-dev` like the desktop. diff --git a/docs/release-flow.md b/docs/release-flow.md index e72bebc73..d9d1801aa 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -68,21 +68,23 @@ release's macOS build back. Each keeps its own checkout, `target/` and Rust inst time, under a lock) and the parity passes and slots. **The desktop's runner.** `ludodesktop-horizon` (labels `self-hosted`, `Linux`, `X64`, `ludodesktop`, and -`horizon-game` once a full trial has passed there) runs on the maintainer's Linux desktop, only while nobody is -at it. `tools/ci/linux-runner.sh install`, run there as him, registers it and installs two systemd user services: -`horizon-runner` (the runner, in `~/.actions-runners/horizon`, nice 19, in `horizon-ci.slice` with CPU and I/O -weight 20 and memory capped at two thirds of the RAM; `CARGO_BUILD_JOBS` and the harness slots at 8, after the -machine froze under ~7 cold cargo builds on 2026-10-14; its own Rust install; the JDK, sccache and the build -libraries from nixpkgs; its own `vscreen` so no game it starts reaches his screen) and `horizon-runner-pause` -(`tools/ci/runner_pause.py`), the only thing that starts the runner. The watcher stops it while a graphical -session is open on the machine, locked or not (`~/fleet/power status` says "IN USE"), while a game runs (Steam, -gamescope, Wine, Proton or Minecraft processes, fleet-load's own detection, or a process outside the CI slice -using the GPU at 50 % or more), or while `~/.actions-runners/horizon/pause` exists, and starts it again 5 minutes -after the last such sign. A job already under way is throttled to 2 threads at the lowest weight and the runner -stops after it: freezing the job would make GitHub drop it as lost and the harnesses time out. Old pull requests' -`runner-env.sh` know only the Mac: the runner's `.env` and `.path` give their jobs Python, the JDK and the -vanilla data (`HORIZON_SHARED_SOURCE`) all the same. The nightly audit stays on the Mac mini's runners, so its -comparison with the previous night is always made on one platform. +`horizon-game` once a full trial has passed there) runs on the maintainer's Linux desktop while nobody uses it: its +screen locked, or untouched for 15 minutes (his rule, 2026-10-26). `tools/ci/linux-runner.sh install`, run there as +him, registers it and installs two systemd user services: `horizon-runner` (the runner, in +`~/.actions-runners/horizon`, nice 19, in `horizon-ci.slice` with CPU and I/O weight 20 and memory capped at two +thirds of the RAM; `CARGO_BUILD_JOBS` and the harness slots at 8, after the machine froze under ~7 cold cargo +builds on 2026-10-14; its own Rust install; the JDK, sccache and the build libraries from nixpkgs; its own +`vscreen` so no game it starts reaches his screen) and `horizon-runner-pause` (`tools/ci/runner_pause.py`), the +only thing that starts the runner. The watcher stops it at once on keyboard, mouse or gamepad input (read from +`/dev/input`: only whether bytes came, never what), while an unlocked session has had input in the last 15 minutes, +while the CPU package is at 90 °C or more, while a game runs (Steam, gamescope, Wine, Proton or Minecraft +processes, fleet-load's own detection, or a process outside the CI slice using the GPU at 50 % or more), or while +`~/.actions-runners/horizon/pause` exists, and starts it again 5 minutes after the last such sign. A job already +under way is throttled to 2 threads at the lowest weight and the runner stops after it: freezing the job would make +GitHub drop it as lost and the harnesses time out. Old pull requests' `runner-env.sh` know only the Mac: the +runner's `.env` and `.path` give their jobs Python, the JDK and the vanilla data (`HORIZON_SHARED_SOURCE`) all the +same. The nightly audit stays on the Mac mini's runners, so its comparison with the previous night is always made +on one platform. ## Merging diff --git a/tests/test_runner_pause.py b/tests/test_runner_pause.py index c6df08b82..38c4affd8 100644 --- a/tests/test_runner_pause.py +++ b/tests/test_runner_pause.py @@ -18,7 +18,7 @@ class Machine: self.throttles = [] # (clock, on) self.calls = [] - def reason(self, hot): + def reason(self, hot, keys): return next((reason for start, end, reason in self.signs if start <= self.clock < end), None) def systemctl(self, *arguments): @@ -77,6 +77,17 @@ class RunnerPauseTests(unittest.TestCase): self.assertLess(stop, 1215) self.assertEqual(machine.throttles[-1], (1290 + 300, False)) + def test_the_desktop_is_free_when_locked_or_untouched_for_15_minutes(self): + cases = [ # (session, seconds since the last input, someone there) + (("3", False), 30, True), (("3", True), 30, True), # any input pauses at once, even on the lock screen + (("3", False), 120, True), (("3", False), 1000, False), # unlocked: free after 15 min untouched + (("3", True), 120, False), (None, 120, False), # locked, or nobody logged in + ] + for session, idle, there in cases: + with self.subTest(session=session, idle=idle), \ + mock.patch.object(runner_pause, "seat_session", lambda: session): + self.assertEqual(runner_pause.at_the_screen(idle) is not None, there) + if __name__ == "__main__": unittest.main() diff --git a/tools/ci/linux-runner.sh b/tools/ci/linux-runner.sh index adc2b0130..1bd587e79 100755 --- a/tools/ci/linux-runner.sh +++ b/tools/ci/linux-runner.sh @@ -9,10 +9,10 @@ # # 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 is -# at the screen or playing, 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. +# 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). @@ -40,7 +40,7 @@ parity_host_links() { [ -d "$checkout" ] || return 0 mkdir -p "$shared" for entry in "$checkout"/*; do - [ -L "$entry" ] && ln -sfn "$entry" "$shared/$(basename "$entry")" + if [ -L "$entry" ]; then ln -sfn "$entry" "$shared/$(basename "$entry")"; fi done } @@ -151,7 +151,7 @@ RestartSec=30 EOF cat > "$units/horizon-runner-pause.service" <= GPU_BUSY %, default 50, in two @@ -34,6 +36,9 @@ 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)) +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): @@ -53,13 +58,71 @@ def ci_process(pid): return True # gone -def at_the_screen(): - """A graphical login on seat0, as ~/fleet/power status counts it (a locked screen counts too).""" +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 = time.monotonic() # a start counts as input: nothing is known yet + + 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: - return f"session {fields[0]} of {fields[2] if len(fields) > 2 else '?'} at the screen (seat0)" + 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 above TEMP_LIMIT °C (coretemp or k10temp).""" + for monitor in Path("/sys/class/hwmon").glob("hwmon*"): + try: + if (monitor / "name").read_text().strip() in ("coretemp", "k10temp"): + celsius = int((monitor / "temp1_input").read_text()) / 1000 + return f"CPU at {celsius:.0f} °C" if celsius >= TEMP_LIMIT else None + except (OSError, ValueError): + pass return None @@ -133,11 +196,12 @@ def throttle(on): systemctl("set-property", "--runtime", SLICE, "CPUWeight=20", "IOWeight=20", "CPUQuota=") -def pause_reason(hot): - """Why the runner may not work now, or None. hot: the GPU users seen busy at the last sample (updated).""" +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() or fleet_load_gaming() or game_process() + 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} @@ -154,13 +218,13 @@ def pause_reason(hot): def main(): - hot = {} + hot, keys = {}, Input() # A boot (or a restart of this watcher) counts as a sign: the runner starts RESUME_AFTER seconds later at the # earliest, which leaves time to log in after switching the machine on. last_sign = time.monotonic() paused = None while True: - reason = pause_reason(hot) + reason = pause_reason(hot, keys) now = time.monotonic() if reason: last_sign = now diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index 5d561175d..f2ba65c68 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -18,7 +18,7 @@ "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 is at the screen (tools/ci/runner_pause.py: 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" + "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", From 836c1ee3b999823ab5d0db767ffbb6b71db4ab1e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:27:32 +0100 Subject: [PATCH 34/43] CI parity: pick harnesses with main's selection code, run them at the head The parity job checks out the PR head, so every branch made before #1964 still selected with the old per-crate rule. The step now runs main's tools/parity.py and tools/parity_reach.py with --changed --list, restores the head's files, and runs the named harnesses with the head's parity.py. A branch that edits either file, or a failure of main's selection, falls back to the head's own `--changed` run. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/parity.yml | 32 +++++++++++++++++++++++++++++++- docs/release-flow.md | 3 +++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index a18fc5019..be87bc965 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -43,7 +43,37 @@ jobs: env: PARITY_HOSTS: '' BASE_SHA: ${{ inputs.base }} - run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner + run: | + # main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a + # branch made before a better selection landed gets it too; the head's own runner then runs those + # harnesses. A branch that changes the selection itself selects with its own code. + set -euo pipefail + own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner + fork_point=$(git merge-base "$BASE_SHA" HEAD) + if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then + own + exit + fi + had_reach=$(git ls-files tools/parity_reach.py) + git show origin/main:tools/parity.py > tools/parity.py + git show origin/main:tools/parity_reach.py > tools/parity_reach.py + status=0 + python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$? + git checkout -- tools/parity.py + if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi + cat .local/parity-selection.txt + if [ "$status" != 0 ]; then + echo "main's selection failed: the head's own selection runs" + own + exit + fi + names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true) + if [ -z "$names" ]; then + echo "Nothing to run." + exit 0 + fi + # shellcheck disable=SC2086 + python3 tools/parity.py $names --timeout 2400 - name: Logs of the failed harnesses if: failure() uses: actions/upload-artifact@v4 diff --git a/docs/release-flow.md b/docs/release-flow.md index 4fb0209d9..3024e0f53 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -43,6 +43,9 @@ copy is: the Mac mini. Its runner runs as the maintainer's account and keeps its modules, Java oracles and every Rust source their probes compile) changed since the merge base, plus any harness nothing is recorded about yet, and runs those that have no pass for their current inputs. A change to `Cargo.lock` or `research-lock.json` affects every harness. Each harness has 25 minutes, the job 45. + The selection runs with main's `tools/parity.py` and `tools/parity_reach.py` (`--changed --list`), so a + branch made before a better selection landed gets it too, and the head's own `parity.py` then runs the named + harnesses. A branch that changes either file selects with its own code. Failed harnesses' logs are uploaded as the `parity-logs` artifact. From 0b970c0c9a0eb259652f5bee756073563e471faf Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:35:22 +0000 Subject: [PATCH 35/43] Cover instant-break sounds alongside replanting Move the instant_digging regression from redundant PR #1966 into the existing stale-dig fix for #1880 and #1908. Co-Authored-By: Codex (gpt-6.1-sol) --- tools/lan_e2e.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f0333c87b..11354b970 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -250,6 +250,7 @@ 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). @@ -5398,6 +5399,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 From 73da2f04ddd56cb2ca1f480f54ab0aad31478223 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:35:28 +0100 Subject: [PATCH 36/43] CI: parity on main, a batch of merges at a time; releases wait for it parity-main runs the vanilla harnesses on every push to main, one run at a time: merges that land during a run wait in one pending run, which checks every merge since main's last green parity-main (tools/parity_main.py base, then parity.py --changed). A failure is bisected over the batch's first-parent merges, running only the failing harnesses, and the breaking merge's pull request gets a comment. Game releases ship only a commit both checks and parity-main passed on (release_train.py; release.yml also starts when parity-main finishes; a forced release doesn't wait). The per-PR parity job now runs only for a PR that changes a harness, an oracle, a probe or the runner, or carries run-parity. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 34 +++++++- .github/workflows/parity-main.yml | 70 ++++++++++++++++ .github/workflows/release.yml | 10 ++- docs/parity-workflow.md | 2 + docs/release-flow.md | 30 ++++++- tests/test_parity_main.py | 43 ++++++++++ tests/test_release_train.py | 21 +++++ tools/parity_main.py | 129 ++++++++++++++++++++++++++++++ tools/release_train.py | 34 ++++++-- 9 files changed, 356 insertions(+), 17 deletions(-) create mode 100644 .github/workflows/parity-main.yml create mode 100644 tests/test_parity_main.py create mode 100644 tools/parity_main.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98d5b9093..eff82fa99 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,8 @@ name: checks # check main requires, so it never has a condition: a skipped job counts as passed, and every run of this workflow # must report a real verify (a pull request that changes no Rust finishes it in seconds instead). # parity: the vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the -# maintainer's own Minecraft files (Horizon never downloads the game); .github/workflows/parity.yml. A fork's pull +# maintainer's own Minecraft files (Horizon never downloads the game); .github/workflows/parity.yml. Only for a pull +# request that changes a harness, oracle, probe or the runner: the rest are checked on main by parity-main. A fork's pull # request runs it only when a maintainer adds the run-parity label (.github/workflows/run-parity.yml), so labels # never start this workflow. See docs/release-flow.md. on: @@ -72,8 +73,37 @@ jobs: run: | cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack - parity: + # Most pull requests leave the harnesses to parity-main, which runs them on main a batch of merges at a time + # (.github/workflows/parity-main.yml; releases wait for it). A pull request still runs them itself when it changes + # a harness, an oracle, a probe or the runner, or carries the run-parity label (run-parity.yml, when it is added). + parity-scope: if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + outputs: + run: ${{ steps.scope.outputs.run }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + persist-credentials: false + - id: scope + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + LABELS: ${{ join(github.event.pull_request.labels.*.name, ' ') }} + run: | + changed=$(git diff --name-only "$(git merge-base "$BASE_SHA" HEAD)" HEAD) + harness=$(grep -E '^(tools/test_[a-z0-9_]+_parity\.py|tools/(parity[a-z_]*|lab)\.py|tools/parity_hosts\.json|mods/horizon/src/test/|crates/[^/]+/examples/|crates/horizon-client/src/game/[a-z_]*(fixture|harness)\.rs|\.github/workflows/parity[a-z-]*\.yml)' <<< "$changed" || true) + if [ -n "$harness" ] || [[ " $LABELS " == *" run-parity "* ]]; then + echo "run=true" >> "$GITHUB_OUTPUT" + echo "The pull request runs its harnesses: ${harness:-label run-parity}" + else + echo "run=false" >> "$GITHUB_OUTPUT" + echo "No harness, oracle, probe or runner change: parity-main checks this on main" + fi + parity: + needs: parity-scope + if: needs.parity-scope.outputs.run == 'true' uses: ./.github/workflows/parity.yml with: base: ${{ github.event.pull_request.base.sha }} diff --git a/.github/workflows/parity-main.yml b/.github/workflows/parity-main.yml new file mode 100644 index 000000000..1ddfb24bb --- /dev/null +++ b/.github/workflows/parity-main.yml @@ -0,0 +1,70 @@ +name: parity-main +# The vanilla harnesses on main, a batch of merges at a time (docs/release-flow.md#parity-on-main), on the Mac mini's +# runner. One run at a time: merges that land while a run goes on wait in one pending run (GitHub keeps only the +# newest), which checks every merge since main's last green parity-main (tools/parity_main.py base). On a failure it +# bisects the failing harnesses over those merges and comments on the pull request that broke them. Releases ship +# only a commit whose parity-main passed (tools/release_train.py), so nothing a harness catches reaches players. +on: + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read + # The comment on the merge that broke a harness. + pull-requests: write + # tools/parity_main.py base reads earlier runs. + actions: read +concurrency: + group: parity-main + cancel-in-progress: false +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + +jobs: + parity-main: + runs-on: [self-hosted, horizon-game] + timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + # Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs. + clean: false + - uses: dtolnay/rust-toolchain@stable + - name: Tools from the runner + run: bash tools/ci/runner-env.sh + - name: Vanilla data, and resources prepared by this preparer + run: bash tools/ci/vanilla-data.sh + - name: Main's last green parity-main + id: base + env: + GH_TOKEN: ${{ github.token }} + run: echo "sha=$(python3 tools/parity_main.py base)" >> "$GITHUB_OUTPUT" + - name: The harnesses the merges since then can affect + env: + PARITY_HOSTS: '' + BASE_SHA: ${{ steps.base.outputs.sha }} + run: | + echo "Merges since ${BASE_SHA}:" + git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD" + python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 + - name: The merge that broke them + if: failure() + env: + GH_TOKEN: ${{ github.token }} + PARITY_HOSTS: '' + BASE_SHA: ${{ steps.base.outputs.sha }} + run: | + rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true + python3 tools/parity_main.py bisect "$BASE_SHA" --comment + - name: Logs of the failed harnesses + if: failure() + uses: actions/upload-artifact@v4 + with: + name: parity-main-logs + path: .local/parity-main-logs/ + if-no-files-found: ignore + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4cba851fa..05f590096 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,7 @@ name: release # Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a -# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides: +# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides, +# for a commit whose checks and parity-main (the vanilla harnesses on main) both passed: # a release when 5 pull requests merged since the last one changed what players run and the newest merged 5 minutes # ago, or when the oldest has waited 6 hours, or at once for a pull request labelled release-now. # RELEASES_PAUSED=1 (repository variable) stops them; so does an open issue labelled release-blocker, forced runs too. @@ -18,7 +19,8 @@ name: release # gh workflow run release -f dry_run=false -f force=true # on main: release now, whatever the rules say on: workflow_run: - workflows: [checks] + # A game release ships a commit both passed on (parity-main runs on batches: the newest commit it passed on). + workflows: [checks, parity-main] types: [completed] branches: [main] schedule: @@ -64,8 +66,8 @@ jobs: env: GH_TOKEN: ${{ github.token }} RELEASES_PAUSED: ${{ vars.RELEASES_PAUSED }} - # The commit whose checks just passed; a dry run builds the branch it was started on; otherwise - # main's newest commit with green checks. + # The commit whose checks or parity-main just passed; a dry run builds the branch it was started on; + # otherwise main's newest commit with green checks and parity-main. HEAD_SHA: ${{ github.event.workflow_run.head_sha || (steps.mode.outputs.dry_run == 'true' && github.sha) || '' }} FORCE: ${{ inputs.force && 'yes' || '' }} run: | diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index d794b9c71..d64ec3087 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -20,6 +20,8 @@ python3 tools/parity.py --changed origin/main # those a branch's changes ca python3 tools/parity.py --changed-files paths.txt # the same for listed paths, in a copy without Git (tools/pr_ready.py) ``` +On CI, a pull request runs the parity job only when it changes a harness, an oracle, a probe or the runner; everything else is checked on main by `parity-main`, a batch of merges at a time, which bisects a failure to the merge that caused it (`tools/parity_main.py`; [release-flow.md](release-flow.md#parity-on-main)). Game releases wait for it. + Each harness runs unmodified under a tracer that records the files it depended on: its Python modules, its Java oracle and the oracle sources javac pulled in, other repository files it read, and the Rust sources of the probes it ran (from Cargo's `.d` dep-info files). A pass stands until one of those files, the pinned vanilla artifacts, `Cargo.lock` or the Rust/Java toolchains change. State and logs are in `.local/parity-runner/`; each harness's own outputs stay in its `.local//` directory. Vanilla oracle runs are reused as well. `tools/parity_shim.py` stands in for `java` and `javac`: it records each oracle run's outputs and the content of every file under the paths its arguments name, and replays the run while those are unchanged. After a Rust-only change a harness pays only for its Rust side (`block_update`: 53 s to 5 s). Files an oracle writes outside its named paths aren't tracked, so 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. diff --git a/docs/release-flow.md b/docs/release-flow.md index 4fb0209d9..b551bad21 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -13,7 +13,7 @@ reopened; labels never start it): | Job | Runs on | What | Time | | --- | --- | --- | --- | | `verify` | GitHub `ubuntu-latest` | Public-tree check, Python tests, rustfmt, clippy with warnings denied, Rust tests. Dependencies and the workspace build come from a cache saved by main's runs | ~4 min cold, less warm | -| `parity / parity` | The Mac mini's runner (`ludovics-mac-mini`, label `horizon-game`) | The vanilla harnesses the change can affect (`tools/parity.py --changed `) | seconds when nothing is affected; minutes per affected harness | +| `parity / parity` | The Mac mini's runner (`ludovics-mac-mini`, label `horizon-game`) | Only for a change to a harness, an oracle, a probe or the runner (or the `run-parity` label): the vanilla harnesses the change can affect (`tools/parity.py --changed `). Other pull requests skip it: [parity-main](#parity-on-main) checks them on main | seconds when nothing is affected; minutes per affected harness | Pushes to main run `verify` only; the nightly audit covers main's harnesses. @@ -80,10 +80,34 @@ gh api -X POST repos/ludovic111/horizon/branches/main/protection/required_status A skipped `parity` (a fork's pull request without the label) counts as passed, so requiring it never blocks a fork's pull request; the maintainer decides whether to run it. +## Parity on main + +Most pull requests merge on `verify` alone and leave the vanilla harnesses to `.github/workflows/parity-main.yml`, +which runs them on main a batch of merges at a time, on the Mac mini's runner: + +- It starts on every push to main, one run at a time (`concurrency: parity-main`). Merges that land while a run + goes on wait in one pending run: GitHub keeps only the newest and cancels the others, so the next run takes them + all. +- `tools/parity_main.py base` gives the newest commit main contains whose parity-main passed (else the last + merge's parent), and the run is `tools/parity.py --changed `: the union of the harnesses every merge + since then can affect, once, with every earlier pass reused. +- On a failure, `tools/parity_main.py bisect` checks out the batch's first-parent merges by halves and runs only + the failing harnesses, names the first merge they fail on in the run's summary and comments on its pull request + (`🤖 Agent: parity-main found that this merge breaks ...`). Fix it with a pull request as usual; the next + run checks from the last green commit again. +- Game releases ship only a commit both `checks` and `parity-main` passed on (`tools/release_train.py`, see + below), so a broken merge holds releases instead of reaching players. `release.yml` also starts when a + parity-main run finishes. A forced release (`force=true`) doesn't wait for parity-main. + +A pull request still runs its own parity job when it changes a harness script, an oracle +(`mods/horizon/src/test/`), a probe (`crates/*/examples/`, `game/*_fixture.rs`, `game/*_harness.rs`), the runner +(`tools/parity*.py`, `tools/lab.py`, `tools/parity_hosts.json`, `parity*.yml`), or carries the `run-parity` label +(`run-parity.yml` runs it when the label is added). + ## Game releases -`.github/workflows/release.yml` releases the game by itself. It starts after every green `checks` run of a push -to main, every 10 minutes (so a release waiting for merges to settle goes out without another merge), and by hand. +`.github/workflows/release.yml` releases the game by itself. It starts after every green `checks` or `parity-main` +run of a push to main (it releases a commit only once both passed on it), every 10 minutes (so a release waiting for merges to settle goes out without another merge), and by hand. ```mermaid flowchart LR diff --git a/tests/test_parity_main.py b/tests/test_parity_main.py new file mode 100644 index 000000000..7a72ecae5 --- /dev/null +++ b/tests/test_parity_main.py @@ -0,0 +1,43 @@ +"""tools/parity_main.py: the base of a parity-main run, and the bisect after a failure.""" +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +from tools import parity_main + + +class ParityMainTests(unittest.TestCase): + def test_first_bad_finds_the_first_failing_merge(self): + commits = list("abcdefgh") # h failed; the base before a passed + for culprit in commits: + tried = [] + fails = lambda commit: tried.append(commit) or commit >= culprit + self.assertEqual(parity_main.first_bad(commits, fails), culprit) + self.assertLessEqual(len(tried), 3, "log2 of 8 merges") + self.assertEqual(parity_main.first_bad(["a"], lambda commit: self.fail("nothing to try")), "a") + + def test_base_is_the_newest_green_run_head_contains(self): + with tempfile.TemporaryDirectory() as tmp, mock.patch.object(parity_main, "ROOT", Path(tmp)): + git = lambda *arguments: parity_main.git(*arguments).stdout.strip() + git("init", "-q") + for n in range(3): + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", str(n)) + head, parent, grandparent = git("rev-parse", "HEAD"), git("rev-parse", "HEAD^1"), git("rev-parse", "HEAD~2") + git("checkout", "-q", "-b", "side", grandparent) + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "side") + side = git("rev-parse", "HEAD") + git("checkout", "-q", head) + self.assertEqual(parity_main.base(runs=[side, grandparent, parent]), grandparent, + "a run on a commit HEAD doesn't contain is skipped") + self.assertEqual(parity_main.base(runs=[]), parent, "no green run yet: the last merge") + self.assertEqual(parity_main.base(runs=[head]), head) + + def test_a_harness_a_commit_does_not_have_cannot_fail_there(self): + with mock.patch.object(parity_main.subprocess, "run") as run: + self.assertFalse(parity_main.run_harnesses(["not_a_harness_yet"], 60)) + run.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_release_train.py b/tests/test_release_train.py index 56064fa42..ee1fbcae5 100644 --- a/tests/test_release_train.py +++ b/tests/test_release_train.py @@ -2,6 +2,7 @@ import datetime as dt from pathlib import Path import tempfile import unittest +from unittest import mock from tools import release_train as train @@ -147,6 +148,26 @@ class ReleaseTrainTests(unittest.TestCase): self.assertFalse(train.decision("game", [], NOW, new_line="0.3", blockers=[7])[0]) self.assertTrue(train.decision("game", [pr(1)], NOW, blockers=[])[0]) + def test_game_releases_ship_only_what_parity_main_passed(self): + def runs(parity, checks): + def gh_json(*arguments): + table = parity if "parity-main" in arguments else checks + if "--commit" in arguments: + sha = arguments[arguments.index("--commit") + 1] + return [{"status": s, "conclusion": c} for h, s, c in table if h == sha] + return [{"headSha": h, "status": s, "conclusion": c} for h, s, c in table] + return mock.patch.object(train, "gh_json", gh_json) + checks = [("c", "in_progress", ""), ("b", "completed", "success"), ("a", "completed", "success")] + with runs([("c", "queued", ""), ("b", "completed", "cancelled"), ("a", "completed", "success")], checks): + self.assertEqual(train.green_main_head(), "b", "checks alone: the newest green checks") + self.assertEqual(train.green_main_head(parity=True), "a", "a superseded parity-main run counts for nothing") + self.assertTrue(train.passed_on("parity-main", "a")) + self.assertFalse(train.passed_on("parity-main", "b")) + with runs([("b", "completed", "failure"), ("a", "completed", "success")], checks): + self.assertIsNone(train.green_main_head(parity=True), "a failed batch holds releases until fixed") + with runs([("c", "completed", "success")], checks): + self.assertIsNone(train.green_main_head(parity=True), "its checks must pass too") + def test_a_release_is_published_only_after_its_smoke_test_and_with_no_blocker(self): drew = {"error": None, "frames": 12710, "chunks": 81, "meshed_sections": 550, "player": [160.5, 71.0, 156.5]} self.assertIsNone(train.gate(drew, [])) diff --git a/tools/parity_main.py b/tools/parity_main.py new file mode 100644 index 000000000..ff319aed0 --- /dev/null +++ b/tools/parity_main.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""parity-main (.github/workflows/parity-main.yml): the vanilla harnesses run on main, a batch of merges at a time. + + python3 tools/parity_main.py base # the commit this run checks from: main's last green parity-main + python3 tools/parity_main.py bisect BASE # after a failure: the first merge since BASE that broke a harness + +`base` prints the newest commit on main whose parity-main run passed and that HEAD contains, else HEAD's first parent, +so a run tests every merge since the last green one (`tools/parity.py --changed `), however many landed while +the previous run went on. `bisect` reads the harnesses that failed (.local/parity-runner/last-run.json), checks out +the first-parent merges between BASE and HEAD by halves and runs only those harnesses, then names the first merge they +fail on (written to $GITHUB_STEP_SUMMARY and, with --comment, on its pull request). HEAD is checked out again at the end. +""" + +import argparse +import json +import os +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] +REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") +LAST_RUN = ROOT / ".local" / "parity-runner" / "last-run.json" + + +def git(*arguments, check=True): + result = subprocess.run(["git", *arguments], cwd=ROOT, capture_output=True, text=True) + if check and result.returncode: + sys.exit(f"git {' '.join(arguments)}: {result.stderr.strip()}") + return result + + +def green_runs(): + """Head commits of main's passing parity-main runs, newest first.""" + result = subprocess.run(["gh", "run", "list", "--repo", REPO, "--workflow", "parity-main", "--branch", "main", + "--status", "success", "--limit", "30", "--json", "headSha"], capture_output=True, text=True) + if result.returncode: + print(f"note: no parity-main history ({result.stderr.strip()})", file=sys.stderr) + return [] + return [run["headSha"] for run in json.loads(result.stdout or "[]")] + + +def base(head="HEAD", runs=None): + for sha in green_runs() if runs is None else runs: + if git("merge-base", "--is-ancestor", sha, head, check=False).returncode == 0: + return git("rev-parse", sha).stdout.strip() + return git("rev-parse", f"{head}^1").stdout.strip() + + +def first_bad(commits, fails): + """The first of commits (oldest first, the last known to fail; the one before them known to pass) where fails().""" + good, bad = -1, len(commits) - 1 + while bad - good > 1: + middle = (good + bad) // 2 + if fails(commits[middle]): + bad = middle + else: + good = middle + return commits[bad] + + +def harness_exists(name): + return (ROOT / "tools" / f"test_{name.split('#')[0]}_parity.py").exists() + + +def run_harnesses(names, timeout): + """Whether any of the harnesses fails at the checked-out commit (those it doesn't have yet can't).""" + present = [name for name in names if harness_exists(name)] + if not present: + return False + return subprocess.run([sys.executable, "tools/parity.py", *present, "--timeout", str(timeout)], cwd=ROOT).returncode != 0 + + +def bisect(since, timeout, comment): + failed = [] + if LAST_RUN.exists(): + failed = json.loads(LAST_RUN.read_text(encoding="utf-8")).get("failed") or [] + if not failed: + print("No failed harness recorded: nothing to bisect.") + return 0 + head = git("rev-parse", "HEAD").stdout.strip() + commits = git("rev-list", "--first-parent", "--reverse", f"{since}..{head}").stdout.split() + if not commits: + print("No merge since the base.") + return 0 + + def fails(commit): + print(f"--- {commit[:9]} {git('log', '-1', '--format=%s', commit).stdout.strip()}", flush=True) + git("checkout", "-q", "--detach", commit) + return run_harnesses(failed, timeout) + + try: + culprit = first_bad(commits, fails) if len(commits) > 1 else commits[0] + finally: + git("checkout", "-q", "--detach", head) + subject = git("log", "-1", "--format=%s", culprit).stdout.strip() + number = re.search(r"Merge pull request #(\d+)", subject) + line = (f"parity-main: {', '.join(failed)} first fail at {culprit[:9]} ({subject}), " + f"of {len(commits)} merges since {since[:9]}.") + print(line) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary: + summary.write(f"### {line}\n") + if comment and number: + url = f"{os.environ.get('GITHUB_SERVER_URL', 'https://github.com')}/{REPO}/actions/runs/{os.environ.get('GITHUB_RUN_ID', '')}" + body = (f"🤖 Agent: parity-main found that this merge breaks {', '.join(f'`{name}`' for name in failed)} on main " + f"(bisected over {len(commits)} merges: {url}). Releases wait until parity-main passes again.") + subprocess.run(["gh", "pr", "comment", number.group(1), "--repo", REPO, "--body", body]) + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + commands.add_parser("base") + bisecting = commands.add_parser("bisect") + bisecting.add_argument("since", help="the last commit known to pass (the run's base)") + bisecting.add_argument("--timeout", type=int, default=2400, help="seconds per harness") + bisecting.add_argument("--comment", action="store_true", help="comment on the breaking merge's pull request") + args = parser.parse_args() + if args.command == "base": + print(base()) + return 0 + return bisect(args.since, args.timeout, args.comment) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release_train.py b/tools/release_train.py index 48d4d46cf..72d81ce57 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -414,13 +414,26 @@ def gather(kind, head, releases=None): return last, prs -def green_main_head(): - """The newest commit on main whose checks passed: what an automatic release builds.""" - runs = gh_json("run", "list", "--repo", REPO, "--workflow", "checks", "--branch", "main", "--event", "push", +def passed_on(workflow, sha): + """Whether the newest finished push run of workflow on main for commit sha passed.""" + runs = gh_json("run", "list", "--repo", REPO, "--workflow", workflow, "--branch", "main", "--event", "push", + "--commit", sha, "--limit", "5", "--json", "status,conclusion") + done = [entry for entry in runs if entry["status"] == "completed" and entry["conclusion"] != "cancelled"] + return bool(done) and done[0]["conclusion"] == "success" + + +def green_main_head(parity=False): + """The newest commit on main whose checks passed: what an automatic release builds. With parity (game + releases), the newest commit parity-main passed on, if its checks passed too: parity-main runs on batches of + merges, so the commits a run skipped are covered by the next one, and a superseded run counts for nothing.""" + workflow = "parity-main" if parity else "checks" + runs = gh_json("run", "list", "--repo", REPO, "--workflow", workflow, "--branch", "main", "--event", "push", "--limit", "10", "--json", "headSha,status,conclusion") for entry in runs: - if entry["status"] == "completed": - return entry["headSha"] if entry["conclusion"] == "success" else None + if entry["status"] == "completed" and entry["conclusion"] != "cancelled": + if entry["conclusion"] != "success": + return None + return entry["headSha"] if not parity or passed_on("checks", entry["headSha"]) else None return None @@ -437,7 +450,7 @@ def main(): parser.add_argument("--kind", choices=["game", "launcher"], required=True) parser.add_argument("--head", help="the commit to release (default: the newest commit on main whose checks passed)") parser.add_argument("--tag", help="notes: the release's tag") - parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle or while paused") + parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle, while paused or before parity-main passed") parser.add_argument("--out", type=Path, help="notes: write title.txt and body.md here") parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)") parser.add_argument("--smoke", type=Path, help="gate: the release smoke test's report (smoke-test.json)") @@ -456,9 +469,12 @@ def main(): summary.write(f"### {line}\n") return 1 if problem else 0 - head = args.head or green_main_head() + # Game releases ship only a commit the vanilla harnesses passed on (parity-main, docs/release-flow.md). + parity = args.kind == "game" and args.command == "decide" and not args.force + head = args.head or green_main_head(parity) if not head: - result = {"release": False, "reason": "main's latest checks did not pass"} + result = {"release": False, "reason": "main's latest checks did not pass" + ( + " or parity-main did not pass on them" if parity else "")} print(json.dumps(result, indent=1)) write_outputs({"release": "false", "reason": result["reason"]}) return 0 @@ -482,6 +498,8 @@ def main(): blockers = open_blockers() if args.kind == "game" else [] release, reason = decision(args.kind, prs, now, os.environ.get("RELEASES_PAUSED") == "1", args.force, new_line, blockers) + if release and args.head and parity and not (passed_on("parity-main", head) and passed_on("checks", head)): + release, reason = False, f"waiting for checks and parity-main to pass on {head[:9]}" minor = any("feature" in pr["labels"] for pr in prs if pr["paths"]) tag = next_game_tag(tags, now.date(), line) if args.kind == "game" else next_launcher_tag(tags, minor, line) result = { From 40c08c2d12ebfb8d0a56e9bc2f71b72460cfff0c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:38:47 +0100 Subject: [PATCH 37/43] streaming: check every fourth cell of the cover test in debug builds the_grid_answers_as_the_scan compared the grid with the scan on every cell of 60 cases and took 20 of the ~30 s of `cargo test -p horizon-client` on the ThinkPad. A debug build now checks every fourth cell of each row, shifted by row and case, so the cases together still meet every cell position relative to the areas; a release build checks every cell. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/streaming.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 55a2f0086..13b19fefc 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -2148,8 +2148,13 @@ mod cover_tests { } /// Every question streaming asks gets the same answer with the grid. + /// + /// A debug build checks every fourth cell of each row, shifted by row and case so the cases still cover every + /// cell's position relative to the areas: the full check took 20 of the ~30 s of the crate's tests. + /// `cargo test --release -p horizon-client --lib the_grid_answers_as_the_scan` checks every cell. #[test] fn the_grid_answers_as_the_scan() { + let stride = if cfg!(debug_assertions) { 4 } else { 1 }; let mut seed = 0x9E37_79B9_7F4A_7C15u64; let forced: HashSet<(i32, i32)> = [(40, -40)].into(); for case in 0..60 { @@ -2165,7 +2170,8 @@ mod cover_tests { let (scan, grid) = (ranges(None), ranges(Some(&cover))); let span = [4, 30, 120][case % 3] + 40; for z in -span..=span { - for x in -span..=span { + let first = -span + (z + case as i32).rem_euclid(stride); + for x in (first..=span).step_by(stride as usize) { for m in 0..=ExtraCover::REACH + 2 { assert_eq!( scan.in_extra(x, z, m), From 5034e4557dba8c54ebd406a50ef4449b8d7ec2ea Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:44:22 +0100 Subject: [PATCH 38/43] parity: clear rust--parity outputs after a pass, reuse oracles on CI Disk: clear_large_outputs only looked at .local directories named after the harness, so the 174 harnesses writing to rust--parity kept every dump (86 GB in one runner checkout, 13 GB for state_provider alone). It now clears those too, keeps vanilla outputs only up to 256 MB (larger ones cost more disk than rerunning their oracle), and handles shard names. collision, world and geometry dropped one mkdtemp run directory per run (11 GB): each run now removes the earlier ones. Time: harnesses inherited the runner's stdin, a pipe on GitHub's runner, and parity_shim never reuses an oracle run whose stdin is a pipe, so oracle reuse never worked on CI. Harnesses now get /dev/null. CI: parity.yml falls back to the head's own selection when the names main's `--list` printed don't match its summary count. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/parity.yml | 11 ++++++++++- tests/test_parity_runner.py | 14 ++++++++++++++ tools/parity.py | 20 ++++++++++++++------ tools/test_collision_parity.py | 3 +++ tools/test_geometry_parity.py | 3 +++ tools/test_world_parity.py | 3 +++ 6 files changed, 47 insertions(+), 7 deletions(-) diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index be87bc965..9dcb21775 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -68,7 +68,16 @@ jobs: exit fi names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true) - if [ -z "$names" ]; then + # The summary line says how many would run: a count that doesn't match the names read (a format change) + # must not let the job pass untested. + expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p') + count=$(printf '%s' "$names" | grep -c . || true) + if [ -z "$expected" ] || [ "$expected" != "$count" ]; then + echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs" + own + exit + fi + if [ "$count" = 0 ]; then echo "Nothing to run." exit 0 fi diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index d10fde854..2d16e7179 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -300,3 +300,17 @@ class LargeOutputTests(unittest.TestCase): self.assertFalse((own / "dump.txt").exists()) # chunk_generation may still be writing there. self.assertTrue((shared / "dump.txt").exists()) + + def test_rust_named_directories_and_big_oracle_outputs_go_too(self): + with tempfile.TemporaryDirectory() as tmp: + local, state = Path(tmp) / ".local", Path(tmp) / "state" + own = local / "rust-state-provider-parity" + own.mkdir(parents=True) + for name, size in (("rust.txt", 16), ("server.txt", 16), ("client.txt", 64), ("report.json", 4)): + (own / name).write_bytes(b"x" * size) + trace = {"commands": [["java", "Oracle", str(own)], ["probe", "fixture", str(own)]]} + with mock.patch.multiple(parity, LOCAL=local, STATE_DIR=state, LARGE_OUTPUT=8, KEPT_ORACLE_OUTPUT=32): + listing = parity.outputs_listing("state_provider#2", fresh=True) + listing.write_text(f"{own / 'server.txt'}\n{own / 'client.txt'}\n") + parity.clear_large_outputs("state_provider#2", trace) + self.assertEqual(sorted(path.name for path in own.iterdir()), ["report.json", "server.txt"]) diff --git a/tools/parity.py b/tools/parity.py index dc5fdb1c9..3f18b922d 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -657,6 +657,9 @@ def prebuild(artifacts, jobs): LARGE_OUTPUT = 64 << 20 +# Vanilla outputs above this are deleted after a pass too: rerunning those few oracles (12 harnesses on the Mac +# mini's runner) costs less than the 26 GB they held in every checkout; smaller ones stay for oracle reuse. +KEPT_ORACLE_OUTPUT = 256 << 20 OWN_DIRECTORIES = {"parity-target", "parity-runner", "rea", "logs", "gate"} @@ -672,11 +675,12 @@ def clear_large_outputs(name, trace): """After a pass, delete the large files a harness regenerates on every run. Harness outputs reach gigabytes and used to stay in every worktree. Vanilla - oracle outputs are kept, since reusing an oracle run needs them in place; - everything else large under the harness's .local directories is rebuilt on - its next run.""" + oracle outputs under KEPT_ORACLE_OUTPUT are kept, since reusing an oracle + run needs them in place; everything else large under the harness's .local + directories (`...` or `rust--parity`) is rebuilt on its next run.""" local = LOCAL.resolve() keep = {os.path.realpath(line) for line in outputs_listing(name).read_text(encoding="utf-8").splitlines() if line} + own = name.split("#")[0].replace("_", "-") directories = set() for command in trace["commands"]: for argument in command[1:]: @@ -688,12 +692,13 @@ def clear_large_outputs(name, trace): # Only the harness's own directory: another harness running beside it may be writing # large files in a directory this one merely read (decorated_region compiles its oracle # into chunk-generation-parity while chunk_generation writes its dumps there). - if top not in OWN_DIRECTORIES and top.startswith(name.replace("_", "-")): + if top not in OWN_DIRECTORIES and (top.startswith(own) or top == f"rust-{own}-parity"): directories.add(local / top) for directory in directories: for file in (directory.rglob("*") if directory.is_dir() else []): try: - if file.is_file() and not file.is_symlink() and file.stat().st_size >= LARGE_OUTPUT and str(file) not in keep: + size = file.stat().st_size if file.is_file() and not file.is_symlink() else 0 + if size >= LARGE_OUTPUT and (str(file) not in keep or size > KEPT_ORACLE_OUTPUT): file.unlink() except OSError: pass @@ -828,8 +833,11 @@ class LocalExecutor: environment.pop("PARITY_SHARD", None) if shard: environment["PARITY_SHARD"] = shard + # stdin from /dev/null: tools/parity_shim.py never reuses an oracle run that reads a pipe, and CI runners + # (and --worker's ssh) give the runner one, which kept oracle reuse off on CI. process = subprocess.Popen([sys.executable, str(Path(__file__)), "--trace", str(trace), str(script)], - cwd=ROOT, env=environment, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + cwd=ROOT, env=environment, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) self.running[name] = {"process": process, "started": time.monotonic(), "log": log, "expected": expected, "slot": slot, "script": script} return True diff --git a/tools/test_collision_parity.py b/tools/test_collision_parity.py index ad99ab960..26f7f25df 100644 --- a/tools/test_collision_parity.py +++ b/tools/test_collision_parity.py @@ -5,6 +5,7 @@ import json import os from pathlib import Path import platform +import shutil import subprocess import tempfile @@ -37,6 +38,8 @@ def main(): if args.prepare: lab.prepare() lock, jars, libraries = test_rust_parity.verify_artifacts() + for earlier in directory.glob("run-*"): # one run per run used to stay behind: 5 GB here after a few weeks + shutil.rmtree(earlier, ignore_errors=True) base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java" sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/probe/collision_fixture.rs"] diff --git a/tools/test_geometry_parity.py b/tools/test_geometry_parity.py index 54ebc21ae..fa58bf66f 100644 --- a/tools/test_geometry_parity.py +++ b/tools/test_geometry_parity.py @@ -9,6 +9,7 @@ from pathlib import Path import platform import random import struct +import shutil import subprocess import tempfile @@ -273,6 +274,8 @@ def main(): if args.prepare: lab.prepare() lock, jars, libraries = test_rust_parity.verify_artifacts() + for earlier in directory.glob("run-*"): # one run per run used to stay behind: 5 GB here after a few weeks + shutil.rmtree(earlier, ignore_errors=True) base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) commands = list(corpus()) inputs = base / "inputs.txt" diff --git a/tools/test_world_parity.py b/tools/test_world_parity.py index 0b4a3deb7..9344a47b0 100644 --- a/tools/test_world_parity.py +++ b/tools/test_world_parity.py @@ -5,6 +5,7 @@ import json import os from pathlib import Path import platform +import shutil import subprocess import tempfile @@ -35,6 +36,8 @@ def main(): if args.prepare: lab.prepare() lock, jars, libraries = test_rust_parity.verify_artifacts() + for earlier in directory.glob("run-*"): # one run per run used to stay behind: 5 GB here after a few weeks + shutil.rmtree(earlier, ignore_errors=True) base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) classes = base / "classes" classes.mkdir() From 9db6a0ee48a6862df8e27fe0e5cb587a61c67e0f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:23:27 +0100 Subject: [PATCH 39/43] CI: parity-main stays on the Mac; heat check on a median, boot as the first sign; nix roots fixed nix-build names a dev output's GC root -dev, so the runner's PKG_CONFIG_PATH pointed at links that didn't exist and every client build failed on libudev; it now uses the store path nix-build prints. The package temperature spikes for a second under load, so the heat check takes the median of 5 readings. Restarting the watcher no longer throttles a running job. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/parity-main.yml | 4 +++- docs/release-flow.md | 5 +++-- tools/ci/linux-runner.sh | 5 +++-- tools/ci/runner_pause.py | 26 ++++++++++++++++---------- 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/.github/workflows/parity-main.yml b/.github/workflows/parity-main.yml index 1ddfb24bb..1debcc694 100644 --- a/.github/workflows/parity-main.yml +++ b/.github/workflows/parity-main.yml @@ -23,7 +23,9 @@ env: jobs: parity-main: - runs-on: [self-hosted, horizon-game] + # The Mac mini's runners only: a desktop job slowed down because the maintainer came back could time out, and a + # failure here bisects and comments on merges. + runs-on: [self-hosted, horizon-game, macOS] timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures steps: - uses: actions/checkout@v4 diff --git a/docs/release-flow.md b/docs/release-flow.md index 28d1feef9..dc96498a0 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -90,8 +90,9 @@ processes, fleet-load's own detection, or a process outside the CI slice using t under way is throttled to 2 threads at the lowest weight and the runner stops after it: freezing the job would make GitHub drop it as lost and the harnesses time out. Old pull requests' `runner-env.sh` know only the Mac: the runner's `.env` and `.path` give their jobs Python, the JDK and the vanilla data (`HORIZON_SHARED_SOURCE`) all the -same. The nightly audit stays on the Mac mini's runners, so its comparison with the previous night is always made -on one platform. +same. The nightly audit and parity-main stay on the Mac mini's runners: the audit compares with the previous night, +so it stays on one platform, and a parity-main job slowed down on the desktop because he came back could time out, +and its failures bisect and comment on merges. ## Merging diff --git a/tools/ci/linux-runner.sh b/tools/ci/linux-runner.sh index 1bd587e79..c7235f5c1 100755 --- a/tools/ci/linux-runner.sh +++ b/tools/ci/linux-runner.sh @@ -24,8 +24,9 @@ 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 '' -A "$1" -o "$dir/nix/$2" > /dev/null && readlink -f "$dir/nix/$2"; } +# 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 '' -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} diff --git a/tools/ci/runner_pause.py b/tools/ci/runner_pause.py index 35476a0b2..8fa0a4c5b 100755 --- a/tools/ci/runner_pause.py +++ b/tools/ci/runner_pause.py @@ -5,7 +5,7 @@ The runner works while nobody uses the machine: its screen locked, or untouched 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 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 @@ -63,7 +63,7 @@ class Input: def __init__(self): self.devices = {} # path -> file descriptor - self.last = time.monotonic() # a start counts as input: nothing is known yet + self.last = 0.0 # the boot (the monotonic clock's zero on Linux) counts as input def poll(self): try: @@ -115,14 +115,20 @@ def at_the_screen(input_idle): def too_hot(): - """The CPU package above TEMP_LIMIT °C (coretemp or k10temp).""" + """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() in ("coretemp", "k10temp"): - celsius = int((monitor / "temp1_input").read_text()) / 1000 - return f"CPU at {celsius:.0f} °C" if celsius >= TEMP_LIMIT else None + 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): - pass + continue + celsius = sorted(readings)[2] + return f"CPU at {celsius:.0f} °C" if celsius >= TEMP_LIMIT else None return None @@ -219,9 +225,9 @@ def pause_reason(hot, keys): def main(): hot, keys = {}, Input() - # A boot (or a restart of this watcher) counts as a sign: the runner starts RESUME_AFTER seconds later at the - # earliest, which leaves time to log in after switching the machine on. - last_sign = time.monotonic() + # 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) From bdbf67ef9399a05e741c64c85e46e98fec69964e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:31:38 +0100 Subject: [PATCH 40/43] pr_ready: work out the affected harnesses once, not once per harness affected_here called parity.affected_harnesses inside the filter, once for each of the 343 harnesses. Since the selection reads the Rust items each probe reaches (#1964) one call takes about a minute and a half, so pr_ready sat for hours before its first step. Co-Authored-By: Claude Opus 5.5 --- tools/pr_ready.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/pr_ready.py b/tools/pr_ready.py index 505de28c1..4a3da6bae 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -164,7 +164,8 @@ def affected_here(changed): (parity.SHARED / "dependencies" / f"{name}.json").exists() for name in found) if not known and not changed & parity.SHARED_INPUTS: return None - return harness_names(name for name in found if name in parity.affected_harnesses(found, records, changed)) + affected = parity.affected_harnesses(found, records, changed) + return harness_names(name for name in found if name in affected) def short_list(names, limit=12): From 49bbdf8954bdc8958bc6f8a2e7917bb8035f710c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:38:23 +0100 Subject: [PATCH 41/43] CI: the desktop's CI slice gets half the threads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On all 24, a cargo build held ludodesktop's CPU at 92 °C and the watcher kept pausing; at half, harnesses run at a median of 80 °C. Co-Authored-By: Claude Opus 5.5 --- tools/ci/linux-runner.sh | 1 + tools/ci/runner_pause.py | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/ci/linux-runner.sh b/tools/ci/linux-runner.sh index c7235f5c1..699742bf1 100755 --- a/tools/ci/linux-runner.sh +++ b/tools/ci/linux-runner.sh @@ -131,6 +131,7 @@ Description=Horizon CI: the runner's jobs and parity workers sent from other mac [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 diff --git a/tools/ci/runner_pause.py b/tools/ci/runner_pause.py index 8fa0a4c5b..845627243 100755 --- a/tools/ci/runner_pause.py +++ b/tools/ci/runner_pause.py @@ -36,6 +36,8 @@ 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)) @@ -199,7 +201,7 @@ 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=") + systemctl("set-property", "--runtime", SLICE, "CPUWeight=20", "IOWeight=20", f"CPUQuota={NORMAL_CPUS * 100}%") def pause_reason(hot, keys): From 160c1e8b7a3bebcd7157feff5c4cf17ada0198c2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:54:02 +0100 Subject: [PATCH 42/43] CI: a failed preparation leaves nothing in .local When horizon-prepare failed, vanilla-data.sh deleted the preparation folder but kept what it had already written to .local/ (horizon-client, horizon-client-motion, ...). The next job then saw those real folders as already there: its preparation listed only horizon-client-structures in .entries, and the checkout kept using the stale resources outside the per-key cache. Now a failed preparation removes the .local/ entries it created; a job first removes real folders named like preparation outputs, and makes again a preparation whose .entries lacks horizon-client. Co-Authored-By: Claude Opus 5.5 --- tools/ci/vanilla-data.sh | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/tools/ci/vanilla-data.sh b/tools/ci/vanilla-data.sh index 5276c54e9..f548e1f14 100755 --- a/tools/ci/vanilla-data.sh +++ b/tools/ci/vanilla-data.sh @@ -42,7 +42,21 @@ until mkdir "$lock" 2>/dev/null; do done trap 'rmdir "$lock" 2>/dev/null || true' EXIT # horizon-prepare writes .local/horizon-client and its exporters' outputs beside it: all of them live in -# $prepared, listed in $prepared/.entries, and .local/ links to them. +# $prepared, listed in $prepared/.entries, and .local/ links to them. A real folder of that kind in .local/ is +# what an older failed preparation left: it would hide the preparations (and a new one would not count it as its +# own output), so it goes. +outputs=$({ cat "$shared"/prepared/*/.entries; cd .local && ls -d horizon-client*; } 2>/dev/null || true) +for name in $(echo "$outputs" | LC_ALL=C sort -u); do + if [ -e ".local/$name" ] && [ ! -L ".local/$name" ]; then + rm -rf ".local/${name:?}" + echo "Removed .local/$name, left by a failed preparation" + fi +done +# A preparation made while such a folder was there did not list it (horizon-client above all), so it is made again. +if [ -f "$prepared/.entries" ] && ! grep -qx horizon-client "$prepared/.entries"; then + echo "Preparation $key lacks horizon-client: preparing again" + rm -rf "$prepared" +fi if [ ! -f "$prepared/.entries" ]; then echo "Preparing resources with this checkout's horizon-prepare ($key)" rm -rf "$prepared" && mkdir -p "$prepared" @@ -55,6 +69,9 @@ if [ ! -f "$prepared/.entries" ]; then cargo build --release --locked -p horizon-prepare if ! target/release/horizon-prepare --root "$PWD" > "$RUNNER_TEMP/prepare.log" 2>&1; then tail -40 "$RUNNER_TEMP/prepare.log" + # Nothing of a failed preparation stays in .local/: the next job prepares again. + LC_ALL=C comm -13 <(echo "$before") <(ls -1A .local | LC_ALL=C sort) | + while read -r name; do rm -rf ".local/${name:?}"; done rm -rf "$prepared" exit 1 fi From d782e455a41f21e79675347c4314c9e8e2bdb535 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:55:57 +0100 Subject: [PATCH 43/43] docs: the desktop's CI slice gets half the threads Co-Authored-By: Claude Opus 5.5 --- docs/release-flow.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/release-flow.md b/docs/release-flow.md index dc96498a0..7bb64d21e 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -78,8 +78,8 @@ time, under a lock) and the parity passes and slots. `horizon-game` once a full trial has passed there) runs on the maintainer's Linux desktop while nobody uses it: its screen locked, or untouched for 15 minutes (his rule, 2026-10-26). `tools/ci/linux-runner.sh install`, run there as him, registers it and installs two systemd user services: `horizon-runner` (the runner, in -`~/.actions-runners/horizon`, nice 19, in `horizon-ci.slice` with CPU and I/O weight 20 and memory capped at two -thirds of the RAM; `CARGO_BUILD_JOBS` and the harness slots at 8, after the machine froze under ~7 cold cargo +`~/.actions-runners/horizon`, nice 19, in `horizon-ci.slice` with CPU and I/O weight 20, half the threads (on all of +them the CPU package reached 92–96 °C) and memory capped at two thirds of the RAM; `CARGO_BUILD_JOBS` and the harness slots at 8, after the machine froze under ~7 cold cargo builds on 2026-10-14; its own Rust install; the JDK, sccache and the build libraries from nixpkgs; its own `vscreen` so no game it starts reaches his screen) and `horizon-runner-pause` (`tools/ci/runner_pause.py`), the only thing that starts the runner. The watcher stops it at once on keyboard, mouse or gamepad input (read from