Merge commit 'bf1cd958686ffc95a6ff30cdbedc9a8de59315ad' into HEAD
# Conflicts: # tools/lan_e2e.py
This commit is contained in:
+134
-5
@@ -10,8 +10,10 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- armour: each side draws the other player in that player's own armour;
|
||||
- nametags: each side draws the other player's name above them;
|
||||
- chest: a chest the guest opens opens on the guest's screen, its lid opens on both sides and
|
||||
closes on both when the guest closes it;
|
||||
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table;
|
||||
closes on both when the guest closes it; the host keeps playing with its mouse look (#687);
|
||||
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table, which
|
||||
leaves the host's screen and mouse look alone;
|
||||
- sign: a sign the guest places doesn't open a sign editor on the host;
|
||||
- damage: a guest in survival takes fall damage;
|
||||
- mobs: with the host in creative, a zombie and a skeleton go for the guest and hurt them;
|
||||
- hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes,
|
||||
@@ -20,6 +22,10 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- containers: the guest's ender chest holds the guest's items, not the host's, and a double chest
|
||||
opens as 9x6 with the right half first;
|
||||
- feedback: the guest's command feedback names the guest and shows the numbers;
|
||||
- effects: a beacon's power reaches every player in range, the host and the guest;
|
||||
- portals: (--server-thread) the server holds a level per dimension: the guest goes to the Nether
|
||||
through a portal while the host stays, then the host goes to the End while the guest is in
|
||||
the Nether, and both come back.
|
||||
- commands: the guest's chat completes commands and their arguments over the server's command
|
||||
tree (Tab), and runs what it completed;
|
||||
- recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it
|
||||
@@ -31,6 +37,7 @@ both sides go to --out (host-*.png, guest-*.png).
|
||||
python3 tools/lan_e2e.py # build with the fast profile, run every check
|
||||
python3 tools/lan_e2e.py --bin-dir target/fast # prebuilt binaries
|
||||
python3 tools/lan_e2e.py --check chest --check tab
|
||||
python3 tools/lan_e2e.py --server-thread --check portals # the host's world on its server thread
|
||||
|
||||
Needs the prepared resources in .local/horizon-client and, on Linux, vscreen (the desktop); on
|
||||
macOS both games render offscreen. Games started here have no audio (HORIZON_NO_AUDIO=1).
|
||||
@@ -52,7 +59,9 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials']
|
||||
# The host plays single player on its server thread (--server-thread).
|
||||
SERVER_THREAD = False
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials', 'effects', 'portals']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -184,6 +193,19 @@ def check_nametags(host, guest, out):
|
||||
return {'host': h, 'guest': g}
|
||||
|
||||
|
||||
def grab(game):
|
||||
"""Mouse look on, as a player's grabbed pointer: an agent's mouse-move stands in for it."""
|
||||
game.raw('mouse-move', 1, 0)
|
||||
game.raw('mouse-move', -1, 0)
|
||||
|
||||
|
||||
def host_unaffected(host, what):
|
||||
"""What a guest opens is the guest's: the host keeps its world on screen and its mouse look (#687)."""
|
||||
state = host('state')
|
||||
assert state.get('screen') == 'playing', f'{what} opened the {state.get("screen")} screen on the host'
|
||||
assert state.get('pointer_grabbed'), f"{what} released the host's pointer"
|
||||
|
||||
|
||||
def lid(game, pos):
|
||||
return game.raw('block', *pos).get('lid', 0.0)
|
||||
|
||||
@@ -193,9 +215,11 @@ def check_chest(host, guest, out):
|
||||
chest = (x, y, z + 2)
|
||||
guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest')
|
||||
guest.wait(10)
|
||||
grab(host)
|
||||
guest.raw('interact', *chest)
|
||||
screen = guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
guest.wait(20)
|
||||
host_unaffected(host, "the guest's chest")
|
||||
opened = {'guest': lid(guest, chest), 'host': lid(host, chest)}
|
||||
host.raw('look-at', chest[0] + 0.5, chest[1] + 0.5, chest[2] + 0.5)
|
||||
host.wait(2)
|
||||
@@ -235,8 +259,10 @@ def check_crafting(host, guest, out):
|
||||
table = (x, y, z - 2)
|
||||
guest('command', command=f'setblock {table[0]} {table[1]} {table[2]} minecraft:crafting_table')
|
||||
guest.wait(10)
|
||||
grab(host)
|
||||
guest.raw('interact', *table)
|
||||
guest.raw('wait-for', 'screen', 'inventory', '--timeout', 10)
|
||||
host_unaffected(host, "the guest's crafting table")
|
||||
size = guest('screen').get('craft_size')
|
||||
assert size == 3, f'the crafting table opened a {size}x{size} grid'
|
||||
# Two planks one above the other in the 3x3 grid: four sticks.
|
||||
@@ -256,6 +282,104 @@ def check_crafting(host, guest, out):
|
||||
return {'planks': planks, 'table': counts}
|
||||
|
||||
|
||||
def check_sign(host, guest, out):
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
spot = (x + 2, y, z)
|
||||
guest('command', command=f'setblock {spot[0]} {spot[1] - 1} {spot[2]} minecraft:stone')
|
||||
guest('command', command=f'setblock {spot[0]} {spot[1]} {spot[2]} minecraft:air')
|
||||
guest('command', command='give @s minecraft:oak_sign 1')
|
||||
guest.wait(10)
|
||||
grab(host)
|
||||
guest.raw('place', *spot, '--item', 'minecraft:oak_sign')
|
||||
guest.wait(20)
|
||||
placed = host.raw('block', *spot).get('block')
|
||||
host.shot(out, 'sign')
|
||||
assert placed and 'sign' in placed, f'the guest placed {placed}'
|
||||
host_unaffected(host, "the guest's sign")
|
||||
return placed
|
||||
|
||||
|
||||
def effect_ids(game):
|
||||
return [e.get('id', '').removeprefix('minecraft:') for e in game('state')['player'].get('effects', [])]
|
||||
|
||||
|
||||
def check_effects(host, guest, out):
|
||||
x, y, z = (int(v // 1) for v in pos_of(host))
|
||||
bx, by, bz = x - 3, y, z - 3
|
||||
host('command', command=f'fill {bx - 1} {by - 1} {bz - 1} {bx + 1} {by - 1} {bz + 1} minecraft:iron_block')
|
||||
host('command', command=f'setblock {bx} {by} {bz} minecraft:beacon{{primary_effect:"minecraft:speed"}}')
|
||||
# BeaconBlockEntity.tick applies its powers every 80 ticks, once the beam has reached the sky.
|
||||
seen = {}
|
||||
for _ in range(15):
|
||||
host.wait(20)
|
||||
seen = {'host': effect_ids(host), 'guest': effect_ids(guest)}
|
||||
if all('speed' in v for v in seen.values()):
|
||||
break
|
||||
host.shot(out, 'effects')
|
||||
guest.shot(out, 'effects')
|
||||
assert 'speed' in seen['host'] and 'speed' in seen['guest'], f'beacon effects: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def wait_dimension(game, dimension, ticks):
|
||||
"""Wait up to `ticks` for the game to be in `dimension` with its world loaded around it."""
|
||||
for _ in range(ticks // 20):
|
||||
state = game('state')
|
||||
if state.get('dimension') == dimension and state.get('player'):
|
||||
return state
|
||||
game.wait(20)
|
||||
return game('state')
|
||||
|
||||
|
||||
def nether_portal(game, x, y, z):
|
||||
"""A lit portal along x, two blocks wide and three tall, its inside starting at x y z."""
|
||||
game('command', command=f'fill {x - 1} {y - 1} {z} {x + 2} {y + 3} {z} minecraft:obsidian')
|
||||
game('command', command=f'fill {x} {y} {z} {x + 1} {y + 2} {z} minecraft:nether_portal[axis=x]')
|
||||
|
||||
|
||||
def check_portals(host, guest, out):
|
||||
if not SERVER_THREAD:
|
||||
return 'skipped (needs --server-thread)'
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
nether_portal(guest, x, y, z + 3)
|
||||
guest.wait(5)
|
||||
guest('command', command=f'tp @s {x + 0.5} {y} {z + 3.5}')
|
||||
# players_nether_portal_default_delay: 80 ticks in survival.
|
||||
there = wait_dimension(guest, 'minecraft:the_nether', 600)
|
||||
guest.wait(40)
|
||||
guest.shot(out, 'portals-nether')
|
||||
host_dim = host('state').get('dimension')
|
||||
assert there.get('dimension') == 'minecraft:the_nether', f'the guest is in {there.get("dimension")}'
|
||||
assert host_dim == 'minecraft:overworld', f'the host went to {host_dim} with the guest'
|
||||
arrived = [int(v // 1) for v in pos_of(guest)]
|
||||
below = guest.raw('block', arrived[0], arrived[1] - 1, arrived[2])
|
||||
assert below.get('loaded') and below.get('block') != 'minecraft:air', f'under the guest in the Nether: {below}'
|
||||
# The host takes an End portal while the guest is in the Nether: three levels at once.
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
host('command', command=f'setblock {hx} {hy} {hz} minecraft:end_portal')
|
||||
end = wait_dimension(host, 'minecraft:the_end', 600)
|
||||
host.wait(40)
|
||||
host.shot(out, 'portals-end')
|
||||
guest_dim = guest('state').get('dimension')
|
||||
assert end.get('dimension') == 'minecraft:the_end', f'the host is in {end.get("dimension")}'
|
||||
assert guest_dim == 'minecraft:the_nether', f'the guest left the Nether for {guest_dim}'
|
||||
# Both come back: the host through an exit portal, the guest out of its portal and in again.
|
||||
ex, ey, ez = (int(v // 1) for v in pos_of(host))
|
||||
host('command', command=f'setblock {ex + 2} {ey} {ez} minecraft:end_portal')
|
||||
host('command', command=f'tp @s {ex + 2.5} {ey} {ez + 0.5}')
|
||||
guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] - 2.5}')
|
||||
guest.wait(30)
|
||||
guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] + 0.5}')
|
||||
home = wait_dimension(host, 'minecraft:overworld', 600)
|
||||
back = wait_dimension(guest, 'minecraft:overworld', 600)
|
||||
guest.wait(40)
|
||||
host.shot(out, 'portals-back')
|
||||
guest.shot(out, 'portals-back')
|
||||
assert home.get('dimension') == 'minecraft:overworld', f'the host stayed in {home.get("dimension")}'
|
||||
assert back.get('dimension') == 'minecraft:overworld', f'the guest stayed in {back.get("dimension")}'
|
||||
return {'guest_nether': arrived, 'host_end': [ex, ey, ez], 'back': pos_of(guest)}
|
||||
|
||||
|
||||
def check_damage(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest.wait(10)
|
||||
@@ -701,16 +825,18 @@ def check_trials(host, guest, out):
|
||||
|
||||
|
||||
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
|
||||
'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage,
|
||||
'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage,
|
||||
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'commands': check_commands,
|
||||
'recipes': check_recipes,
|
||||
'trials': check_trials,
|
||||
'walls': check_walls}
|
||||
'walls': check_walls, 'effects': check_effects, 'portals': check_portals}
|
||||
|
||||
|
||||
def run(ctl, out, resources, checks):
|
||||
host, guest = Game('host', ctl, resources), Game('guest', ctl, resources)
|
||||
if SERVER_THREAD:
|
||||
host.d.env['HORIZON_SERVER_THREAD'] = '1'
|
||||
results = {}
|
||||
try:
|
||||
host('launch', wait=False, offscreen=sys.platform == 'darwin')
|
||||
@@ -756,7 +882,10 @@ def main():
|
||||
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
|
||||
parser.add_argument('--check', action='append', choices=CHECKS, help='run only these checks (repeatable)')
|
||||
parser.add_argument('--out', default=str(ROOT / '.local/lan-e2e'), help='screenshots and game logs go here')
|
||||
parser.add_argument('--server-thread', action='store_true', help="the host's world runs on its server thread")
|
||||
args = parser.parse_args()
|
||||
global SERVER_THREAD
|
||||
SERVER_THREAD = args.server_thread
|
||||
if args.bin_dir:
|
||||
bins = Path(args.bin_dir).resolve()
|
||||
else:
|
||||
|
||||
+31
-5
@@ -44,6 +44,7 @@ import json
|
||||
import math
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import statistics
|
||||
@@ -185,19 +186,35 @@ def summary(values):
|
||||
return {"n": n, "mean": rnd(mean), "stdev": sd, "min": rnd(min(values)), "max": rnd(max(values)), "ci95": ci}
|
||||
|
||||
|
||||
def phys_footprint(pid):
|
||||
"""macOS: the bytes the kernel charges the process (`footprint`), without
|
||||
the freed pages the allocator marked reusable, which `ps` still counts as
|
||||
resident until memory runs short. None elsewhere."""
|
||||
if sys.platform != "darwin":
|
||||
return None
|
||||
out = subprocess.run(["footprint", "-f", "bytes", str(pid)], capture_output=True, text=True)
|
||||
m = re.search(r"phys_footprint:\s*(\d+)", out.stdout)
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
|
||||
class Sampler(threading.Thread):
|
||||
"""Samples a process's resident memory every quarter second (ps, so the
|
||||
same reading for every game and OS)."""
|
||||
same reading for every game and OS) and, on macOS, its physical footprint
|
||||
every two seconds."""
|
||||
|
||||
def __init__(self, pid):
|
||||
super().__init__(daemon=True)
|
||||
self.pid, self.samples, self.stop = pid, [], threading.Event()
|
||||
self.pid, self.samples, self.footprints, self.stop = pid, [], [], threading.Event()
|
||||
|
||||
def run(self):
|
||||
tick = 0
|
||||
while not self.stop.is_set():
|
||||
out = subprocess.run(["ps", "-o", "rss=", "-p", str(self.pid)], capture_output=True, text=True)
|
||||
if out.stdout.strip():
|
||||
self.samples.append((time.time(), int(out.stdout.split()[0]) * 1024))
|
||||
if tick % 8 == 0 and (fp := phys_footprint(self.pid)) is not None:
|
||||
self.footprints.append((time.time(), fp))
|
||||
tick += 1
|
||||
self.stop.wait(0.25)
|
||||
|
||||
def summary(self, windows):
|
||||
@@ -205,11 +222,16 @@ class Sampler(threading.Thread):
|
||||
if not self.samples:
|
||||
return {}
|
||||
during = [rss for t, rss in self.samples if any(a <= t <= b for a, b in windows)]
|
||||
return {
|
||||
out = {
|
||||
"rss_peak_mb": max(rss for _, rss in self.samples) / 2**20,
|
||||
"rss_steady_mb": statistics.median(during) / 2**20 if during else None,
|
||||
"rss_samples": len(self.samples),
|
||||
}
|
||||
if self.footprints:
|
||||
steady = [fp for t, fp in self.footprints if any(a <= t <= b for a, b in windows)]
|
||||
out["footprint_peak_mb"] = max(fp for _, fp in self.footprints) / 2**20
|
||||
out["footprint_steady_mb"] = statistics.median(steady) / 2**20 if steady else None
|
||||
return out
|
||||
|
||||
|
||||
def nvidia_memory_mb(pid):
|
||||
@@ -685,6 +707,8 @@ def report(args, distance, runs, app):
|
||||
metric(f"memory.{name}.gpu_mb", [s.get("gpu_mb") for s in scenes])
|
||||
metric("memory.rss_peak_mb", [r["memory"].get("rss_peak_mb") for r in runs])
|
||||
metric("memory.rss_steady_mb", [r["memory"].get("rss_steady_mb") for r in runs])
|
||||
metric("memory.footprint_peak_mb", [r["memory"].get("footprint_peak_mb") for r in runs])
|
||||
metric("memory.footprint_steady_mb", [r["memory"].get("footprint_steady_mb") for r in runs])
|
||||
return {"format": REPORT_FORMAT, "version": REPORT_VERSION, "kind": "game",
|
||||
"created": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"app": app, "hardware": hw, "conditions": conditions, "metrics": metrics, "frames": entries,
|
||||
@@ -711,7 +735,7 @@ def table(labels):
|
||||
cells.append(" / ".join(cell(m.get(f"fps.{scene}.{k}")) for k in ("avg_fps", "low_1pct_fps", "low_01pct_fps")))
|
||||
print(f"| {d} | {scene} | " + " | ".join(cells) + " |")
|
||||
print()
|
||||
print("| RD | " + " | ".join(f"{l}: title / world s, mean scene load s, RSS steady / peak MB, load avg" for l in labels) + " |")
|
||||
print("| RD | " + " | ".join(f"{l}: title / world s, mean scene load s, RSS steady / peak MB, footprint steady / peak MB, load avg" for l in labels) + " |")
|
||||
print("| --- |" + " --- |" * len(labels))
|
||||
for d in distances:
|
||||
cells = []
|
||||
@@ -726,7 +750,9 @@ def table(labels):
|
||||
mb = lambda k: f"{m[k]['mean']:.0f}" if k in m else "–"
|
||||
cells.append(f"{sec('startup.title_ms')} / {sec('startup.world_ms')}, "
|
||||
f"{statistics.mean(loads) / 1000 if loads else 0:.1f}, "
|
||||
f"{mb('memory.rss_steady_mb')} / {mb('memory.rss_peak_mb')}, {r['conditions'].get('load_avg_1m')}")
|
||||
f"{mb('memory.rss_steady_mb')} / {mb('memory.rss_peak_mb')}, "
|
||||
f"{mb('memory.footprint_steady_mb')} / {mb('memory.footprint_peak_mb')}, "
|
||||
f"{r['conditions'].get('load_avg_1m')}")
|
||||
print(f"| {d} | " + " | ".join(cells) + " |")
|
||||
|
||||
|
||||
|
||||
+11
-1
@@ -39,7 +39,17 @@ EXPORTERS = "mods/horizon/src/test/java/dev/horizonlab/parity/"
|
||||
|
||||
# What players run. Documentation (*.md), tests, benchmarks and harness probes (examples/) never count.
|
||||
GAME_PATHS = ["crates/", "xtask/", "packaging/", "Cargo.toml", "Cargo.lock", "research-lock.json"]
|
||||
LAUNCHER_PATHS = ["launcher/", "crates/horizon-prepare/", "crates/horizon-theme/", "crates/horizon-telemetry/"]
|
||||
# Every crate the launcher builds in (cargo metadata --manifest-path launcher/Cargo.toml: the path packages).
|
||||
LAUNCHER_PATHS = [
|
||||
"launcher/",
|
||||
"crates/horizon-bench/",
|
||||
"crates/horizon-friends/",
|
||||
"crates/horizon-mods/",
|
||||
"crates/horizon-port-pack/",
|
||||
"crates/horizon-prepare/",
|
||||
"crates/horizon-telemetry/",
|
||||
"crates/horizon-theme/",
|
||||
]
|
||||
LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"]
|
||||
|
||||
FOOTER = {
|
||||
|
||||
+91
-24
@@ -8,10 +8,18 @@ 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);
|
||||
- chunks the bots receive per second (new terrain while the `explore` bots fly outwards), chunks sent again
|
||||
while a bot still held them, and the moves the server refused (pull-backs; "moved too quickly" and
|
||||
"moved wrongly" lines);
|
||||
- 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
|
||||
python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --behaviour walk,explore
|
||||
|
||||
The bots can run on another machine, so they don't take the server's CPU: `--bots-via 'ssh macmini'` with
|
||||
`--bots-bin` naming horizon-bots there and `--connect` the address it reaches this machine at. `--nice 19`
|
||||
runs every server at the lowest priority (a shared machine). The explore bots fly as fast as each server
|
||||
sends them chunks, so a faster server gets more terrain to generate; `--explore-speed` slows them to a rate
|
||||
both servers keep up with, for equal work.
|
||||
|
||||
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:
|
||||
@@ -186,8 +194,16 @@ def server_command(kind, directory, args):
|
||||
return [server, '--dir', directory, 'run']
|
||||
|
||||
|
||||
def run_once(kind, bots, args, out):
|
||||
directory = out / f'{kind}-{bots}'
|
||||
def bots_command(args):
|
||||
"""horizon-bots here, or through `--bots-via` (for example `ssh macmini`) on another machine."""
|
||||
if args.bots_via:
|
||||
return [*args.bots_via.split(), args.bots_bin or 'horizon-bots']
|
||||
return [args.bots_bin or BIN / f'horizon-bots{EXE}']
|
||||
|
||||
|
||||
def run_once(kind, bots, behaviour, args, out):
|
||||
name = f'{kind}-{behaviour}-{bots}'
|
||||
directory = out / name
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir(parents=True)
|
||||
port = free_port()
|
||||
@@ -195,19 +211,27 @@ def run_once(kind, bots, args, out):
|
||||
(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)
|
||||
if args.nice:
|
||||
command = ['nice', '-n', str(args.nice), *command]
|
||||
started = time.time()
|
||||
server = Server(command, directory, out / f'{kind}-{bots}.log')
|
||||
result = {'server': kind, 'bots': bots}
|
||||
server = Server(command, directory, out / f'{name}.log')
|
||||
result = {'server': kind, 'bots': bots, 'behaviour': behaviour}
|
||||
try:
|
||||
server.wait_for(r'/INFO\]: Done \(', 600)
|
||||
result['start_seconds'] = round(time.time() - started, 2)
|
||||
# Every bot appears on the world spawn itself, not spread around it, so both servers see the same paths.
|
||||
server.console('gamerule respawn_radius 0')
|
||||
for rule in filter(None, args.gamerule.split(',')):
|
||||
server.console('gamerule ' + rule.replace('=', ' '))
|
||||
time.sleep(5)
|
||||
report = out / f'{kind}-{bots}-bots.json'
|
||||
report = out / f'{name}-bots.json'
|
||||
total = bots * args.join_every + args.warmup + args.seconds
|
||||
# The summary comes back on stdout after the per-second lines, so it works over ssh too.
|
||||
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],
|
||||
[*bots_command(args), '--server', f'{args.connect}:{port}', '--bots', str(bots),
|
||||
'--behaviour', behaviour, '--join-every', str(args.join_every), '--seconds', str(int(total)),
|
||||
'--seed', str(args.seed), '--report', '-',
|
||||
*(['--explore-speed', str(args.explore_speed)] if args.explore_speed else [])],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
bot_lines = []
|
||||
threading.Thread(target=lambda: bot_lines.extend(bot_process.stdout), daemon=True).start()
|
||||
@@ -229,11 +253,27 @@ def run_once(kind, bots, args, out):
|
||||
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 {}
|
||||
time.sleep(0.5)
|
||||
measured, rest = [], []
|
||||
for line in list(bot_lines):
|
||||
try:
|
||||
sample = json.loads(line)
|
||||
except ValueError:
|
||||
sample = None
|
||||
if isinstance(sample, dict) and 't' in sample:
|
||||
measured.append(sample)
|
||||
else:
|
||||
rest.append(line)
|
||||
window = [l for l in measured if l['t'] >= measured[-1]['t'] - args.seconds] if measured else []
|
||||
summary_text = ''.join(rest)
|
||||
summary = json.loads(summary_text) if summary_text.strip() else {}
|
||||
report.write_text(json.dumps(summary, indent=2) + '\n')
|
||||
mean = lambda xs: round(statistics.fmean(xs), 2) if xs else None
|
||||
per_bot = summary.get('per_bot', [])
|
||||
by_behaviour = {}
|
||||
for b in per_bot:
|
||||
by_behaviour.setdefault(b['behaviour'], []).append(b)
|
||||
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),
|
||||
@@ -242,6 +282,19 @@ def run_once(kind, bots, args, out):
|
||||
'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]),
|
||||
# Over the measured window: different chunks reaching the bots, chunks they had dropped and got
|
||||
# again (walking back), and ticks the bots stood still waiting for their own chunk.
|
||||
**({k + '_per_second': round((window[-1][k] - window[0][k]) / max(len(window) - 1, 1), 2)
|
||||
for k in ('unique', 'forgotten', 'waited_ticks')} if len(window) > 1 else {}),
|
||||
'chunks_total': summary.get('chunks'),
|
||||
# Per bot over the whole run: every chunk received, the different ones, and those sent again
|
||||
# while the bot still held them.
|
||||
'chunks_per_bot': {k: mean([b['chunks'] for b in v]) for k, v in by_behaviour.items()},
|
||||
'unique_chunks_per_bot': {k: mean([b['unique_chunks'] for b in v]) for k, v in by_behaviour.items()},
|
||||
'resent': summary.get('resent'),
|
||||
'pulled_back': summary.get('pulled_back'),
|
||||
'moved_too_quickly': sum('moved too quickly!' in l for l in server.since(0)),
|
||||
'moved_wrongly': sum('moved wrongly!' in l for l in server.since(0)),
|
||||
'bots_joined': summary.get('joined'),
|
||||
'bots_failed': [b for b in summary.get('per_bot', []) if b.get('error')],
|
||||
'tick_queries': len(ticks),
|
||||
@@ -257,23 +310,34 @@ 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('--behaviour', default='walk,explore', help='one pass per behaviour (comma-separated)')
|
||||
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('--explore-speed', type=float, default=0,
|
||||
help='blocks a second the explore bots fly (default: the bots\' 22, as fast as chunks '
|
||||
'come); a speed both servers keep up with makes the explore pass equal work')
|
||||
parser.add_argument('--gamerule', default='',
|
||||
help="more game rules for both servers, 'name=value,...' (locator_bar=false: Horizon has "
|
||||
"no locator bar yet)")
|
||||
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)')
|
||||
parser.add_argument('--nice', type=int, default=0, help='run the servers under nice -n N')
|
||||
parser.add_argument('--bots-via', default='', help="a command prefix to run the bots elsewhere ('ssh host')")
|
||||
parser.add_argument('--bots-bin', default='', help='horizon-bots (on the --bots-via machine)')
|
||||
parser.add_argument('--connect', default='127.0.0.1', help='the address the bots reach the server at')
|
||||
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)
|
||||
for behaviour in args.behaviour.split(','):
|
||||
for bots in [int(b) for b in args.bots.split(',')]:
|
||||
for kind in args.servers.split(','):
|
||||
print(f'{kind}, {bots} {behaviour} bots...', flush=True)
|
||||
result = run_once(kind, bots, behaviour, 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'),
|
||||
@@ -286,13 +350,16 @@ def main():
|
||||
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}')
|
||||
print(f'\n{"server":8} {"pass":8} {"bots":>4} {"start s":>8} {"MSPT":>6} {"P95":>6} {"P99":>6} {"RSS MB":>7} '
|
||||
f'{"CPU %":>6} {"chunks/s":>8} {"/bot":>6} {"resent":>6} {"pulled":>6} {"joined":>6}')
|
||||
for r in runs:
|
||||
if 'error' in r:
|
||||
print(f'{r["server"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}')
|
||||
print(f'{r["server"]:8} {r["behaviour"]: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} '
|
||||
per_bot = r['chunks_per_bot'].get(r['behaviour'])
|
||||
print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} '
|
||||
f'{r["mspt"]["p95"]!s:>6} {r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} '
|
||||
f'{r["chunks_per_second"]!s:>8} {per_bot!s:>6} {r["resent"]!s:>6} {r["pulled_back"]!s:>6} '
|
||||
f'{r["bots_joined"]!s:>6}')
|
||||
print(f'\nWrote {path}')
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ the same files), chats, runs /list and commands that fail (`/random value
|
||||
7..7`, `/random value x`, `/trigger nope`), trades, is made an operator by
|
||||
the console, runs /kill, respawns (as vanilla's LevelLoadTracker waits: until the "level
|
||||
chunks load start" event and the chunk under the player), sets a furnace
|
||||
beside itself, gives itself raw iron and coal, opens the furnace, shift-clicks
|
||||
beside itself, gives itself raw iron and coal, sets and asks its own score
|
||||
(`@s`), opens the furnace, shift-clicks
|
||||
the ore and the coal in and the ingot out, and leaves. The
|
||||
console then runs `list` and `say` and `stop`. Compared, all of them
|
||||
exactly:
|
||||
@@ -33,7 +34,9 @@ exactly:
|
||||
player respawned (guests' death messages aren't Horizon's yet: left out);
|
||||
- the furnace menu: its type and title, its contents, the slots each
|
||||
shift-click changes and its lit and cooking totals;
|
||||
- the console lines about the player, the chat, `list`, `say` and `stop`;
|
||||
- the console lines about the player (an operator's command feedback, which
|
||||
vanilla broadcasts to the console, included), the chat, `list`, `say` and
|
||||
`stop`;
|
||||
- the files the servers leave: server.properties (but the date line),
|
||||
eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json,
|
||||
usercache.json (but the date the player's entry expires).
|
||||
@@ -209,10 +212,9 @@ CONSOLE_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*)$')
|
||||
KEPT = re.compile(r'Tester|\[Server\]|\[Not Secure\]|There are|Stopping|Saving|ThreadedAnvilChunkStorage|All dimensions|Unknown or incomplete')
|
||||
|
||||
|
||||
# Guests' death messages, the op's command feedback broadcast to the console and guests'
|
||||
# advancement announcements aren't Horizon's yet (the client's own transcript leaves the
|
||||
# death message out as well).
|
||||
NOT_YET = re.compile(r'Tester was killed|Killed Tester|System chat: \[Tester: |Tester has made the advancement')
|
||||
# Guests' death messages and advancement announcements aren't Horizon's yet (the client's
|
||||
# own transcript leaves the death message out as well).
|
||||
NOT_YET = re.compile(r'Tester was killed|Tester has made the advancement')
|
||||
|
||||
|
||||
def console_lines(lines):
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A new world's generator settings from server.properties, against vanilla's dedicated server.
|
||||
|
||||
DedicatedServerProperties.WorldDimensionData makes a world that doesn't exist yet from `level-type` (a world
|
||||
preset: `flat`, `minecraft:normal`, or a name it can't find, which it warns about and replaces with
|
||||
`minecraft:normal`), a flat world's `generator-settings` (FlatLevelGeneratorSettings: its layers, biome,
|
||||
lakes and features; a layer that doesn't parse is left out and logged, and settings without layers fall back
|
||||
to the preset's classic ones) and `generate-structures`.
|
||||
|
||||
Each case starts vanilla's server and Horizon's (`horizon-client --dedicated --nogui`) in a new folder, waits
|
||||
for `Done` and stops them. Compared exactly: the world's `data/minecraft/world_gen_settings.dat`, tag types
|
||||
included, and the warnings and errors logged while the world's settings are read (the `Worker-Main` lines;
|
||||
the worker's number is left out).
|
||||
|
||||
Horizon generates the normal and flat presets only: `large_biomes`, `amplified`, `single_biome_surface` and
|
||||
`debug_all_block_states` aren't tested.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import anvil_dump, lab, test_rust_parity as base
|
||||
from .test_dedicated_server_parity import Server, free_port
|
||||
except ImportError:
|
||||
import anvil_dump
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
from test_dedicated_server_parity import Server, free_port
|
||||
|
||||
NAME = 'server-world-gen-parity'
|
||||
PROPERTIES = {
|
||||
'online-mode': 'false',
|
||||
'view-distance': '2',
|
||||
'simulation-distance': '2',
|
||||
'spawn-protection': '0',
|
||||
}
|
||||
CASES = {
|
||||
# server.properties' default generator-settings ({}) has no layers: the preset's classic ones.
|
||||
'flat': {'level-type': 'flat', 'level-seed': '1'},
|
||||
'flat-layers': {
|
||||
'level-type': 'minecraft:flat',
|
||||
'level-seed': '-7',
|
||||
'generator-settings': json.dumps({
|
||||
'layers': [{'block': 'minecraft:bedrock', 'height': 1}, {'block': 'stone', 'height': 10},
|
||||
{'block': 'minecraft:no_such_block', 'height': 2}, {'block': 'sand', 'height': 3}],
|
||||
'biome': 'minecraft:desert', 'lakes': True, 'features': True}, separators=(',', ':')),
|
||||
},
|
||||
'flat-biome': {
|
||||
'level-type': 'FLAT',
|
||||
'level-seed': 'flat',
|
||||
'generator-settings': '{"layers":[{"block":"minecraft:glass","height":5}],"biome":"nowhere"}',
|
||||
},
|
||||
'normal': {'level-type': 'minecraft:normal', 'level-seed': 'abc', 'generate-structures': 'false'},
|
||||
'unknown': {'level-type': 'Some Type', 'level-seed': '42'},
|
||||
}
|
||||
WORKER = re.compile(r'\[Worker-Main-\d+/(WARN|ERROR)\]: (.*)')
|
||||
|
||||
|
||||
def escape(value):
|
||||
"""java.util.Properties.store's escaping of a value."""
|
||||
return value.replace('\\', '\\\\').replace(':', '\\:').replace('=', '\\=').replace('#', '\\#')
|
||||
|
||||
|
||||
def run_case(label, command, build, case):
|
||||
directory = build / label / case
|
||||
if directory.exists():
|
||||
shutil.rmtree(directory)
|
||||
directory.mkdir(parents=True)
|
||||
props = dict(PROPERTIES, **CASES[case], **{'server-port': str(free_port())})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={escape(v)}\n' for k, v in props.items()),
|
||||
encoding='iso-8859-1')
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
server = Server(command, directory, f'{label}-{case}')
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
finally:
|
||||
server.stop()
|
||||
out = [f'# {case}']
|
||||
out += [f'{m.group(1)}: {m.group(2)}' for l in server.lines if (m := WORKER.search(l))]
|
||||
settings = anvil_dump.plain(anvil_dump.read_dat(directory / 'world/data/minecraft/world_gen_settings.dat'),
|
||||
True, typed=True)
|
||||
out += json.dumps(settings, indent=1, sort_keys=True).splitlines()
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
check=True, capture_output=True)
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main',
|
||||
'nogui']
|
||||
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
|
||||
vanilla, horizon = [], []
|
||||
for case in CASES:
|
||||
vanilla += run_case('vanilla', vanilla_server, build, case)
|
||||
horizon += run_case('horizon', horizon_server, build, case)
|
||||
(build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8')
|
||||
(build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8')
|
||||
if vanilla != horizon:
|
||||
import difflib
|
||||
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=2, lineterm=''))
|
||||
raise AssertionError(f'world settings differ (see {build}/vanilla.txt and horizon.txt):\n' + diff[:6000])
|
||||
if not any('minecraft:flat' in l for l in vanilla) or not any(l.startswith('ERROR: ') for l in vanilla):
|
||||
raise AssertionError(f'vanilla made no flat world or logged no error (see {build})')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
cases=list(CASES), lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='a new dedicated-server world: level-type (flat, normal, unknown), a flat world\'s '
|
||||
'generator-settings, generate-structures, as world_gen_settings.dat and the lines logged.'))
|
||||
print(f'server world gen: {len(CASES)} cases, {len(vanilla)} lines identical')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as error:
|
||||
sys.exit(f'{NAME}: {error}')
|
||||
Reference in New Issue
Block a user