Merge main into t3/fix-hero-trading-discount: keep both sides' appended checks

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

# Conflicts:
#	tools/lan_e2e.py
This commit is contained in:
Ludovic Marie
2026-10-25 08:41:23 +01:00
94 changed files with 6551 additions and 2221 deletions
+9 -6
View File
@@ -67,17 +67,20 @@ class Failed(Exception):
pass
def game_env(screen):
def game_env(screen, home=None):
"""The environment of a game: lab.game_env with HORIZON_HOME `home` (a scratch folder when None), no live-count
ping, and on Linux the virtual screen `screen`."""
extra = {'HORIZON_TELEMETRY_URL': 'off'} # no live-count ping from test games
if home is not None:
extra['HORIZON_HOME'] = home
if sys.platform == 'darwin':
return dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
env = dict(os.environ, VSCREEN=screen)
return lab.game_env(**extra)
env = lab.game_env(VSCREEN=screen, **extra)
subprocess.run(['vscreen', 'up'], env=env, check=False, capture_output=True)
text = subprocess.run(['vscreen', 'env'], env=env, capture_output=True, text=True, check=True).stdout
env.pop('DISPLAY', None)
for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]):
env[match.group(1)] = match.group(2)
env['HORIZON_NO_AUDIO'] = '1'
env['HORIZON_TELEMETRY_URL'] = 'off' # no live-count ping from test games
if LAVAPIPE.exists():
env['VK_ICD_FILENAMES'] = str(LAVAPIPE)
return env
@@ -632,7 +635,7 @@ def scratch(mode, resources):
(work / '.local/horizon-client').mkdir()
os.symlink(resources, work / '.local/horizon-client' / lab.VERSION)
# horizon-ctl reads No AI in the game home: this one, not the player's.
env = dict(game_env(os.environ.get('VSCREEN', 'agent-control')), HORIZON_HOME=str(work))
env = game_env(os.environ.get('VSCREEN', 'agent-control'), home=work)
return work, env
+25 -4
View File
@@ -22,19 +22,40 @@ def prohibited(path):
return bool(parsed.parts and parsed.parts[0] in PRIVATE_ROOTS) or parsed.suffix.lower() in PRIVATE_EXTENSIONS
def paths_in_repository(history=False):
def paths_in_repository(history=False, revisions=None):
if not history:
result = subprocess.check_output(["git", "ls-files", "-z"])
return result.decode("utf-8").split("\0")
result = subprocess.check_output(["git", "log", "--all", "--format=", "--name-only", "-z"])
# An empty push (including deletions only) must not fall back to HEAD or --all.
if revisions is not None and not revisions:
return []
roots = ["--all"] if revisions is None else revisions
# Include diffs against merge parents so merge-resolution-only artifacts are caught.
# Git pushes the stored objects, not the history presented by local replace refs.
result = subprocess.check_output(["git", "--no-replace-objects", "log", "--format=", "--name-only",
"-z", "-m", *roots, "--"])
return [path.lstrip("\n") for path in result.decode("utf-8").split("\0")]
def pushed_revisions(stream):
"""Read Git's pre-push ref updates and retain the non-deleted local object IDs."""
revisions = []
for line in stream:
_local_ref, local_oid, _remote_ref, _remote_oid = line.split()
if local_oid.strip("0"):
revisions.append(local_oid)
return revisions
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--history", action="store_true", help="Also inspect paths in all local Git history")
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--history", action="store_true", help="Inspect paths in all local Git history")
mode.add_argument("--pre-push", action="store_true", help="Inspect history reachable from Git's ref updates on stdin")
args = parser.parse_args()
rejected = sorted({path for path in paths_in_repository(args.history) if path and prohibited(path)})
revisions = pushed_revisions(sys.stdin) if args.pre_push else None
rejected = sorted({path for path in paths_in_repository(args.history or args.pre_push, revisions)
if path and prohibited(path)})
if rejected:
print("Private game/profiling artifacts must stay outside Git:", file=sys.stderr)
for path in rejected:
+36
View File
@@ -36,6 +36,11 @@ def group_setup():
*setup('/kill @e[type=!player]'),
{'op': 'tick', 'n': 25},
*setup('/fill 0 200 0 15 228 15 air', '/time set 1000', '/weather clear', '/difficulty normal', '/clear @s'),
# Before the gamerules above, while the oracle waits for its entities to load (a number of ticks that
# depends on the machine), mobs spawn and some die with their drops on: a bat's death rolled
# minecraft:entities/bat on 1 vanilla run in 24, one more sequence for the ticking group's
# /random reset * to count. Every run starts the script without them.
*setup('/random reset *'),
]
@@ -286,6 +291,36 @@ def entities():
]
def riding_teleport():
"""Player teleports remove the vehicle, leave it behind and keep the destination (#1473)."""
horse = '@e[tag=tp_horse,limit=1]'
operations = setup(
'/summon minecraft:horse 4.5 220 4.5 {Tame:1b,NoAI:1b,NoGravity:1b,Tags:["tp_horse"]}',
'/summon minecraft:marker 8.5 220 0.5 {Tags:["tp_destination"]}',
)
for teleport in ('/tp @s 8.5 220 0.5', '/teleport @s ~4 220 ~-4',
'/tp @s @e[tag=tp_destination,limit=1]'):
operations += [
*setup('/tp @s 4.5 220 4.5'),
cmd(f'/ride @s mount {horse}'),
cmd('/execute on vehicle run say mounted'),
# An invalid destination must not dismount the player.
cmd('/tp @s 30000000 220 0'),
cmd('/execute on vehicle run say still mounted'),
cmd(teleport),
cmd('/execute on vehicle run say still riding after teleport'),
cmd('/data get entity @s Pos'),
cmd(f'/data get entity {horse} Pos'),
{'op': 'tick', 'n': 60},
cmd('/execute on vehicle run say still riding after ticks'),
cmd('/data get entity @s Pos'),
cmd(f'/data get entity {horse} Pos'),
cmd('/ride @s dismount'),
]
return operations + setup('/kill @e[tag=tp_horse]', '/kill @e[tag=tp_destination]',
'/tp @s 8.5 230 8.5 0 0')
def scores():
return [
cmd('/scoreboard objectives add harness dummy'),
@@ -975,6 +1010,7 @@ def groups():
('player state', player_state()),
('blocks and border', world_blocks()),
('entities', entities()),
('riding teleport', riding_teleport()),
('scores, teams and bossbars', scores()),
('execute', execute()),
('levels', levels()),
+3 -4
View File
@@ -53,15 +53,14 @@ guiScale:0
def vscreen_env():
out = subprocess.run(["vscreen", "env"], cwd=ROOT, capture_output=True, text=True, check=True)
env = dict(os.environ)
env = lab.game_env()
for part in out.stdout.replace(";", " ").split():
if "=" in part and not part.startswith("export"):
k, v = part.split("=", 1)
env[k] = v
env.pop("DISPLAY", None)
# Benchmark games never play sound on the machine's speakers.
env["HORIZON_NO_AUDIO"] = "1"
# Nor reach the telemetry server (docs/telemetry.md).
# lab.game_env: no sound on the machine's speakers, and scratch folders instead of the player's.
# Benchmark games do not reach the telemetry server (docs/telemetry.md).
env["HORIZON_TELEMETRY_URL"] = "off"
return env
+33
View File
@@ -5,6 +5,7 @@ generated files stay in .local/. Also the small helpers the harnesses share
(free ports, offline UUIDs, VarInts, float bits)."""
import argparse
import atexit
from collections import Counter
import hashlib
import json
@@ -54,6 +55,38 @@ def cargo_target():
return ROOT / os.environ.get("CARGO_TARGET_DIR", "target")
_SCRATCH_DIRS = []
def _scratch_dir(prefix):
path = tempfile.mkdtemp(prefix=prefix)
_SCRATCH_DIRS.append(path)
return path
@atexit.register
def _remove_scratch_dirs():
for path in _SCRATCH_DIRS:
shutil.rmtree(path, ignore_errors=True)
def game_env(base=None, **extra):
"""The environment for every run of the game, the launcher or horizon-ctl from a tool or a harness: no audio,
and fresh scratch folders for the game's home (logs, saves, options), the launcher's home and the XDG folders,
so a run never writes into a real player's folders (the game falls back to them when HORIZON_HOME is unset).
A folder the caller already has in `base` (default os.environ) or passes in `extra` is kept. The scratch folders
are removed when this process exits."""
env = dict(os.environ if base is None else base)
env.update({key: str(value) for key, value in extra.items()})
env["HORIZON_NO_AUDIO"] = "1"
env["HORIZON_LAUNCHER_NO_SELF_UPDATE"] = "1"
for key, prefix in (("HORIZON_HOME", "horizon-home-"), ("HORIZON_LAUNCHER_HOME", "horizon-launcher-home-"),
("XDG_DATA_HOME", "horizon-xdg-data-"), ("XDG_CONFIG_HOME", "horizon-xdg-config-")):
if not env.get(key):
env[key] = _scratch_dir(prefix)
return env
def write_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+517 -4
View File
@@ -87,7 +87,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
- 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
places a log in the inventory's crafting grid (the server places it).
places a log in the inventory's crafting grid (the server places it).
- recipe_removal: the host and guest each forget all and individual recipes while the book
is open; it stays empty when reopened, and a later grant appears (#1495).
- feedback: the guest's command feedback names the guest and shows the numbers, and the host (an
operator) is told of it as `[Guest: ...]`.
- clicks: with real mouse presses (not click-slot, which skips the screen's press and drag
@@ -102,6 +104,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
pushes it, as in vanilla), not ever faster across the ground.
- eat: holding right click with bread, the guest's own screen plays the eating (the item in use
counts up) and the server eats one loaf and feeds the guest.
- consume-release: the host and the guest each cancel eating a golden apple and drinking milk from
either hand: use ends on client and server, the item and effects stay, and holding
use to completion still consumes the item (#1293).
- eating: each side sees the other player eat: the item in use (LivingEntity's flags) on the
player it draws, and no longer once the bread is eaten (#803);
- xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the
@@ -109,7 +114,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
- objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the
guest as the host has them (kind, place, rotation, what they hold or wear, the variant).
- projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where
the host has them; a falling block lands on both sides.
the host has them; a falling block lands on both sides.
- shulker_bullets: every shot a shulker fires has its own id and flies on both sides, following
the same trajectory; the bullets disappear on both sides when they hit blocks (#1494).
- thrown: a splash potion and an eye of ender the host and the guest each throw fly on both
sides (#1363, #1391);
- sparks: level events' particles on both sides: the host's and the guest's bone meal on wheat
@@ -136,6 +143,8 @@ address. The script then checks, from both sides, what a guest's game used to ge
server's game time after the guest's game stalls for a few seconds (#848).
- growth: far from the host, the chunks around the guest tick (#890): water placed there flows
and wheat on farmland grows (random ticks), however the host runs its world.
- farmland: the host and guest each trample planted farmland: the wheat breaks and drops its items,
and both clients see dirt/air (#1492).
- ladder: the guest climbs down ten blocks of ladder and lands unhurt: the server resets its fall
distance on a ladder every tick, as LivingEntity.handleOnClimbable does (#1255).
- boats: the host (single player, on its server thread or not) and the guest each right-click a
@@ -156,6 +165,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
- riding: the host and the guest each saddle and ride a horse (walk, jump), a pig and a strider
(with their sticks), a camel and a donkey, sit on a llama and fly a happy ghast, and
get off by sneaking; the other side sees the animal move.
- riding_teleport: the host and the guest each /tp through chat while riding a horse; after 60
ticks each stays dismounted at the destination and both sides see the horse left
behind. The host also teleports a mounted guest by name.
- lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the
sky (on its server thread the host's window is a client of it too).
- drops: an item lies where the host, then the guest, places a block: it comes out of the block
@@ -280,8 +292,7 @@ class Game:
(self.work / '.local/horizon-client').mkdir(parents=True)
os.symlink(resources, self.work / '.local/horizon-client' / lab.VERSION)
self.socket = self.work / 'c.sock'
env = game_env(os.environ.get('VSCREEN', 'lan-e2e'))
env['HORIZON_HOME'] = str(self.work / 'home')
env = game_env(os.environ.get('VSCREEN', 'lan-e2e'), home=self.work / 'home')
self.d = Cli(ctl, self.socket, self.work, env)
self.d.name = name
@@ -4900,6 +4911,82 @@ CHECKS += ['helduse']
CHECK_FNS.update(helduse=check_held_use)
def check_consume_release(host, guest, out):
"""#1293: releasing a consumable in either hand cancels it on client and server, while
holding it to completion applies its effects and remainder (Consumable.onConsume)."""
apart(host, guest)
seen = {}
try:
for game in (host, guest):
game('command', command='gamemode survival')
x, y, z = pos_of(game)
game.raw('look-at', x, y + 1.6, z + 2)
for hand in ('mainhand', 'offhand'):
for item in ('golden_apple', 'milk_bucket'):
case = f'{game.name}-{hand}-{item}'
game('command', command='clear @s')
game('command', command='item replace entity @s weapon.offhand with minecraft:air')
game('command', command='effect clear @s')
if item == 'milk_bucket':
game('command', command='effect give @s minecraft:speed 60')
game('command', command=f'item replace entity @s weapon.{hand} with minecraft:{item}')
game.wait(10)
assert game('looking_at')['kind'] == 'none', f'{case} is not aimed into the air'
before = set(effect_ids(game))
assert before == ({'speed'} if item == 'milk_bucket' else set()), f'{case}: {before}'
game.raw('mouse', 'right', 'down')
game.wait(5)
during = {'client': game('state').get('using'), 'server': server_using(host, game)}
game.raw('mouse', 'right', 'up')
game.wait(10)
released = {'client': game('state').get('using'), 'server': server_using(host, game)}
# Wait past the full use duration: the server must not finish eating after release.
game.wait(60)
effects = set(effect_ids(game))
inventory = game('inventory')
stack = inventory['offhand'] if hand == 'offhand' else inventory['held']
cancelled = {'during': during, 'released': released,
'stack': stack, 'effects': sorted(effects)}
seen[case] = {'cancelled': cancelled}
assert during['client'] and during['server'], f'{case} did not start on both sides: {cancelled}'
assert released == {'client': None, 'server': None}, f'{case} did not cancel: {cancelled}'
assert stack and stack['item'] == f'minecraft:{item}' and stack['count'] == 1, \
f'{case} consumed the released item: {cancelled}'
assert effects == before, f'{case} applied consumption effects after release: {cancelled}'
game.shot(out, f'consume-release-{hand}-{item}')
# A sustained press must still consume normally, including the milk's empty bucket.
game.raw('mouse', 'right', 'down')
game.wait(40)
game.raw('mouse', 'right', 'up')
game.wait(10)
inventory = game('inventory')
stack = inventory['offhand'] if hand == 'offhand' else inventory['held']
completed = {'stack': stack, 'effects': sorted(effect_ids(game)),
'using': (game('state').get('using'), server_using(host, game))}
seen[case]['completed'] = completed
assert completed['using'] == (None, None), \
f'{case} did not finish normally: {completed}'
if item == 'golden_apple':
assert inventory['counts'].get('minecraft:golden_apple', 0) == 0, \
f'{case} kept the eaten apple: {completed}'
assert set(completed['effects']) == {'regeneration', 'absorption'}, f'{case}: {completed}'
else:
assert not completed['effects'] and stack and stack['item'] == 'minecraft:bucket' \
and stack['count'] == 1, f'{case}: {completed}'
finally:
for game in (host, guest):
game.raw('mouse', 'right', 'up')
game('command', command='clear @s')
game('command', command='item replace entity @s weapon.offhand with minecraft:air')
game('command', command='effect clear @s')
face_each_other(host, guest)
return seen
CHECKS += ['consume-release']
CHECK_FNS.update({'consume-release': check_consume_release})
def check_wind(host, guest, out):
"""A wind charge each player throws at its own feet (ServerExplosion with TRIGGER_BLOCK): the
server's burst pushes the thrower through its ClientboundExplodePacket (hitPlayers), which
@@ -5512,6 +5599,57 @@ CHECKS += ['hero-trading']
CHECK_FNS.update({'hero-trading': check_hero_trading})
def check_spectator_travel(host, guest, out):
"""Player.tick's spectator noPhysics survives a replacement body after dimension travel (#1299)."""
players = (host, guest) if SERVER_THREAD else (host,)
seen = {}
for game in players:
home = pos_of(game)
game('command', command='gamemode spectator')
game.wait(10)
try:
for dimension in (NETHER, OVERWORLD):
game('command', command=f'execute in {dimension} run tp @s .5 102 .5 0 0')
there = wait_dimension(game, dimension, 600)
assert there.get('dimension') == dimension, f'{game.name} stayed in {there.get("dimension")}'
# A replacement body arrives before its chunks; fill needs the whole corridor loaded.
for _ in range(30):
if all(game.raw('block', *pos).get('loaded') for pos in ((-2, 101, -1), (2, 105, 16))):
break
game.wait(20)
game('command', command='fill -2 101 -1 2 105 16 minecraft:air')
game('command', command='fill -2 101 3 2 105 3 minecraft:stone')
game.wait(10)
wall = game.raw('block', 0, 102, 3)
assert wall.get('loaded') and wall.get('block') == 'minecraft:stone', f'wall: {wall}'
label = f'spectator-{dimension.removeprefix("minecraft:")}'
game.shot(out, f'{label}-before')
game.raw('key', 'w', 'down')
game.wait(20)
game.raw('key', 'w', 'up')
game.wait(10)
state = game('state')
client = state['player']
server = server_player(host, game)
seen[f'{game.name}-{dimension}'] = {'client': client['position'], 'server': server['position']}
game.shot(out, f'{label}-after')
assert state.get('gamemode') == 'spectator' and client['flying'], f'{game.name} lost spectator flight'
assert client['position'][2] > 4 and server['position'][2] > 4, \
f'{game.name} collides after travel to {dimension}: {seen}'
game('command', command='fill -2 101 3 2 105 3 minecraft:air')
finally:
game.raw('key', 'w', 'up')
game('command', command=f'execute in {OVERWORLD} run tp @s {home[0]:.2f} {home[1]:.2f} {home[2]:.2f}')
wait_dimension(game, OVERWORLD, 600)
game('command', command='gamemode survival')
game.wait(20)
return seen
CHECKS += ['spectator-travel']
CHECK_FNS.update({'spectator-travel': check_spectator_travel})
def check_villagers(host, guest, out):
"""Villager.DATA_VILLAGER_DATA and ZombieVillager's reach the guest: summoned villagers show
their type, profession and level, and an unemployed villager that takes a composter placed
@@ -5571,6 +5709,381 @@ CHECKS += ['villagers']
CHECK_FNS.update(villagers=check_villagers)
def check_riding_teleport(host, guest, out):
"""#1473: a chat /tp dismounts each player and leaves the horse behind in both modes;
teleporting another player exercises the guest-target command path too."""
spots = apart(host, guest)
result = {}
for label, player, source in (('host', host, None), ('guest', guest, None),
('guest-targeted', guest, host)):
x, y, z = spots['host' if player is host else 'guest']
horse_at = (x + 0.5, y, z + 2.5)
destination = (x + 3.5, y, z + 5.5)
tag = 'tp_horse'
try:
player('command', command='clear @s')
player('command', command='gamemode survival')
player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0')
player('command', command='item replace entity @s weapon.mainhand with minecraft:saddle')
player('command', command=f'summon minecraft:horse {horse_at[0]} {y} {horse_at[2]} '
f'{{Tame:1b,NoAI:1b,NoGravity:1b,Tags:["{tag}"]}}')
player.wait(5)
horses = [m for m in player.raw('mobs', 16)['near']
if m['kind'] == 'minecraft:horse' and m['health'] > 0]
horse = next((m for m in horses if math.dist(m['pos'], horse_at) < 0.1), None)
assert horse, f'{label}: no live horse at {horse_at}: {horses}'
player.raw('look-at', horse_at[0], y + 0.8, horse_at[2])
player.raw('mouse', 'right', 'click')
player.wait(5)
player('command', command='item replace entity @s weapon.mainhand with minecraft:air')
player.wait(2)
player.raw('mouse', 'right', 'click')
player.wait(5)
assert player('status').get('riding') == horse['id'], f'{label}: not riding the horse'
player.shot(out, f'riding-tp-{label}-before')
coordinates = ' '.join(map(str, destination))
if source is None:
player.raw('key', 't', 'tap')
player.raw('type', f'/tp @s {coordinates}')
player.raw('key', 'enter', 'tap')
else:
source('command', command=f'tp {GUEST_NAME} {coordinates}')
player.wait(60)
player.shot(out, f'riding-tp-{label}-after')
seen = {'riding': player('status').get('riding'), 'client': pos_of(player),
'server': server_player(host, player)['position'],
'horse': mob_seen(player, horse['id'])['pos'],
'other_horse': mob_seen(guest if player is host else host, horse['id'])['pos']}
assert seen['riding'] is None, f'{label}: still mounted after /tp: {seen}'
assert all(math.dist(seen[side], destination) < 0.01 for side in ('client', 'server')), \
f'{label}: /tp did not keep its destination after 60 ticks: {seen}'
assert all(math.dist(seen[side], horse_at) < 0.01 for side in ('horse', 'other_horse')), \
f'{label}: /tp moved the horse: {seen}'
result[label] = seen
finally:
back_to_game(player)
player('command', command=f'kill @e[tag={tag}]')
player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0')
# The next case uses this spot again: let the previous horse's death animation finish.
player.wait(25)
return result
CHECKS += ['riding_teleport']
CHECK_FNS.update(riding_teleport=check_riding_teleport)
def check_recipe_removal(host, guest, out):
"""ServerRecipeBook.removeRecipes sends ClientboundRecipeBookRemovePacket to the player:
the open book updates immediately, reopening keeps it empty, and later grants still arrive."""
seen = {}
for game in (host, guest):
back_to_game(game)
game('command', command='clear @s')
game('command', command='give @s minecraft:oak_log 4')
game('command', command='recipe give @s minecraft:oak_planks')
game('command', command='recipe give @s minecraft:stick')
game.wait(40)
game.raw('key', 'e', 'tap')
game.wait(5)
try:
book = game('screen').get('recipe_book')
assert book, f'{game.name}: the inventory has no recipe book'
if len(book['targets']) == 1:
game.raw('click-at', *centre(book['targets'][0]))
game.wait(5)
book = game('screen')['recipe_book']
known = book['known']
assert known > 1, f'{game.name}: recipes were not granted: {book}'
game.shot(out, 'recipe-removal-before')
game('command', command='recipe take @s *')
game.wait(20)
empty = game('screen')['recipe_book']['known']
game.shot(out, 'recipe-removal-empty')
assert empty == 0, f'{game.name}: forgotten recipes remain in the open book: {empty}'
game.raw('key', 'esc', 'tap')
game.wait(5)
game.raw('key', 'e', 'tap')
game.wait(5)
reopened = game('screen')['recipe_book']['known']
assert reopened == 0, f'{game.name}: reopening restored {reopened} forgotten recipes'
game('command', command='recipe give @s minecraft:oak_planks')
game('command', command='recipe give @s minecraft:stick')
game.wait(20)
given = game('screen')['recipe_book']['known']
assert given == 2, f'{game.name}: two later grants did not appear: {given}'
game('command', command='recipe take @s minecraft:oak_planks')
game.wait(20)
one = game('screen')['recipe_book']['known']
assert one == 1, f'{game.name}: taking one recipe left {one}, expected 1'
game('command', command='recipe take @s minecraft:stick')
game.wait(20)
assert game('screen')['recipe_book']['known'] == 0, f'{game.name}: the last recipe remains'
game('command', command='recipe give @s minecraft:oak_planks')
game.wait(20)
granted = game('screen')['recipe_book']['known']
assert granted == 1, f'{game.name}: a later grant did not appear: {granted}'
game.shot(out, 'recipe-removal-granted')
seen[game.name] = {'known': known, 'empty': empty, 'reopened': reopened,
'given': given, 'one': one, 'granted': granted}
finally:
back_to_game(game)
return seen
CHECKS += ['recipe_removal']
CHECK_FNS.update(recipe_removal=check_recipe_removal)
def check_shulker_bullets(host, guest, out):
"""ShulkerAttackGoal's bullets reach ClientPacketListener.handleAddEntity, then the existing
projectile renderer and interpolation, with distinct ids from the server's entity counter."""
x, y, z = (int(v // 1) for v in pos_of(host))
tag = 'lan_shulker_bullets'
selector = f'@e[type=minecraft:shulker,tag={tag},limit=1]'
sound = 'minecraft:entity.shulker.shoot'
paths = {g.name: {} for g in (host, guest)}
before = {g.name: heard(g, sound) for g in (host, guest)}
shots = dict.fromkeys(before, 0)
first_shot = stopped = None
photographed = False
def bullets(status):
return [p for p in status['projectiles'] if p['kind'] == 'ShulkerBullet']
try:
host('command', command='difficulty normal')
host('command', command='gamemode creative')
guest('command', command='gamemode survival')
guest('command', command='effect give @s minecraft:resistance 120 4 true')
host('command', command=f'fill {x - 10} {y - 1} {z - 10} {x + 10} {y - 1} {z + 18} minecraft:stone')
host('command', command=f'fill {x - 10} {y} {z - 10} {x + 10} {y + 12} {z + 18} minecraft:air')
# A west wall supports the shulker above the floor, leaving room for a short flight.
host('command', command=f'fill {x - 1} {y} {z + 7} {x - 1} {y + 4} {z + 7} minecraft:stone')
host('command', command=f'tp @s {x + 4.5} {y} {z - 0.5}')
guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
host('command', command=f'summon minecraft:shulker {x + 0.5} {y + 3} {z + 7.5} '
f'{{NoAI:1b,PersistenceRequired:1b,Tags:["{tag}"]}}')
for game in (host, guest):
game.raw('look-at', x + 0.5, y + 3.5, z + 7.5)
guest.wait(20)
host('command', command=f'data merge entity {selector} {{NoAI:0b}}')
for waited in range(2, 402, 2):
guest.wait(2)
for game in (host, guest):
status = game('status')
live = bullets(status)
ids = [p['id'] for p in live]
assert all(ids) and len(set(ids)) == len(ids), f'{game.name}: invalid bullet ids {ids}'
for p in live:
paths[game.name].setdefault(p['id'], []).append(p['position'])
shots[game.name] = status['heard'].get(sound, 0) - before[game.name]
if shots['host'] and first_shot is None:
first_shot = waited
if first_shot is not None and waited - first_shot >= 8 and not photographed:
host('command', command='tick freeze')
try:
for game in (host, guest):
game.raw('look-at', x + 0.5, y + 3.5, z + 7.5)
game.raw('key', 'f1', 'tap')
try:
game.shot(out, 'shulker-bullets')
finally:
game.raw('key', 'f1', 'tap')
finally:
host('command', command='tick unfreeze')
photographed = True
if shots['host'] >= 2 and stopped is None:
host('command', command=f'data merge entity {selector} {{NoAI:1b}}')
stopped = waited
if stopped is not None and waited - stopped >= 20:
break
# Keep the survival target in range after a hit applies levitation.
if waited % 20 == 0:
guest('command', command='effect clear @s minecraft:levitation')
guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
lab.write_json(out / 'shulker-bullets.json', {'shots': shots, 'paths': paths})
assert shots['host'] >= 2, f'the shulker did not attack twice: {shots}'
for name, by_id in paths.items():
assert len(by_id) == shots[name], f'{name}: {shots[name]} shots but bullet ids {list(by_id)}'
for id, positions in by_id.items():
assert any(math.dist(positions[0], p) > 0.5 for p in positions), \
f'{name}: bullet {id} did not move: {positions}'
assert paths['host'].keys() == paths['guest'].keys(), f'different bullets: {paths}'
for id, positions in paths['guest'].items():
# The clients interpolate three ticks behind, and reads are not simultaneous.
assert all(min(math.dist(p, q) for q in paths['host'][id]) < 1.5 for p in positions), \
f'bullet {id} diverged from the host: {paths}'
# Put blocks in the flight volume to exercise server removal without depending on homing.
for game in (host, guest):
game('command', command='gamemode creative')
game('command', command=f'tp @s {x + 0.5} {y + 16} {z + 0.5}')
host('command', command=f'fill {x - 10} {y} {z - 10} {x + 10} {y + 12} {z + 18} minecraft:stone')
for _ in range(20):
guest.wait(2)
remaining = {g.name: bullets(g('status')) for g in (host, guest)}
if not any(remaining.values()):
break
assert not any(remaining.values()), f'bullets survived block hits: {remaining}'
finally:
host('command', command='tick unfreeze')
host('command', command=f'kill @e[tag={tag}]')
host('command', command=f'fill {x - 10} {y} {z - 10} {x + 10} {y + 12} {z + 18} minecraft:air')
for game in (host, guest):
game('command', command='effect clear @s')
game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
game('command', command='gamemode survival')
face_each_other(host, guest)
return {'shots': shots, 'ids': sorted(paths['host']), 'removed': True}
CHECKS += ['shulker_bullets']
CHECK_FNS.update(shulker_bullets=check_shulker_bullets)
def check_farmland(host, guest, out):
"""FarmlandBlock.fallOn's base-block change breaks the unsupported crop (#1492):
the host and guest each land on mature wheat, get its drops, and both clients see dirt/air."""
hx, hy, hz = (int(v // 1) for v in pos_of(host))
y = max(hy + 12, 100)
starts = {g.name: pos_of(g) for g in (host, guest)}
seen = {}
host('command', command='gamerule random_tick_speed 0')
try:
for game, other, dz in ((host, guest, -3), (guest, host, 3)):
x, z = hx + 2, hz + dz
soil, crop, marker = (x, y, z), (x, y + 1, z), (x + 4, y + 1, z)
for g in (game, other):
g('command', command='gamemode creative')
host('command', command=f'fill {x - 4} {y} {z - 2} {x + 4} {y} {z + 2} minecraft:stone')
host('command', command=f'fill {x - 4} {y + 1} {z - 2} {x + 4} {y + 7} {z + 2} minecraft:air')
host('command', command=f'setblock {x} {y} {z} minecraft:farmland[moisture=7]')
host('command', command=f'setblock {x} {y + 1} {z} minecraft:wheat[age=7]')
other('command', command=f'tp @s {x + 3.5} {y + 1} {z + 0.5}')
game('command', command=f'tp @s {x + 2.5} {y + 1} {z + 0.5}')
game('command', command='clear @s')
game('command', command='gamemode survival')
game.wait(20)
before = {g.name: [g.raw('block', *p).get('block') for p in (soil, crop)]
for g in (host, guest)}
assert all(v == ['minecraft:farmland', 'minecraft:wheat'] for v in before.values()), \
f'{game.name}: planted wheat missing before landing: {before}'
other.raw('look-at', x + 0.5, y + 1, z + 0.5)
other.shot(out, f'farmland-{game.name}-before')
# More than 1.5 blocks of fall distance guarantees the trampling random check.
game('command', command=f'tp @s {x + 0.5} {y + 6} {z + 0.5}')
game.wait(80)
after = {g.name: [g.raw('block', *p).get('block') for p in (soil, crop)]
for g in (host, guest)}
# Test the authoritative blocks too, rather than only each client's view.
game('command', command=f'execute if block {x} {y} {z} minecraft:dirt '
f'if block {x} {y + 1} {z} minecraft:air run '
f'setblock {marker[0]} {marker[1]} {marker[2]} minecraft:gold_block')
game.wait(10)
counts = {item: server_count(game, item) for item in ('wheat', 'wheat_seeds')}
client_counts = game('inventory')['counts']
seen[game.name] = {'blocks': after, 'server': game.raw('block', *marker).get('block'),
'drops': counts,
'client_drops': {item: client_counts.get('minecraft:' + item, 0)
for item in counts}}
other.shot(out, f'farmland-{game.name}-after')
finally:
host('command', command='gamerule random_tick_speed 3')
host('command', command='kill @e[type=minecraft:item]')
for g in (host, guest):
x0, y0, z0 = starts[g.name]
g('command', command=f'tp @s {x0} {y0} {z0}')
g('command', command='gamemode survival')
for name, s in seen.items():
assert all(v == ['minecraft:dirt', 'minecraft:air'] for v in s['blocks'].values()), \
f'{name}: unsupported wheat after landing: {seen}'
assert s['server'] == 'minecraft:gold_block', f'{name}: server kept the unsupported wheat: {seen}'
assert s['drops']['wheat'] == 1 and 1 <= s['drops']['wheat_seeds'] <= 4, \
f'{name}: mature wheat drops missing: {seen}'
assert s['client_drops'] == s['drops'], f'{name}: crop drops did not synchronize: {seen}'
return seen
CHECKS += ['farmland']
CHECK_FNS.update(farmland=check_farmland)
def check_large_chest(host, guest, out):
"""Every player slot can be picked up or shift-clicked into a double chest (#1505, #1589).
Reopening checks the authoritative contents, with a single chest as the control."""
seen = {}
for game in (host, guest):
game('command', command='gamemode survival')
x, y, z = (int(v // 1) for v in pos_of(game))
chest, other = (x, y, z + 2), (x + 1, y, z + 2)
try:
for double in (False, True):
size = 54 if double else 27
# Double chest indices 54..89 include the old cutoff at 63/64 and every hotbar slot.
sources = list(range(9, 36)) + list(range(9)) if double else [19, 0, 8]
for shift in (False, True):
back_to_game(game)
for at in (chest, other):
game('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
game('command', command='kill @e[type=minecraft:item,distance=..8]')
game('command', command='clear @s')
block = 'minecraft:chest[facing=north,type=left]' if double else 'minecraft:chest'
game('command', command=f'setblock {x} {y} {z + 2} {block}')
if double:
game('command', command=f'setblock {x + 1} {y} {z + 2} minecraft:chest[facing=north,type=right]')
for slot in sources:
name = f'hotbar.{slot}' if slot < 9 else f'inventory.{slot - 9}'
game('command', command=f'item replace entity @s {name} with minecraft:diamond')
game.wait(10)
game.raw('interact', *chest)
game.raw('wait-for', 'screen', 'container', '--timeout', 10)
game.wait(10)
assert container_items(game)[1] == size, f'{game.name}: expected {size} chest slots'
label = f'{"double" if double else "single"}-chest-{"shift" if shift else "pickup"}'
for target, slot in enumerate(sources):
if shift:
game.raw('key', 'shift', 'down')
try:
mouse(game, slot)
finally:
if shift:
game.raw('key', 'shift', 'up')
if not shift:
held = game('inventory').get('carried') or {}
if held.get('item') != 'minecraft:diamond' or held.get('count') != 1:
game.shot(out, f'{label}-slot-{slot}-failed')
raise AssertionError(f'{game.name} {label}: slot {slot} picked up {held}')
mouse(game, 300 + target)
game.raw('key', 'esc', 'tap')
game.wait(10)
game.raw('interact', *chest)
game.raw('wait-for', 'screen', 'container', '--timeout', 10)
game.wait(10)
contents = [s for s in game('screen')['slots'] if 300 <= s['slot'] < 300 + size and s.get('item')]
inv = game('inventory')
stored = sum(s['count'] for s in contents if s['item'] == 'minecraft:diamond')
assert stored == len(sources) and not inv['counts'].get('minecraft:diamond') and not inv.get('carried'), \
f'{game.name} {label}: chest {contents}, inventory {inv}'
game.shot(out, label)
seen[f'{game.name}-{label}'] = stored
game.raw('key', 'esc', 'tap')
finally:
back_to_game(game)
for at in (chest, other):
game('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
game('command', command='kill @e[type=minecraft:item,distance=..8]')
game('command', command='clear @s')
return seen
CHECKS += ['large_chest']
CHECK_FNS.update(large_chest=check_large_chest)
def check_falling(host, guest, out):
"""ItemEntity and FallingBlockEntity tick on a client too (gravity, collisions, drag), and their
position packets snap them (Entity's NO_OP InterpolationHandler). The server sends an item's
+1 -2
View File
@@ -167,8 +167,7 @@ def main():
os.symlink(bins / name, version / name)
os.symlink(resources, version / '.local/horizon-client' / lab.VERSION)
(version / '.installed').write_text('')
env = dict(os.environ, HORIZON_LAUNCHER_HOME=str(work / 'launcher'), HORIZON_HOME=str(work / 'home'),
HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
env = lab.game_env(HORIZON_LAUNCHER_HOME=work / 'launcher', HORIZON_HOME=work / 'home', HORIZON_TELEMETRY_URL='off')
m = Mcp(Path(args.launcher).resolve(), env)
try:
summary = scenario(m, out)
+6 -2
View File
@@ -33,6 +33,11 @@ import tempfile
import time
from pathlib import Path
try:
from . import lab
except ImportError:
import lab
ROOT = Path(__file__).resolve().parents[1]
@@ -154,8 +159,7 @@ def main():
args = ap.parse_args()
home = Path(tempfile.mkdtemp(prefix="horizon-mod-browser-"))
env = dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO="1", HORIZON_NO_HEARTBEAT="1",
HORIZON_CONTROL=str(home / "ctl.sock"))
env = lab.game_env(HORIZON_HOME=home, HORIZON_NO_HEARTBEAT="1", HORIZON_CONTROL=home / "ctl.sock")
launcher = [args.launcher]
game = Game(str(Path(args.bin) / "horizon-ctl"), str(Path(args.bin) / "horizon-client"),
args.resources, home, env)
+7
View File
@@ -39,6 +39,7 @@ import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import socket
import subprocess
import sys
@@ -812,6 +813,12 @@ class LocalExecutor:
trace.unlink(missing_ok=True)
log = (STATE_DIR / "logs" / f"{name}.log").open("w")
environment = run_environment(reuse)
# A game the harness starts logs into HORIZON_HOME, which is a real player's folder when it is unset
# (lab.game_env keeps this one).
game_home = STATE_DIR / "game-home" / name
shutil.rmtree(game_home, ignore_errors=True)
game_home.mkdir(parents=True)
environment.setdefault("HORIZON_HOME", str(game_home))
environment["PARITY_SHIM_OUTPUTS"] = str(outputs_listing(name, fresh=True))
environment.pop("PARITY_SHARD", None)
if shard:
+1 -1
View File
@@ -400,7 +400,7 @@ def run_horizon(args, distance):
for carry in dev_mods(args):
command += ["--dev-mod", str(carry)]
# Benchmark runs stay out of the live count and send nothing (docs/telemetry.md).
env = dict(os.environ, HORIZON_NO_AUDIO="1", HORIZON_TELEMETRY_URL="off")
env = lab.game_env(HORIZON_TELEMETRY_URL="off")
if args.warm:
# A first start to the title screen builds what later starts reuse (the content-mod
# root, the block behaviour snapshot). It is not measured: players see it once.
+1 -1
View File
@@ -120,7 +120,7 @@ class Server:
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'))
env=lab.game_env())
threading.Thread(target=self._read, daemon=True).start()
def _read(self):
+3 -4
View File
@@ -206,9 +206,8 @@ class Game:
self.home = work / 'home'
for d in ('home', 'launcher', 'data', 'config'):
(work / d).mkdir(parents=True)
self.env = dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_LAUNCHER_HOME=str(work / 'launcher'),
XDG_DATA_HOME=str(work / 'data'), XDG_CONFIG_HOME=str(work / 'config'),
HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
self.env = lab.game_env(HORIZON_HOME=self.home, HORIZON_LAUNCHER_HOME=work / 'launcher',
XDG_DATA_HOME=work / 'data', XDG_CONFIG_HOME=work / 'config', HORIZON_TELEMETRY_URL='off')
self.base = [str(bins / 'horizon-ctl'), '--socket', str(work / 'c.sock')]
self.log = work / 'c.log'
reply = self('launch', '--game', bins / 'horizon-client', '--offscreen', '--resources', resources)
@@ -343,7 +342,7 @@ class Run:
('XDG_CONFIG_HOME', 'config')):
(work / 'servers' / sub).mkdir(parents=True)
os.environ[var] = str(work / 'servers' / sub)
os.environ.update(HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
os.environ.update(lab.game_env(HORIZON_TELEMETRY_URL='off'))
game = self.game = Game(Path(self.args.bin), self.resources, work / 'game')
servers_dat = game.home / 'servers.dat'
downloads = game.home / 'downloads'
+1 -1
View File
@@ -183,7 +183,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
+1 -1
View File
@@ -82,7 +82,7 @@ def main():
rust_dir = build / 'rust'
shutil.rmtree(rust_dir, ignore_errors=True)
rust_dir.mkdir()
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_COMMAND_SCRIPT=str(script_path), HORIZON_COMMAND_OUTPUT=str(build / 'rust.jsonl'))
env = lab.game_env(HORIZON_COMMAND_SCRIPT=script_path, HORIZON_COMMAND_OUTPUT=build / 'rust.jsonl')
run([binary, '--resources', lab.RESOURCES, '--world', 'harness', '--seed', SEED, '--radius', 4], 'rust', cwd=rust_dir, env=env)
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').open(encoding='utf-8')]
+1 -1
View File
@@ -125,7 +125,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+1 -1
View File
@@ -245,7 +245,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+18 -13
View File
@@ -126,7 +126,7 @@ class Server:
self.lines = []
self.process = subprocess.Popen(list(map(str, command)), cwd=directory, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
encoding='utf-8', errors='replace')
encoding='utf-8', errors='replace', env=lab.game_env())
self.reader = threading.Thread(target=self._read, daemon=True)
self.reader.start()
@@ -181,20 +181,25 @@ def settle(server, ticks=600, timeout=600):
break
time.sleep(2)
def game_time():
start = len(server.lines)
server.console('time query gametime')
while time.time() < deadline:
for line in server.lines[start:]:
if m := re.search(r'The (?:game )?time is (\d+)', line):
return int(m.group(1))
time.sleep(0.2)
raise AssertionError(f'{server.log_path.name}: no game time in {timeout} s')
until = game_time() + ticks
while game_time() < until:
until = game_time(server, deadline - time.time()) + ticks
while game_time(server, deadline - time.time()) < until:
time.sleep(2)
def game_time(server, timeout=300):
"""The server's game time, asked from its console: the console runs its queue in order, so every console
command sent before has run."""
deadline = time.time() + timeout
start = len(server.lines)
server.console('time query gametime')
while time.time() < deadline:
for line in server.lines[start:]:
if m := re.search(r'The (?:game )?time is (\d+)', line):
return int(m.group(1))
time.sleep(0.05)
raise AssertionError(f'{server.log_path.name}: no game time in {timeout:.0f} s')
def legacy_ping(port):
"""The reply to a 1.6 client's 0xFE 0x01 0xFA MC|PingHost query (LegacyQueryHandler)."""
host = 'localhost'
@@ -352,7 +357,7 @@ def horizon_client_joins(vanilla_server, binary, world, build, reference):
server = Server(vanilla_server, directory, label)
try:
server.wait_for(r'Done \(')
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report))
env = lab.game_env(HORIZON_NET_REPORT=report)
with (build / 'horizon-client-run.log').open('w') as log:
subprocess.run([str(c) for c in [binary, '--resources', lab.RESOURCES, '--render-distance', 2,
'--server', f'127.0.0.1:{port}', '--name', PLAYER]],
+1 -1
View File
@@ -417,7 +417,7 @@ def main():
run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
+1 -1
View File
@@ -96,7 +96,7 @@ class Game:
self.process = subprocess.Popen(Game.prefix + [
str(client), '--resources', str(resources), '--render-distance', '2', '--test-terrain',
'--control-socket', str(self.endpoint), '--timeout-seconds', '600',
] + Game.extra, cwd=self.home, env=dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_NO_AUDIO='1', **env),
] + Game.extra, cwd=self.home, env=lab.game_env(HORIZON_HOME=self.home, **env),
stdout=self.log, stderr=subprocess.STDOUT)
wait_for(self.endpoint, 'screen', lambda v: v['screen'] == 'title', 120, f'{name} title')
+177
View File
@@ -0,0 +1,177 @@
#!/usr/bin/env python3
"""Item stacks on the wire: every data component, as vanilla 26.3 encodes it.
VanillaItemWireOracle encodes stacks with ItemStack.OPTIONAL_STREAM_CODEC
(what a server sends in inventories, recipe books and advancements): each
default component value of every vanilla item, the SNBT fixtures below
(direct holders, tags and lists, optional fields, every consume effect,
block predicates with component matchers, the mob variants) and patches
built in Java (components without a persistent codec, removals). The Rust
probe decodes each with horizon_protocol::item::Slot and must consume every
byte and find the same component ids in the same order; a stack whose
components Horizon only reads past must also encode back to the same bytes.
Every id in DataComponents must be covered."""
import argparse
import json
import os
import platform
import subprocess
from pathlib import Path
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
COMPONENT_TYPES = 122
FIXTURES = [
('custom_data', '{custom_data:{a:1,b:"x",c:[1,2]}}'),
('unbreakable', '{unbreakable:{}}'),
('custom_name', '{custom_name:{text:"Hi",color:"red",bold:1b}}'),
('lore', '{lore:["a",{text:"b",italic:0b}]}'),
('enchantments', '{enchantments:{"minecraft:sharpness":5,"minecraft:unbreaking":3}}'),
('can_break tag', '{can_break:{blocks:"#minecraft:logs"}}'),
('can_break list state nbt', '{can_break:[{blocks:["minecraft:stone","minecraft:dirt"],state:{snowy:"true",age:{min:"1",max:"3"},level:{min:"2"}},nbt:"{a:1b}"}]}'),
('can_place_on components', '{can_place_on:{blocks:"minecraft:chest",components:{"minecraft:custom_name":"x","minecraft:damage":3},predicates:{"minecraft:custom_data":{a:1},"minecraft:damage":{durability:{min:1}}}}}'),
('can_place_on empty', '{can_place_on:[{}]}'),
('custom_model_data', '{custom_model_data:{floats:[1.0f,2.5f],flags:[1b,0b],strings:["a"],colors:[16711680]}}'),
('tooltip_display', '{tooltip_display:{hide_tooltip:1b,hidden_components:["minecraft:enchantments","minecraft:damage"]}}'),
('repair_cost', '{repair_cost:7}'),
('intangible_projectile', '{intangible_projectile:{}}'),
('tooltip_style', '{tooltip_style:"minecraft:fancy"}'),
('interact_animation', '{interact_animation:{type:"stab",duration:9}}'),
('dyed_color', '{dyed_color:16711935}'),
('map_id', '{map_id:42}'),
('written_book_content', '{written_book_content:{title:{raw:"T",filtered:"F"},author:"me",generation:1,pages:[{raw:"p1",filtered:"q1"},"p2"],resolved:1b}}'),
('trim registry', '{trim:{material:"minecraft:gold",pattern:"minecraft:coast"}}'),
('trim direct', '{trim:{material:{palette_id:"minecraft:x",description:"X"},pattern:{asset_id:"minecraft:y",description:"Y",decal:1b}}}'),
('block_entity_data', '{block_entity_data:{id:"minecraft:chest",Items:[]}}'),
('lodestone_tracker target', '{lodestone_tracker:{target:{dimension:"minecraft:the_nether",pos:[1,-64,3]},tracked:0b}}'),
('lodestone_tracker empty', '{lodestone_tracker:{}}'),
('firework_explosion', '{firework_explosion:{shape:"star",colors:[1,2],fade_colors:[3],has_trail:1b,has_twinkle:0b}}'),
('profile name', '{profile:{name:"Notch"}}'),
('profile full', '{profile:{name:"jeb_",id:[I;1,2,3,4],properties:[{name:"textures",value:"abc",signature:"sig"}]}}'),
('note_block_sound', '{note_block_sound:"minecraft:block.note_block.bell"}'),
('base_color', '{base_color:"lime"}'),
('sulfur_cube_content', '{sulfur_cube_content:{id:"minecraft:stone",count:1}}'),
('lock', '{lock:{items:"minecraft:diamond"}}'),
('container_loot', '{container_loot:{loot_table:"minecraft:chests/simple_dungeon",seed:5L}}'),
('waxed', '{waxed:{}}'),
('banner_patterns', '{banner_patterns:[{pattern:"minecraft:stripe_bottom",color:"red"},{pattern:{asset_id:"minecraft:x",translation_key:"y"},color:"blue"}]}'),
('pot_decorations', '{pot_decorations:{back:{id:"minecraft:brick"},left:{id:"minecraft:angler_pottery_sherd"},front:{id:"minecraft:skull_pottery_sherd",count:1}}}'),
('suspicious_stew_effects', '{suspicious_stew_effects:[{id:"minecraft:night_vision",duration:100},{id:"minecraft:poison"}]}'),
('potion_contents full', '{potion_contents:{potion:"minecraft:swiftness",custom_color:123,custom_effects:[{id:"minecraft:speed",amplifier:1b,duration:200,ambient:1b,show_particles:0b,show_icon:1b,hidden_effect:{id:"minecraft:speed",duration:100,hidden_effect:{id:"minecraft:speed",duration:50}}}],custom_name:"x"}}'),
('potion_contents bare', '{potion_contents:{}}'),
('container', '{container:[{slot:0,item:{id:"minecraft:stone",count:3}},{slot:5,item:{id:"minecraft:diamond_sword",components:{"minecraft:damage":5,"minecraft:trim":{material:"minecraft:gold",pattern:"minecraft:coast"}}}}]}'),
('bundle_contents', '{bundle_contents:[{id:"minecraft:stone",count:2},{id:"minecraft:potion",components:{"minecraft:potion_contents":{potion:"minecraft:water"}}}]}'),
('charged_projectiles', '{charged_projectiles:[{id:"minecraft:arrow"},{id:"minecraft:firework_rocket",components:{"minecraft:fireworks":{flight_duration:2b,explosions:[{shape:"burst",colors:[5]}]}}}]}'),
('block_state', '{block_state:{facing:"north",half:"top"}}'),
('bees', '{bees:[{entity_data:{id:"minecraft:bee",Health:5f},ticks_in_hive:5,min_ticks_in_hive:10}]}'),
('entity_data', '{entity_data:{id:"minecraft:pig",NoAI:1b}}'),
('bucket_entity_data', '{bucket_entity_data:{Health:5f}}'),
('instrument direct', '{instrument:{sound_event:{sound_id:"minecraft:x",range:8f},use_duration:3f,range:64f,description:"Horn"}}'),
('painting variant', '{"minecraft:painting/variant":"minecraft:kebab"}'),
('sign_text_front', '{sign_text_front:{messages:["a","b","c","d"],filtered_messages:["e","f","g","h"],color:"red",has_glowing_text:1b}}'),
('sign_text_back', '{sign_text_back:{messages:["a","","",""]}}'),
('map_decorations', '{map_decorations:{a:{type:"minecraft:player",x:1.0d,z:2.0d,rotation:0f}}}'),
('debug_stick_state', '{debug_stick_state:{"minecraft:oak_stairs":"facing"}}'),
('recipes', '{recipes:["minecraft:stone_bricks"]}'),
('attribute_modifiers', '{attribute_modifiers:[{type:"minecraft:attack_damage",id:"minecraft:x",amount:1.5d,operation:"add_value",slot:"mainhand",display:{type:"override",value:"hi"}},{type:"minecraft:armor",id:"minecraft:y",amount:2d,operation:"add_multiplied_total",display:{type:"hidden"}}]}'),
('consumable all effects', '{consumable:{consume_seconds:2f,animation:"drink",sound:{sound_id:"minecraft:x",range:4f},has_consume_particles:0b,on_consume_effects:[{type:"apply_effects",effects:[{id:"minecraft:speed",duration:20}],probability:0.5f},{type:"remove_effects",effects:"minecraft:poison"},{type:"remove_effects",effects:["minecraft:poison","minecraft:wither"]},{type:"clear_all_effects"},{type:"teleport_randomly",diameter:8f},{type:"play_sound",sound:"minecraft:entity.generic.eat"}]}}'),
('death_protection', '{death_protection:{death_effects:[{type:"clear_all_effects"}]}}'),
('equippable full', '{equippable:{slot:"head",equip_sound:"minecraft:item.armor.equip_gold",asset_id:"minecraft:gold",camera_overlay:"minecraft:misc/pumpkinblur",allowed_entities:"#minecraft:skeletons",dispensable:0b,swappable:0b,damage_on_hurt:0b,equip_on_interact:1b,can_be_sheared:1b,shearing_sound:{sound_id:"minecraft:y"}}}'),
('equippable bare', '{equippable:{slot:"chest"}}'),
('tool rules', '{tool:{rules:[{blocks:"#minecraft:mineable/pickaxe",speed:4f,correct_for_drops:1b},{blocks:["minecraft:stone"]}],default_mining_speed:2f,damage_per_block:2,can_destroy_blocks_in_creative:0b}}'),
('blocks_attacks full', '{blocks_attacks:{block_delay_seconds:0.5f,disable_cooldown_scale:2f,damage_reductions:[{horizontal_blocking_angle:45f,type:"#minecraft:is_fire",base:1f,factor:0.5f},{base:0f,factor:1f}],item_damage:{threshold:3f,base:1f,factor:2f},bypassed_by:"#minecraft:bypasses_shield",block_sound:"minecraft:item.shield.block",disable_sound:{sound_id:"minecraft:z"}}}'),
('damage_resistant', '{damage_resistant:{types:"#minecraft:is_fire"}}'),
('repairable list', '{repairable:{items:["minecraft:diamond","minecraft:emerald"]}}'),
('use_cooldown group', '{use_cooldown:{seconds:1.5f,cooldown_group:"minecraft:x"}}'),
('use_remainder', '{use_remainder:{id:"minecraft:bowl",count:2}}'),
('fireworks', '{fireworks:{flight_duration:3b,explosions:[{shape:"creeper",colors:[1],fade_colors:[2,3],has_trail:1b},{shape:"small_ball"}]}}'),
('provides_banner_patterns', '{provides_banner_patterns:"#minecraft:pattern_item/globe"}'),
('wolf variant', '{"minecraft:wolf/variant":"minecraft:ashen","minecraft:wolf/sound_variant":"minecraft:angry","minecraft:wolf/collar":"red"}'),
('fox salmon parrot', '{"minecraft:fox/variant":"snow","minecraft:salmon/size":"large","minecraft:parrot/variant":"blue"}'),
('tropical fish', '{"minecraft:tropical_fish/pattern":"flopper","minecraft:tropical_fish/base_color":"white","minecraft:tropical_fish/pattern_color":"black"}'),
('mooshroom rabbit', '{"minecraft:mooshroom/variant":"brown","minecraft:rabbit/variant":"gold"}'),
('pig cow chicken', '{"minecraft:pig/variant":"minecraft:cold","minecraft:pig/sound_variant":"minecraft:big","minecraft:cow/variant":"minecraft:warm","minecraft:cow/sound_variant":"minecraft:classic","minecraft:chicken/variant":"minecraft:cold","minecraft:chicken/sound_variant":"minecraft:classic"}'),
('nautilus frog horse', '{"minecraft:zombie_nautilus/variant":"minecraft:warm","minecraft:frog/variant":"minecraft:cold","minecraft:horse/variant":"chestnut"}'),
('llama axolotl cat', '{"minecraft:llama/variant":"brown","minecraft:axolotl/variant":"blue","minecraft:cat/variant":"minecraft:tabby","minecraft:cat/sound_variant":"minecraft:classic","minecraft:cat/collar":"blue"}'),
('sheep shulker villager', '{"minecraft:sheep/color":"pink","minecraft:shulker/color":"purple","minecraft:villager/variant":"minecraft:taiga"}'),
('trim material direct provider', '{provides_trim_material:{palette_id:"minecraft:x",description:"X"}}'),
('everything at once', '{damage:3,unbreakable:{},custom_name:"n",enchantments:{"minecraft:mending":1},trim:{material:"minecraft:gold",pattern:"minecraft:coast"},banner_patterns:[{pattern:"minecraft:globe",color:"red"}],pot_decorations:{right:{id:"minecraft:brick"}},lore:["x"],rarity:"epic"}'),
]
# Fixtures on another item than a stick (the components need it, or read better there).
ITEMS = {'profile name': 'player_head', 'profile full': 'player_head', 'trim registry': 'diamond_chestplate',
'trim direct': 'diamond_chestplate', 'banner_patterns': 'white_banner', 'pot_decorations': 'decorated_pot',
'everything at once': 'diamond_chestplate'}
def compare(vanilla, rust):
"""Failures, stacks checked, and the component ids covered."""
results = {r['label']: r for r in rust}
failures, covered = [], set()
for v in vanilla:
if 'error' in v:
failures.append(f"oracle {v['label']}: {v['error']}")
continue
covered.update(v['added'] + v['removed'])
r = results.get(v['label'])
if r is None or 'error' in r:
failures.append(f"{v['label']}: {r and r['error']}")
elif r['left'] or r['added'] != v['added'] or r['removed'] != v['removed']:
failures.append(f"{v['label']}: {r['left']} bytes left, ids {r['added']}/{r['removed']}, vanilla {v['added']}/{v['removed']}")
elif not r['same_bytes'] and not r['typed']:
failures.append(f"{v['label']}: read past, but encoded back differently")
missing = sorted(set(range(COMPONENT_TYPES)) - covered)
if missing:
failures.append(f'component ids no stack covers: {missing}')
return failures, len(vanilla), covered
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'item-wire-parity'
build.mkdir(parents=True, exist_ok=True)
report_path = build / 'report.json'
report_path.unlink(missing_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemWireOracle.java'
classes = build / 'classes'
classes.mkdir(exist_ok=True)
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
dependency_path = os.pathsep.join(map(str, libraries))
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', str(jars['server']) + os.pathsep + dependency_path,
'-d', classes, oracle], 'compile-java')
fixtures = build / 'fixtures.tsv'
fixtures.write_text(''.join(f'{label}\t{{id:"minecraft:{ITEMS.get(label, "stick")}",count:1,components:{snbt}}}\n'
for label, snbt in FIXTURES), encoding='utf-8')
vanilla_path, rust_path = build / 'vanilla.jsonl', build / 'rust.jsonl'
run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), dependency_path]),
'dev.horizonlab.parity.VanillaItemWireOracle', fixtures, vanilla_path], 'oracle')
run(['cargo', 'build', '--release', '-p', 'horizon-protocol', '--example', 'item_wire_probe'], 'compile-rust')
binary = lab.cargo_target() / 'release/examples' / ('item_wire_probe.exe' if os.name == 'nt' else 'item_wire_probe')
run([binary, vanilla_path, rust_path], 'rust')
read = lambda path: [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines() if line.strip()]
failures, stacks, covered = compare(read(vanilla_path), read(rust_path))
for failure in failures[:40]:
print(failure)
if failures:
raise SystemExit(f'{len(failures)} item wire mismatches (of {stacks} stacks)')
lab.write_json(report_path, {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(),
'stacks': stacks, 'component_types_covered': len(covered),
'oracle_sha256': lab.digest(vanilla_path, 'sha256'), 'rust_sha256': lab.digest(rust_path, 'sha256')})
print(f'Item wire parity passed: {stacks} stacks, all {len(covered)} component types: {report_path}')
if __name__ == '__main__':
main()
+1 -1
View File
@@ -170,7 +170,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+1 -1
View File
@@ -71,7 +71,7 @@ def main():
str(executable), '--radius', '1', '--frames', '30',
'--smoke-report', str(report), '--timeout-seconds', '60']
with (root / 'startup-smoke.log').open('w') as log:
subprocess.run(command, cwd=lab.ROOT, env=environment, check=True,
subprocess.run(command, cwd=lab.ROOT, env=lab.game_env(environment), check=True,
stdout=log, stderr=subprocess.STDOUT, timeout=120)
result = json.loads(report.read_text())
if (result.get('error') is not None or result.get('presented_frames') != 30
+2 -2
View File
@@ -179,7 +179,7 @@ def run_client(binary, build, port, label, token, discovery):
shutil.rmtree(directory, ignore_errors=True)
directory.mkdir()
report = directory / 'report.json'
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report), HORIZON_API_DISCOVERY=discovery)
env = lab.game_env(HORIZON_NET_REPORT=report, HORIZON_API_DISCOVERY=discovery)
command = [binary, '--resources', lab.RESOURCES, '--render-distance', 2,
'--server', f'127.0.0.1:{port}', '--name', PLAYER]
if token:
@@ -246,7 +246,7 @@ def run_side(label, command, binary, build, services, discovery):
props = dict(PROPERTIES, **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
(directory / 'eula.txt').write_text('eula=true\n')
os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery)
os.environ.update(lab.game_env(HORIZON_API_DISCOVERY=discovery))
server = Server(command, directory, f'{label}-online')
checks = []
starts = []
+2 -2
View File
@@ -330,7 +330,7 @@ def entity_uuid_text(i):
def vscreen_env():
text = subprocess.run(['vscreen', 'env'], capture_output=True, text=True, check=True).stdout
env = dict(os.environ)
env = lab.game_env()
env.pop('DISPLAY', None)
for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]):
env[match.group(1)] = match.group(2)
@@ -346,7 +346,7 @@ def horizon_resave(source, destination, bin_dir):
ctl = [str(bin_dir / 'horizon-ctl'), '--socket', str(socket)]
extra = []
if sys.platform == 'darwin':
env = dict(os.environ, HORIZON_NO_AUDIO='1')
env = lab.game_env()
extra = ['--offscreen']
else:
alsa = destination / 'null-asound.conf'
+1 -1
View File
@@ -339,7 +339,7 @@ def main():
oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'],
build, 'compile-rust')
oracle_harness.run_logged([lab.cargo_target() / 'release/horizon-client', '--resources', resources], build, 'horizon',
env={**os.environ, 'HORIZON_SCULK_FIXTURE': f'{inputs},{build / "horizon.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_SCULK_FIXTURE=f'{inputs},{build / "horizon.txt"}'))
if args.java_only:
return
names = {s[0] for _, s in chosen}
+1 -1
View File
@@ -264,7 +264,7 @@ def main():
oh.run_logged([*java, 'keys', build], build, 'keys')
services = Services(json.loads((build / 'publickeys.json').read_text()))
discovery = services.url + '/minecraft/client'
os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery)
os.environ.update(lab.game_env(HORIZON_API_DISCOVERY=discovery))
servers = {
'vanilla': ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}',
'-cp', dependencies, 'net.minecraft.server.Main', 'nogui'],
+34 -12
View File
@@ -10,7 +10,11 @@ A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`)
vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both (players made
of vanilla's protocol code) and records, step by step, the system chat each receives and what the server changes
about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other
players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly,
players it is sent or loses and the levels it respawns into. A step ends by the server's clock, not the wall's: its
console commands have run (the console's `time query gametime` comes back), each player's commands have run (a
`sync` round trip), the server has ticked STEP_TICKS more times, and each client holds what was sent until then (a
last `sync`), so a server that stalls under load still has each packet recorded in its own step (a fixed 2.5 s
filed a stalled vanilla's teleports under the next step). Each player's lines in each step are compared exactly,
in sorted order (the packets of one step may leave in another order within the tick), with the locator bar's
waypoints as each step leaves them (one manager per level: a player in another level is untracked). What a death does besides its messages
is left to its own harness.
@@ -25,12 +29,12 @@ import time
try:
from . import lab, test_rust_parity as base
from .test_dedicated_server_parity import Server
from .test_dedicated_server_parity import Server, game_time
from .test_locator_bar_parity import generate_world, server_dir
except ImportError:
import lab
import test_rust_parity as base
from test_dedicated_server_parity import Server
from test_dedicated_server_parity import Server, game_time
from test_locator_bar_parity import generate_world, server_dir
NAME = 'server-player-targets-parity'
@@ -70,7 +74,8 @@ SCRIPT = [
# What the players' locator bars show has its own harness (test_locator_bar_parity), and what a death does
# besides its messages (drops, the body leaving) the player combat ones: here only the messages of `kill`.
DEATH_STEP = 'step=console-kill'
STEP_SECONDS = 2.5
STEP_TICKS = 40
PLAYERS = ('Alice', 'Bob')
def run_side(label, server_command, client_command, build, world):
@@ -83,32 +88,49 @@ def run_side(label, server_command, client_command, build, world):
server.wait_for(r'Done \(')
with (build / f'{label}-client.log').open('w') as log:
client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
text=True)
cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True)
def tell(line):
client.stdin.write(line + '\n')
client.stdin.flush()
def sync():
for name in PLAYERS:
tell(f'sync {name}')
for name in PLAYERS:
while (line := client.stdout.readline()) != f'synced {name}\n':
if not line:
raise AssertionError(f'{label}: the client exited (see {build}/{label}-client.log)')
log.write(line)
def finish_step():
sync()
until = game_time(server) + STEP_TICKS
while game_time(server) < until:
time.sleep(0.2)
for name in PLAYERS:
tell(f'still {name}')
sync()
try:
for name, x in (('Alice', 0.5), ('Bob', 4.5)):
for name, x in zip(PLAYERS, (0.5, 4.5)):
tell(f'join {name}')
server.wait_for(rf'{name} joined the game', timeout=120)
tell(f'fly {name} on')
tell(f'cmd {name} tp @s {x} -60 0.5 0 0')
time.sleep(STEP_SECONDS)
finish_step()
for flag in ('chat', 'state', 'players'):
tell(f'{flag} on')
for step, console, actions in SCRIPT:
tell(f'step {step}')
for command in console:
server.console(command)
game_time(server) # the console runs its queue in order: these commands have run
for action in actions:
tell(action)
time.sleep(STEP_SECONDS)
for name in ('Alice', 'Bob'):
tell(f'still {name}')
finish_step()
tell('end')
client.wait(timeout=60)
log.write(client.communicate(timeout=60)[0])
finally:
if client.poll() is None:
client.kill()
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Compare Horizon's structure starts, piece by piece, with the starts a real server saved.
Expected side: the clean-room structure oracle (horizon-parity `cleanroom/structures/oracle/`), which ran
vanilla 1.21.1 servers and kept every saved start. Its `base_pieces` are the no-mod world's start of each
located structure (villages, outposts, trial chambers, shipwrecks, ruined portals, desert pyramids): the
vanilla layout. Its results live outside the repository; put them (or link them) under
`.local/structure-oracle/<profile>/seed-<seed>.json.gz`, or point HORIZON_STRUCTURE_ORACLE at that folder.
Horizon side: the structure_pieces probe generates the same seed and lists the starts each chunk owns.
Jigsaw pieces must match exactly: element (template location), rotation, position, ground level delta and
bounding box, in saved order. Other pieces (shipwrecks, ruined portals, desert pyramids) match by type and
horizontal box: their height is settled when they are placed, after the start is created, and the oracle
saved them placed.
The oracle's game is 1.21.1 and Horizon's 26.3. KNOWN lists the starts where 26.3 itself differs from
1.21.1, each checked against 26.3 vanilla (VanillaChunkGenerationOracle's `scan`, HORIZON_PIECES=1), whose
pieces equal Horizon's there; they are reported, not failed.
usage: test_structure_layout_parity.py [--profile lithostitched] [--filter REGEX] [--verbose]
"""
import argparse
import gzip
import json
import os
import re
import subprocess
import sys
from pathlib import Path
try:
from . import lab
except ImportError:
import lab
ORACLE = Path(os.environ.get('HORIZON_STRUCTURE_ORACLE', lab.LOCAL / 'structure-oracle'))
# (profile, seed, structure id, start chunk x, z) -> how 26.3 vanilla differs from 1.21.1 there.
TRIAL_CHAMBERS = '26.3 vanilla lays it out as Horizon does, unlike 1.21.1'
RUINED_PORTAL = "26.3 vanilla's portal is Horizon's; 1.21.1 picked another"
KNOWN = {
('lithostitched', 1234, 'minecraft:village_plains', -24, 47): 'no start in 26.3 vanilla (nor in Horizon)',
('lithostitched', 1234, 'minecraft:ruined_portal', -16, 51): RUINED_PORTAL,
('lithostitched', 42, 'minecraft:ruined_portal', -19, -38): RUINED_PORTAL,
**{('lithostitched', seed, 'minecraft:trial_chambers', x, z): TRIAL_CHAMBERS
for seed, x, z in [(1234, 13, 21), (2, -28, 13), (2, 11, 16), (2, 146, 44), (42, 17, 7), (42, 38, -25)]},
}
def element(saved):
kind = saved.get('element_type')
if kind in ('minecraft:single_pool_element', 'minecraft:legacy_single_pool_element'):
location = saved['location']
return location if ':' in location else 'minecraft:' + location
if kind == 'minecraft:feature_pool_element':
return 'feature:' + saved['feature']
if kind == 'minecraft:list_pool_element':
return 'list:' + '+'.join(element(e) for e in saved['elements'])
if kind == 'minecraft:empty_pool_element':
return 'empty'
return kind
def expected_piece(saved):
box = saved['BB']
piece = {'type': saved['id'], 'box': box if saved['id'] == 'minecraft:jigsaw' else [box[0], box[2], box[3], box[5]]}
if saved['id'] == 'minecraft:jigsaw':
piece.update(element=element(saved['pool_element']), rotation=saved['rotation'],
position=[saved['PosX'], saved['PosY'], saved['PosZ']], ground_level_delta=saved['ground_level_delta'])
return piece
def probe_binary():
subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'world_probe'], check=True, cwd=lab.ROOT)
name = 'world_probe.exe' if os.name == 'nt' else 'world_probe'
return lab.cargo_target() / 'release/examples' / name
def horizon_starts(binary, seed, dimension, chunks):
result = subprocess.run([str(binary), 'structure_pieces', str(lab.RESOURCES), str(seed), dimension,
*(f'{x},{z}' for x, z in chunks)], capture_output=True, text=True, cwd=lab.ROOT)
if result.returncode:
raise SystemExit('structure_pieces failed: ' + result.stderr[-2000:])
starts, current = {}, None
for line in result.stdout.splitlines():
fields = line.split()
if fields[0] == 'start':
current = starts.setdefault((fields[1], int(fields[2]), int(fields[3])), [])
elif fields[0] == 'piece':
box = list(map(int, fields[8:14]))
piece = {'type': fields[1], 'box': box if fields[1] == 'minecraft:jigsaw' else [box[0], box[2], box[3], box[5]]}
if fields[1] == 'minecraft:jigsaw':
piece.update(element=fields[2], rotation=fields[3], position=list(map(int, fields[4:7])),
ground_level_delta=int(fields[7]))
current.append(piece)
return starts
def compare(expected, actual):
"""Index of the first differing piece and what differs, or None."""
for i, (want, got) in enumerate(zip(expected, actual)):
if want != got:
return i, {k: (want.get(k), got.get(k)) for k in want.keys() | got.keys() if want.get(k) != got.get(k)}
if len(expected) != len(actual):
return min(len(expected), len(actual)), {'pieces': (len(expected), len(actual))}
return None
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--profile', default='lithostitched')
parser.add_argument('--filter', default='', help='only structure ids matching this regex')
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()
results = sorted((ORACLE / args.profile).glob('seed-*.json.gz'))
if not results:
print(f'SKIP: no oracle results in {ORACLE / args.profile} (see this file\'s docstring)')
return 0
binary = probe_binary()
matched, known, failed = 0, 0, []
for path in results:
oracle = json.load(gzip.open(path))
seed = oracle['seed']
by_dimension = {}
for start in oracle['structures']:
if start.get('base_pieces') is None or not re.search(args.filter, start['id']):
continue
by_dimension.setdefault(start['dimension'], []).append(start)
for dimension, starts in by_dimension.items():
chunks = sorted({tuple(s['start_chunk']) for s in starts})
actual = horizon_starts(binary, seed, dimension.removeprefix('minecraft:'), chunks)
for start in starts:
key = (start['id'], *start['start_chunk'])
expected = [expected_piece(p) for p in start['base_pieces']]
got = actual.get(key)
label = f'seed {seed} {start["id"]} chunk {start["start_chunk"]}'
difference = (0, {'start': 'missing in Horizon'}) if got is None else compare(expected, got)
reason = KNOWN.get((args.profile, seed, *key))
if difference is None:
matched += 1
if args.verbose:
print(f'ok {label}: {len(expected)} pieces')
elif reason:
known += 1
print(f'known {label}: {reason}')
else:
failed.append(label)
index, fields = difference
print(f'FAIL {label}: {len(expected)} pieces expected, {len(got or [])} placed; piece {index}: {fields}')
total = matched + known + len(failed)
print(f'{matched} of {total} starts match the oracle piece for piece; {known} known version differences')
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main())
+1 -1
View File
@@ -375,7 +375,7 @@ def main():
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+4 -1
View File
@@ -24,6 +24,9 @@ import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import lab # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
RESOURCES = ROOT / '.local' / 'horizon-client' / '26.3'
RUN = ROOT / '.local' / 'world-reopen'
@@ -32,7 +35,7 @@ CYCLES = 3
def game_env():
"""macOS renders offscreen; Linux uses the virtual screen (as test_save_roundtrip_parity)."""
env = dict(os.environ, HORIZON_NO_AUDIO='1')
env = lab.game_env()
if sys.platform == 'darwin':
return env, ['--offscreen']
subprocess.run(['vscreen', 'up'], check=False, capture_output=True)
+1 -1
View File
@@ -140,7 +140,7 @@ def main():
# One worker thread: the chunks decorated in a fixed order (see above).
vanilla_server = ['java', '-Xmx2g', '-Dmax.bg.threads=1', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui']
os.environ['HORIZON_NO_AUDIO'] = '1'
os.environ.update(lab.game_env())
def one(seed):
t0 = time.time()