horizon-bots and tools/server_bench.py: the first server benchmark against vanilla
horizon-bots is a load client on horizon-protocol for any 26.3 server: offline login, configuration, keep-alives, pings, teleports, chunk-batch acknowledgements, and movement at 20 Hz. The bots play in creative and fly above their spawn point, so they need no world of their own and no server refuses their moves; idle, walk, explore and mixed behaviours are deterministic from a seed. tools/server_bench.py runs the same bots on Horizon's server (horizon-server run) and on the pinned vanilla jar, each fresh from the same server.properties, and measures MSPT from each server's own /tick query, RSS and CPU of the process tree, the chunks the bots receive, and the start time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+8
@@ -1398,6 +1398,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-bots"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-protocol",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-client"
|
||||
version = "0.1.0"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
exclude = ["launcher", "crates/horizon-telemetry-server"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "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-mod-sdk/examples/coords-hud", "xtask"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "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-mod-sdk/examples/coords-hud", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "horizon-bots"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Load-test bots for Minecraft Java Edition 26.3 servers (docs/server.md, section 9)"
|
||||
|
||||
[dependencies]
|
||||
horizon-protocol = { path = "../horizon-protocol" }
|
||||
serde_json = "1.0.151"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,589 @@
|
||||
//! `horizon-bots`: load-test bots for any Minecraft Java Edition 26.3 server, vanilla, Paper or Horizon
|
||||
//! (docs/server.md, section 9). Each bot logs in offline, goes through configuration as vanilla's client
|
||||
//! does, answers keep-alives and pings, accepts teleports, acknowledges chunk batches, and moves at 20 Hz.
|
||||
//!
|
||||
//! Bots fly a little above the ground, so the server must give them creative mode (`gamemode=creative`
|
||||
//! and `force-gamemode=true`): they never touch blocks, so they need no world of their own, and no server
|
||||
//! can refuse their moves for walking into terrain. Every behaviour is deterministic from `--seed`.
|
||||
//!
|
||||
//! horizon-bots --server 127.0.0.1:25565 --bots 25 --behaviour mixed --seconds 360 --report bots.json
|
||||
//!
|
||||
//! It prints one JSON line a second (bots online, chunks received) and writes a summary with `--report`.
|
||||
|
||||
use horizon_protocol::{
|
||||
PROTOCOL_VERSION,
|
||||
buf::{Reader, Writer},
|
||||
connection::{ConnWriter, Connection},
|
||||
crypto::offline_uuid,
|
||||
ids,
|
||||
packets::{
|
||||
Empty, configuration,
|
||||
handshake::{self, Intention},
|
||||
login::{self, ServerHello},
|
||||
play,
|
||||
},
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const HELP: &str = "\
|
||||
horizon-bots: load-test bots for a Minecraft Java Edition 26.3 server (offline mode, creative)
|
||||
|
||||
--server HOST:PORT default 127.0.0.1:25565
|
||||
--bots N default 10
|
||||
--behaviour B idle, walk, explore or mixed (60 % walk, 20 % explore, 20 % idle); default mixed
|
||||
--join-every SECONDS default 1
|
||||
--seconds N how long to run after the first bot joins; default 60
|
||||
--view-distance N what the bots ask for; default 10
|
||||
--seed N default 12345
|
||||
--name PREFIX bot names: PREFIX0, PREFIX1...; default Bot
|
||||
--report FILE a JSON summary at the end
|
||||
";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Behaviour {
|
||||
Idle,
|
||||
Walk,
|
||||
Explore,
|
||||
}
|
||||
|
||||
impl Behaviour {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Idle => "idle",
|
||||
Self::Walk => "walk",
|
||||
Self::Explore => "explore",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Options {
|
||||
host: String,
|
||||
port: u16,
|
||||
bots: usize,
|
||||
behaviour: String,
|
||||
join_every: f64,
|
||||
seconds: u64,
|
||||
view_distance: i8,
|
||||
seed: u64,
|
||||
name: String,
|
||||
report: Option<String>,
|
||||
}
|
||||
|
||||
fn options() -> Result<Options, String> {
|
||||
let mut o = Options {
|
||||
host: "127.0.0.1".into(),
|
||||
port: 25565,
|
||||
bots: 10,
|
||||
behaviour: "mixed".into(),
|
||||
join_every: 1.0,
|
||||
seconds: 60,
|
||||
view_distance: 10,
|
||||
seed: 12345,
|
||||
name: "Bot".into(),
|
||||
report: None,
|
||||
};
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
if arg == "-h" || arg == "--help" {
|
||||
print!("{HELP}");
|
||||
std::process::exit(0);
|
||||
}
|
||||
let value = args.next().ok_or(format!("{arg} needs a value"))?;
|
||||
let number = |what: &str| format!("{arg} needs {what}, not {value:?}");
|
||||
match arg.as_str() {
|
||||
"--server" => {
|
||||
let (host, port) = value.rsplit_once(':').unwrap_or((&value, "25565"));
|
||||
o.host = host.into();
|
||||
o.port = port.parse().map_err(|_| number("a port"))?;
|
||||
}
|
||||
"--bots" => o.bots = value.parse().map_err(|_| number("a number"))?,
|
||||
"--behaviour" => o.behaviour = value,
|
||||
"--join-every" => o.join_every = value.parse().map_err(|_| number("seconds"))?,
|
||||
"--seconds" => o.seconds = value.parse().map_err(|_| number("seconds"))?,
|
||||
"--view-distance" => o.view_distance = value.parse().map_err(|_| number("2 to 32"))?,
|
||||
"--seed" => o.seed = value.parse().map_err(|_| number("a number"))?,
|
||||
"--name" => o.name = value,
|
||||
"--report" => o.report = Some(value),
|
||||
_ => return Err(format!("unknown option {arg}; --help lists them")),
|
||||
}
|
||||
}
|
||||
if !["idle", "walk", "explore", "mixed"].contains(&o.behaviour.as_str()) {
|
||||
return Err(format!(
|
||||
"--behaviour {}: use idle, walk, explore or mixed",
|
||||
o.behaviour
|
||||
));
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// What one bot is doing, shared between its reader and its ticks.
|
||||
#[derive(Default)]
|
||||
struct Bot {
|
||||
online: AtomicBool,
|
||||
chunks: AtomicU64,
|
||||
/// Where the server last put the bot (a teleport), to start from.
|
||||
teleport: Mutex<Option<[f64; 3]>>,
|
||||
error: Mutex<Option<String>>,
|
||||
joined_after_ms: AtomicU64,
|
||||
}
|
||||
|
||||
/// A small deterministic generator (SplitMix64), so every run moves the bots the same way.
|
||||
struct Random(u64);
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
fn unit(&mut self) -> f64 {
|
||||
(self.next() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
}
|
||||
|
||||
fn raw(id: i32, write: impl FnOnce(&mut Writer)) -> Vec<u8> {
|
||||
let mut w = Writer::new();
|
||||
w.varint(id);
|
||||
write(&mut w);
|
||||
w.data
|
||||
}
|
||||
|
||||
fn err(e: impl std::fmt::Display) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
/// Handshake, offline login and configuration; returns the connection in the play state.
|
||||
fn join(o: &Options, name: &str) -> Result<Connection, String> {
|
||||
let mut c = Connection::connect(&o.host, o.port, Duration::from_secs(10)).map_err(err)?;
|
||||
c.send(
|
||||
&handshake::Serverbound::Intention(Intention {
|
||||
protocol: PROTOCOL_VERSION,
|
||||
host: o.host.clone(),
|
||||
port: o.port,
|
||||
intent: handshake::LOGIN,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?;
|
||||
c.send(
|
||||
&login::Serverbound::Hello(ServerHello {
|
||||
name: name.into(),
|
||||
uuid: offline_uuid(name),
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?;
|
||||
loop {
|
||||
let (id, body) = c.recv().map_err(err)?;
|
||||
match login::Clientbound::decode(id, &body).map_err(err)? {
|
||||
login::Clientbound::Compression(p) => c.set_compression(p.threshold),
|
||||
login::Clientbound::LoginFinished(_) => {
|
||||
c.send(&login::Serverbound::LoginAcknowledged(Empty).encode())
|
||||
.map_err(err)?;
|
||||
break;
|
||||
}
|
||||
login::Clientbound::Disconnect(p) => return Err(format!("refused: {}", p.reason_json)),
|
||||
login::Clientbound::Hello(_) => {
|
||||
return Err("the server is in online mode; bots need online-mode=false".into());
|
||||
}
|
||||
login::Clientbound::CustomQuery(p) => c
|
||||
.send(
|
||||
&login::Serverbound::CustomQueryAnswer(login::CustomQueryAnswer {
|
||||
transaction: p.transaction,
|
||||
payload: None,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?,
|
||||
login::Clientbound::CookieRequest(p) => c
|
||||
.send(
|
||||
&login::Serverbound::CookieResponse(login::CookieResponse {
|
||||
key: p.key,
|
||||
payload: None,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?,
|
||||
login::Clientbound::Unknown(..) => {}
|
||||
}
|
||||
}
|
||||
use ids::configuration::clientbound as cb;
|
||||
c.send(
|
||||
&configuration::Serverbound::ClientInformation(configuration::ClientInformation::new(
|
||||
o.view_distance,
|
||||
))
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?;
|
||||
loop {
|
||||
let (id, body) = c.recv().map_err(err)?;
|
||||
let reply = match id {
|
||||
cb::SELECT_KNOWN_PACKS
|
||||
| cb::KEEP_ALIVE
|
||||
| cb::PING
|
||||
| cb::CODE_OF_CONDUCT
|
||||
| cb::COOKIE_REQUEST
|
||||
| cb::DISCONNECT
|
||||
| cb::FINISH_CONFIGURATION => {
|
||||
match configuration::Clientbound::decode(id, &body).map_err(err)? {
|
||||
configuration::Clientbound::SelectKnownPacks(p) => {
|
||||
configuration::Serverbound::SelectKnownPacks(p)
|
||||
}
|
||||
configuration::Clientbound::KeepAlive(p) => {
|
||||
configuration::Serverbound::KeepAlive(p)
|
||||
}
|
||||
configuration::Clientbound::Ping(p) => configuration::Serverbound::Pong(p),
|
||||
configuration::Clientbound::CodeOfConduct(_) => {
|
||||
configuration::Serverbound::AcceptCodeOfConduct(Empty)
|
||||
}
|
||||
configuration::Clientbound::CookieRequest(p) => {
|
||||
configuration::Serverbound::CookieResponse(configuration::CookieResponse {
|
||||
key: p.key,
|
||||
payload: None,
|
||||
})
|
||||
}
|
||||
configuration::Clientbound::Disconnect(_) => {
|
||||
return Err("disconnected during configuration".into());
|
||||
}
|
||||
configuration::Clientbound::FinishConfiguration(_) => {
|
||||
c.send(&configuration::Serverbound::FinishConfiguration(Empty).encode())
|
||||
.map_err(err)?;
|
||||
return Ok(c);
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
c.send(&reply.encode()).map_err(err)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the play state: answers what a client must answer, counts chunks, records teleports.
|
||||
fn read(
|
||||
mut reader: horizon_protocol::connection::ConnReader,
|
||||
writer: Arc<Mutex<ConnWriter>>,
|
||||
bot: Arc<Bot>,
|
||||
) {
|
||||
use ids::play::clientbound as cb;
|
||||
use ids::play::serverbound as sb;
|
||||
let send = |body: Vec<u8>| writer.lock().unwrap().send(&body);
|
||||
loop {
|
||||
let (id, body) = match reader.recv() {
|
||||
Ok(packet) => packet,
|
||||
Err(e) => {
|
||||
if bot.online.swap(false, Ordering::SeqCst) {
|
||||
*bot.error.lock().unwrap() = Some(e.to_string());
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut r = Reader::new(&body);
|
||||
let sent = match id {
|
||||
cb::KEEP_ALIVE => match r.i64() {
|
||||
Ok(v) => send(raw(sb::KEEP_ALIVE, |w| w.i64(v))),
|
||||
Err(_) => Ok(()),
|
||||
},
|
||||
cb::PING => match r.i32() {
|
||||
Ok(v) => send(raw(sb::PONG, |w| w.i32(v))),
|
||||
Err(_) => Ok(()),
|
||||
},
|
||||
cb::LEVEL_CHUNK_WITH_LIGHT => {
|
||||
bot.chunks.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
cb::CHUNK_BATCH_FINISHED => send(
|
||||
play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived {
|
||||
chunks_per_tick: 25.0,
|
||||
})
|
||||
.encode(),
|
||||
),
|
||||
cb::PLAYER_POSITION => match play::Clientbound::decode(id, &body) {
|
||||
Ok(play::Clientbound::PlayerPosition(p)) => {
|
||||
let mut at = bot.teleport.lock().unwrap();
|
||||
let previous = at.unwrap_or([0.0; 3]);
|
||||
// Relative flags: X 1, Y 2, Z 4.
|
||||
let pos: [f64; 3] = std::array::from_fn(|i| {
|
||||
if p.relatives & (1 << i) != 0 {
|
||||
previous[i] + p.position[i]
|
||||
} else {
|
||||
p.position[i]
|
||||
}
|
||||
});
|
||||
*at = Some(pos);
|
||||
send(
|
||||
play::Serverbound::AcceptTeleportation(play::AcceptTeleportation {
|
||||
id: p.teleport,
|
||||
x: pos[0],
|
||||
y: pos[1],
|
||||
z: pos[2],
|
||||
yaw: p.yaw,
|
||||
pitch: p.pitch,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
}
|
||||
_ => Ok(()),
|
||||
},
|
||||
cb::DISCONNECT | cb::START_CONFIGURATION => {
|
||||
bot.online.store(false, Ordering::SeqCst);
|
||||
*bot.error.lock().unwrap() = Some(if id == cb::DISCONNECT {
|
||||
format!(
|
||||
"disconnected: {}",
|
||||
String::from_utf8_lossy(&body)
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.collect::<String>()
|
||||
)
|
||||
} else {
|
||||
"sent back to configuration".into()
|
||||
});
|
||||
return;
|
||||
}
|
||||
_ => Ok(()),
|
||||
};
|
||||
if sent.is_err() {
|
||||
bot.online.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One bot: join, then move every 50 ms until `until`.
|
||||
fn run_bot(
|
||||
o: Arc<Options>,
|
||||
index: usize,
|
||||
behaviour: Behaviour,
|
||||
bot: Arc<Bot>,
|
||||
until: Arc<Mutex<Option<Instant>>>,
|
||||
) {
|
||||
let name = format!("{}{index}", o.name);
|
||||
let asked = Instant::now();
|
||||
let connection = match join(&o, &name) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
*bot.error.lock().unwrap() = Some(e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (reader, writer) = connection.split();
|
||||
let writer = Arc::new(Mutex::new(writer));
|
||||
bot.online.store(true, Ordering::SeqCst);
|
||||
{
|
||||
let (writer, bot) = (writer.clone(), bot.clone());
|
||||
thread::spawn(move || read(reader, writer, bot));
|
||||
}
|
||||
use ids::play::serverbound as sb;
|
||||
// Wait for the spawn position.
|
||||
let spawn = loop {
|
||||
if let Some(at) = *bot.teleport.lock().unwrap() {
|
||||
break at;
|
||||
}
|
||||
if !bot.online.load(Ordering::SeqCst) || asked.elapsed() > Duration::from_secs(60) {
|
||||
if bot.error.lock().unwrap().is_none() {
|
||||
*bot.error.lock().unwrap() = Some("no spawn position within 60 s".into());
|
||||
}
|
||||
return;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
bot.joined_after_ms
|
||||
.store(asked.elapsed().as_millis() as u64, Ordering::SeqCst);
|
||||
let send = |body: Vec<u8>| writer.lock().unwrap().send(&body).is_ok();
|
||||
send(raw(sb::PLAYER_LOADED, |_| {}));
|
||||
let mut random = Random(o.seed ^ (index as u64).wrapping_mul(0x2545_F491_4F6C_DD1D));
|
||||
let mut pos = spawn;
|
||||
let cruise = spawn[1] + 24.0;
|
||||
let heading = random.unit() * std::f64::consts::TAU;
|
||||
let mut target = pos;
|
||||
let mut next = Instant::now();
|
||||
loop {
|
||||
if until.lock().unwrap().is_some_and(|u| Instant::now() >= u)
|
||||
|| !bot.online.load(Ordering::SeqCst)
|
||||
{
|
||||
break;
|
||||
}
|
||||
// A teleport from the server wins over where the bot thought it was.
|
||||
if let Some(at) = bot.teleport.lock().unwrap().take() {
|
||||
pos = at;
|
||||
}
|
||||
if pos[1] < cruise {
|
||||
pos[1] = (pos[1] + 0.5).min(cruise);
|
||||
} else {
|
||||
match behaviour {
|
||||
Behaviour::Idle => {}
|
||||
Behaviour::Walk => {
|
||||
let (dx, dz) = (target[0] - pos[0], target[2] - pos[2]);
|
||||
let distance = dx.hypot(dz);
|
||||
if distance < 1.0 {
|
||||
let angle = random.unit() * std::f64::consts::TAU;
|
||||
let reach = 8.0 + random.unit() * 40.0;
|
||||
target = [
|
||||
spawn[0] + angle.cos() * reach,
|
||||
cruise,
|
||||
spawn[2] + angle.sin() * reach,
|
||||
];
|
||||
} else {
|
||||
// Sprinting: 5.6 blocks a second.
|
||||
let step = 0.28_f64.min(distance);
|
||||
pos[0] += dx / distance * step;
|
||||
pos[2] += dz / distance * step;
|
||||
}
|
||||
}
|
||||
Behaviour::Explore => {
|
||||
// Flying fast in creative: about 22 blocks a second, which keeps new chunks coming.
|
||||
pos[0] += heading.cos() * 1.1;
|
||||
pos[2] += heading.sin() * 1.1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = send(
|
||||
play::Serverbound::MovePlayerPos(play::MovePlayerPos {
|
||||
x: pos[0],
|
||||
y: pos[1],
|
||||
z: pos[2],
|
||||
flags: 0,
|
||||
})
|
||||
.encode(),
|
||||
) && send(raw(sb::CLIENT_TICK_END, |_| {}));
|
||||
if !ok {
|
||||
bot.online.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
next += Duration::from_millis(50);
|
||||
let now = Instant::now();
|
||||
if next > now {
|
||||
thread::sleep(next - now);
|
||||
} else if now - next > Duration::from_secs(1) {
|
||||
next = now;
|
||||
}
|
||||
}
|
||||
// Offline first, so the reader doesn't count the closed connection as a failure.
|
||||
bot.online.store(false, Ordering::SeqCst);
|
||||
writer.lock().unwrap().shutdown();
|
||||
}
|
||||
|
||||
fn behaviour_of(mode: &str, index: usize) -> Behaviour {
|
||||
match mode {
|
||||
"idle" => Behaviour::Idle,
|
||||
"walk" => Behaviour::Walk,
|
||||
"explore" => Behaviour::Explore,
|
||||
// mixed: of every five bots, three walk, one explores, one stands.
|
||||
_ => match index % 5 {
|
||||
0 | 2 | 4 => Behaviour::Walk,
|
||||
1 => Behaviour::Explore,
|
||||
_ => Behaviour::Idle,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let o = match options() {
|
||||
Ok(o) => Arc::new(o),
|
||||
Err(e) => {
|
||||
eprintln!("horizon-bots: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let start = Instant::now();
|
||||
let until: Arc<Mutex<Option<Instant>>> = Arc::new(Mutex::new(None));
|
||||
let bots: Vec<Arc<Bot>> = (0..o.bots).map(|_| Arc::new(Bot::default())).collect();
|
||||
let launcher = {
|
||||
let (o, bots, until) = (o.clone(), bots.clone(), until.clone());
|
||||
thread::spawn(move || {
|
||||
let mut handles = Vec::new();
|
||||
for (i, bot) in bots.iter().enumerate() {
|
||||
let (o2, bot, until) = (o.clone(), bot.clone(), until.clone());
|
||||
let behaviour = behaviour_of(&o.behaviour, i);
|
||||
handles.push(thread::spawn(move || run_bot(o2, i, behaviour, bot, until)));
|
||||
thread::sleep(Duration::from_secs_f64(o.join_every));
|
||||
}
|
||||
handles
|
||||
})
|
||||
};
|
||||
// The run lasts --seconds after the first bot is in.
|
||||
let mut previous_chunks = 0;
|
||||
let mut first = None;
|
||||
loop {
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
let online = bots
|
||||
.iter()
|
||||
.filter(|b| b.online.load(Ordering::SeqCst))
|
||||
.count();
|
||||
let chunks: u64 = bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum();
|
||||
let failed = bots
|
||||
.iter()
|
||||
.filter(|b| b.error.lock().unwrap().is_some())
|
||||
.count();
|
||||
if first.is_none() && online > 0 {
|
||||
first = Some(Instant::now());
|
||||
*until.lock().unwrap() = Some(Instant::now() + Duration::from_secs(o.seconds));
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"t": start.elapsed().as_secs(),
|
||||
"online": online,
|
||||
"failed": failed,
|
||||
"chunks": chunks,
|
||||
"chunks_per_second": chunks - previous_chunks,
|
||||
})
|
||||
);
|
||||
previous_chunks = chunks;
|
||||
let over = until.lock().unwrap().is_some_and(|u| Instant::now() >= u);
|
||||
let all_failed = failed == o.bots;
|
||||
if over || all_failed || (first.is_none() && start.elapsed() > Duration::from_secs(120)) {
|
||||
*until.lock().unwrap() = Some(Instant::now());
|
||||
break;
|
||||
}
|
||||
}
|
||||
for handle in launcher.join().unwrap_or_default() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
let summary = json!({
|
||||
"server": format!("{}:{}", o.host, o.port),
|
||||
"bots": o.bots,
|
||||
"behaviour": o.behaviour,
|
||||
"seed": o.seed,
|
||||
"view_distance": o.view_distance,
|
||||
"seconds": o.seconds,
|
||||
"joined": bots.iter().filter(|b| b.joined_after_ms.load(Ordering::SeqCst) > 0).count(),
|
||||
"chunks": bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum::<u64>(),
|
||||
"per_bot": bots.iter().enumerate().map(|(i, b)| json!({
|
||||
"name": format!("{}{i}", o.name),
|
||||
"behaviour": behaviour_of(&o.behaviour, i).name(),
|
||||
"joined_after_ms": b.joined_after_ms.load(Ordering::SeqCst),
|
||||
"chunks": b.chunks.load(Ordering::Relaxed),
|
||||
"error": *b.error.lock().unwrap(),
|
||||
})).collect::<Vec<_>>(),
|
||||
});
|
||||
if let Some(path) = &o.report {
|
||||
if let Err(e) = std::fs::write(path, format!("{summary:#}\n")) {
|
||||
eprintln!("horizon-bots: {path}: {e}");
|
||||
}
|
||||
}
|
||||
let errors: Vec<String> = bots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, b)| {
|
||||
b.error
|
||||
.lock()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.map(|e| format!("{}{i}: {e}", o.name))
|
||||
})
|
||||
.collect();
|
||||
for e in errors.iter().take(10) {
|
||||
eprintln!("horizon-bots: {e}");
|
||||
}
|
||||
std::process::exit(if errors.is_empty() { 0 } else { 1 });
|
||||
}
|
||||
Executable
+301
@@ -0,0 +1,301 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Server benchmark: the same bots on Horizon's server and on vanilla 26.3's (docs/server.md, section 9).
|
||||
|
||||
Every run starts a fresh server from the same server.properties (seed, view and simulation distance 10,
|
||||
offline, creative so the bots can fly), waits for `Done`, lets `horizon-bots` join one a second, warms up,
|
||||
then measures for a while:
|
||||
|
||||
- MSPT (average, P50, P95, P99) from each server's own `/tick query`, asked every 5 seconds on the console:
|
||||
vanilla's ServerTickRateManager numbers, which Horizon reproduces, so both measure themselves the same way;
|
||||
- RSS and CPU of the server's whole process tree, once a second;
|
||||
- chunks the bots receive per second (new terrain while the `explore` bots fly outwards);
|
||||
- the start time to `Done`, and every bot that failed to join or was dropped.
|
||||
|
||||
python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --seconds 120
|
||||
|
||||
The vanilla side runs the pinned server jar from tools/lab.py prepare (your own copy). It needs Java 25. The
|
||||
Horizon side runs target/release/horizon-server with the engine beside it; build both first:
|
||||
cargo build --release -p horizon-client --bin horizon-client -p horizon-server -p horizon-bots
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
ROOT = lab.ROOT
|
||||
EXE = '.exe' if os.name == 'nt' else ''
|
||||
# Where horizon-server and horizon-bots are (the engine is found beside horizon-server or on the PATH).
|
||||
BIN = Path(os.environ.get('HORIZON_BENCH_BIN', ROOT / 'target/release'))
|
||||
|
||||
PROPERTIES = {
|
||||
'level-seed': '12345',
|
||||
'view-distance': '10',
|
||||
'simulation-distance': '10',
|
||||
'online-mode': 'false',
|
||||
'white-list': 'false',
|
||||
'gamemode': 'creative',
|
||||
'force-gamemode': 'true',
|
||||
'spawn-protection': '0',
|
||||
'max-players': '200',
|
||||
'difficulty': 'easy',
|
||||
'sync-chunk-writes': 'true',
|
||||
}
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def cpu_seconds(text):
|
||||
"""ps's cumulative CPU time: [[DD-]HH:]MM:SS[.ss]."""
|
||||
days, _, rest = text.rpartition('-')
|
||||
parts = [float(p) for p in rest.split(':')]
|
||||
seconds = 0.0
|
||||
for p in parts:
|
||||
seconds = seconds * 60 + p
|
||||
return seconds + (float(days) * 86400 if days else 0)
|
||||
|
||||
|
||||
def tree_usage(root):
|
||||
"""RSS (bytes) and CPU seconds of a process and all its descendants."""
|
||||
out = subprocess.run(['ps', '-A', '-o', 'pid=,ppid=,rss=,time='], capture_output=True, text=True).stdout
|
||||
rows = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) == 4:
|
||||
rows[int(parts[0])] = (int(parts[1]), int(parts[2]) * 1024, cpu_seconds(parts[3]))
|
||||
tree, frontier = {root}, [root]
|
||||
while frontier:
|
||||
parent = frontier.pop()
|
||||
for pid, (ppid, _, _) in rows.items():
|
||||
if ppid == parent and pid not in tree:
|
||||
tree.add(pid)
|
||||
frontier.append(pid)
|
||||
rss = sum(rows[p][1] for p in tree if p in rows)
|
||||
cpu = sum(rows[p][2] for p in tree if p in rows)
|
||||
return rss, cpu
|
||||
|
||||
|
||||
class Server:
|
||||
"""A server with its console on stdin and its output collected."""
|
||||
|
||||
def __init__(self, command, directory, log_path):
|
||||
self.lines = []
|
||||
self.lock = threading.Lock()
|
||||
self.log = log_path.open('w', encoding='utf-8')
|
||||
self.process = subprocess.Popen([str(c) for c in command], cwd=directory, stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||
encoding='utf-8', errors='replace',
|
||||
env=dict(os.environ, HORIZON_NO_AUDIO='1'))
|
||||
threading.Thread(target=self._read, daemon=True).start()
|
||||
|
||||
def _read(self):
|
||||
for line in self.process.stdout:
|
||||
with self.lock:
|
||||
self.lines.append(line.rstrip('\n'))
|
||||
self.log.write(line)
|
||||
self.log.flush()
|
||||
|
||||
def count(self):
|
||||
with self.lock:
|
||||
return len(self.lines)
|
||||
|
||||
def since(self, n):
|
||||
with self.lock:
|
||||
return self.lines[n:]
|
||||
|
||||
def wait_for(self, pattern, timeout):
|
||||
regex = re.compile(pattern)
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if any(regex.search(l) for l in self.since(0)):
|
||||
return
|
||||
if self.process.poll() is not None:
|
||||
raise RuntimeError('the server exited:\n' + '\n'.join(self.since(0)[-20:]))
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError(f'no {pattern!r} within {timeout} s')
|
||||
|
||||
def console(self, line):
|
||||
self.process.stdin.write(line + '\n')
|
||||
self.process.stdin.flush()
|
||||
|
||||
def stop(self):
|
||||
if self.process.poll() is None:
|
||||
try:
|
||||
self.console('stop')
|
||||
self.process.wait(timeout=180)
|
||||
except (BrokenPipeError, subprocess.TimeoutExpired):
|
||||
self.process.kill()
|
||||
self.process.wait()
|
||||
self.log.close()
|
||||
|
||||
|
||||
TICK_AVERAGE = re.compile(r'Average time per tick: ([0-9.]+) ?ms')
|
||||
TICK_PERCENTILES = re.compile(r'P50: ([0-9.]+) ?ms P95: ([0-9.]+) ?ms P99: ([0-9.]+) ?ms')
|
||||
|
||||
|
||||
def tick_query(server):
|
||||
"""Asks `tick query` and reads the average and percentiles it prints (both servers print the same)."""
|
||||
start = server.count()
|
||||
server.console('tick query')
|
||||
deadline = time.time() + 5
|
||||
average = percentiles = None
|
||||
while time.time() < deadline and (average is None or percentiles is None):
|
||||
for line in server.since(start):
|
||||
if (m := TICK_AVERAGE.search(line)) and average is None:
|
||||
average = float(m.group(1))
|
||||
if (m := TICK_PERCENTILES.search(line)) and percentiles is None:
|
||||
percentiles = tuple(float(g) for g in m.groups())
|
||||
time.sleep(0.05)
|
||||
if average is None or percentiles is None:
|
||||
return None
|
||||
return {'average': average, 'p50': percentiles[0], 'p95': percentiles[1], 'p99': percentiles[2]}
|
||||
|
||||
|
||||
def server_command(kind, directory, args):
|
||||
if kind == 'vanilla':
|
||||
_, jars, libraries = base.verify_artifacts()
|
||||
classpath = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
return ['java', f'-Xms{args.heap}', f'-Xmx{args.heap}', '-Duser.timezone=UTC', '-cp', classpath,
|
||||
'net.minecraft.server.Main', 'nogui']
|
||||
server = BIN / f'horizon-server{EXE}'
|
||||
subprocess.run([server, '--dir', directory, 'import', directory / 'server.properties'], check=True,
|
||||
capture_output=True)
|
||||
toml = directory / 'server.toml'
|
||||
# The same settings, without the web panel.
|
||||
toml.write_text(re.sub(r'(?m)^bind = "127\.0\.0\.1:8130"', 'bind = ""', toml.read_text()))
|
||||
return [server, '--dir', directory, 'run']
|
||||
|
||||
|
||||
def run_once(kind, bots, args, out):
|
||||
directory = out / f'{kind}-{bots}'
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir(parents=True)
|
||||
port = free_port()
|
||||
props = dict(PROPERTIES, **{'server-port': str(port), 'level-seed': str(args.seed)})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
command = server_command(kind, directory, args)
|
||||
started = time.time()
|
||||
server = Server(command, directory, out / f'{kind}-{bots}.log')
|
||||
result = {'server': kind, 'bots': bots}
|
||||
try:
|
||||
server.wait_for(r'/INFO\]: Done \(', 600)
|
||||
result['start_seconds'] = round(time.time() - started, 2)
|
||||
time.sleep(5)
|
||||
report = out / f'{kind}-{bots}-bots.json'
|
||||
total = bots * args.join_every + args.warmup + args.seconds
|
||||
bot_process = subprocess.Popen(
|
||||
[BIN / f'horizon-bots{EXE}', '--server', f'127.0.0.1:{port}', '--bots', str(bots),
|
||||
'--behaviour', args.behaviour, '--join-every', str(args.join_every), '--seconds', str(int(total)),
|
||||
'--seed', str(args.seed), '--report', report],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
bot_lines = []
|
||||
threading.Thread(target=lambda: bot_lines.extend(bot_process.stdout), daemon=True).start()
|
||||
# All bots in, then the warm-up.
|
||||
time.sleep(bots * args.join_every + args.warmup)
|
||||
measure_start = time.time()
|
||||
rss, cpu, ticks = [], [], []
|
||||
_, last_cpu = tree_usage(server.process.pid)
|
||||
last_time = time.time()
|
||||
next_query = time.time()
|
||||
while time.time() - measure_start < args.seconds:
|
||||
time.sleep(1)
|
||||
now = time.time()
|
||||
r, c = tree_usage(server.process.pid)
|
||||
rss.append(r)
|
||||
cpu.append((c - last_cpu) / (now - last_time) * 100)
|
||||
last_cpu, last_time = c, now
|
||||
if now >= next_query:
|
||||
if (t := tick_query(server)) is not None:
|
||||
ticks.append(t)
|
||||
next_query = now + 5
|
||||
measured = [json.loads(l) for l in list(bot_lines) if l.startswith('{')]
|
||||
window = [l for l in measured if l['t'] >= measured[-1]['t'] - args.seconds] if measured else []
|
||||
bot_process.wait(timeout=total + 120)
|
||||
summary = json.loads(report.read_text()) if report.exists() else {}
|
||||
mean = lambda xs: round(statistics.fmean(xs), 2) if xs else None
|
||||
result.update({
|
||||
'mspt': {k: mean([t[k] for t in ticks]) for k in ('average', 'p50', 'p95', 'p99')},
|
||||
'mspt_worst_p99': max((t['p99'] for t in ticks), default=None),
|
||||
# /tick query reports times, not the rate: 20 while the average fits in 50 ms.
|
||||
'tps': round(min(20.0, 1000 / max(statistics.fmean([t['average'] for t in ticks]), 1e-9)), 2) if ticks else None,
|
||||
'rss_mb': {'mean': mean([r / 1e6 for r in rss]), 'max': round(max(rss) / 1e6, 1) if rss else None},
|
||||
'cpu_percent': mean(cpu),
|
||||
'chunks_per_second': mean([l['chunks_per_second'] for l in window]),
|
||||
'bots_joined': summary.get('joined'),
|
||||
'bots_failed': [b for b in summary.get('per_bot', []) if b.get('error')],
|
||||
'tick_queries': len(ticks),
|
||||
})
|
||||
except Exception as e: # a failed run is reported, and the next one still runs
|
||||
result['error'] = str(e)
|
||||
finally:
|
||||
server.stop()
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
|
||||
parser.add_argument('--servers', default='horizon,vanilla')
|
||||
parser.add_argument('--bots', default='1,10,25,50')
|
||||
parser.add_argument('--behaviour', default='mixed')
|
||||
parser.add_argument('--join-every', type=float, default=1.0)
|
||||
parser.add_argument('--warmup', type=int, default=60)
|
||||
parser.add_argument('--seconds', type=int, default=300)
|
||||
parser.add_argument('--seed', type=int, default=12345)
|
||||
parser.add_argument('--heap', default='4g', help='the Java heap, -Xms and -Xmx (vanilla)')
|
||||
parser.add_argument('--out', type=Path, default=None, help='the report (JSON)')
|
||||
args = parser.parse_args()
|
||||
out = lab.LOCAL / 'server-bench'
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
runs = []
|
||||
for bots in [int(b) for b in args.bots.split(',')]:
|
||||
for kind in args.servers.split(','):
|
||||
print(f'{kind}, {bots} bots...', flush=True)
|
||||
result = run_once(kind, bots, args, out)
|
||||
runs.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
report = {
|
||||
'kind': 'horizon-server-benchmark',
|
||||
'date': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'),
|
||||
'machine': {'system': platform.system(), 'machine': platform.machine(), 'cpus': os.cpu_count()},
|
||||
'commit': subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=ROOT, capture_output=True, text=True).stdout.strip(),
|
||||
'java': subprocess.run(['java', '--version'], capture_output=True, text=True).stdout.splitlines()[:1],
|
||||
'settings': {**vars(args), 'out': str(args.out), 'properties': PROPERTIES},
|
||||
'runs': runs,
|
||||
}
|
||||
path = args.out or out / 'report.json'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(f'\n{"server":8} {"bots":>4} {"start s":>8} {"MSPT":>6} {"P95":>6} {"P99":>6} {"RSS MB":>7} {"CPU %":>6} {"chunks/s":>8} {"joined":>6}')
|
||||
for r in runs:
|
||||
if 'error' in r:
|
||||
print(f'{r["server"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}')
|
||||
continue
|
||||
print(f'{r["server"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} {r["mspt"]["p95"]!s:>6} '
|
||||
f'{r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} {r["chunks_per_second"]!s:>8} '
|
||||
f'{r["bots_joined"]!s:>6}')
|
||||
print(f'\nWrote {path}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user