Merge feat/server-dialog-screen into feat/styled-menu-titles

Both branches changed the machine screens' title drawing: keep the styled server
title from this branch and the translated container title and inventory label
from feat/server-dialog-screen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-26 03:22:13 +01:00
301 changed files with 22627 additions and 1164 deletions
+39
View File
@@ -291,6 +291,19 @@ def entities():
cmd('/data get entity @e[tag=root,limit=1] Passengers[0].Health'),
cmd('/data get entity @e[tag=root,limit=1] Passengers[0].id'),
cmd('/kill @e[tag=root]'),
# Saved attribute bases are read for every mob, then Health or the max
# health when there is none (LivingEntity.readAdditionalSaveData, #1483).
cmd('/summon minecraft:cow 4.5 210 8.5 {Tags:["attr"],NoAI:1b,NoGravity:1b,'
'attributes:[{id:"minecraft:max_health",base:40.0d},{id:"minecraft:movement_speed",base:0.5d}]}'),
cmd('/data get entity @e[tag=attr,limit=1] Health'),
cmd('/attribute @e[tag=attr,limit=1] minecraft:max_health base get'),
cmd('/attribute @e[tag=attr,limit=1] minecraft:movement_speed base get'),
cmd('/kill @e[tag=attr]'),
cmd('/summon minecraft:zombie 4.5 210 8.5 {Tags:["attr"],NoAI:1b,NoGravity:1b,Health:7.0f,'
'attributes:[{id:"minecraft:attack_damage",base:9.0d}]}'),
cmd('/data get entity @e[tag=attr,limit=1] Health'),
cmd('/attribute @e[tag=attr,limit=1] minecraft:attack_damage base get'),
cmd('/kill @e[tag=attr]'),
*setup('/kill @e[type=minecraft:armor_stand]'),
{'op': 'tick', 'n': 25},
cmd('/execute if entity @e[tag=h]'),
@@ -327,6 +340,31 @@ def riding_teleport():
'/tp @s 8.5 230 8.5 0 0')
def mob_riding():
"""Mobs mount and dismount mobs with /ride, NBT passengers included (#1520)."""
rider, vehicle = '@e[tag=ride_r,limit=1]', '@e[tag=ride_v,limit=1]'
return [
*setup('/summon minecraft:cow 4.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_v"]}',
'/summon minecraft:pig 6.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_r"]}'),
cmd(f'/ride {rider} dismount'),
cmd(f'/ride {rider} mount @s'),
cmd(f'/ride {rider} mount {rider}'),
cmd(f'/ride {rider} mount {vehicle}'),
cmd(f'/ride {rider} mount {vehicle}'),
cmd(f'/ride {vehicle} mount {rider}'),
cmd('/execute as @e[tag=ride_r] on vehicle run say carrying'),
cmd(f'/ride {rider} dismount'),
cmd(f'/data get entity {rider} Pos'),
cmd('/execute as @e[tag=ride_r] on vehicle run say still carrying'),
*setup('/kill @e[tag=ride_r]', '/kill @e[tag=ride_v]'),
*setup('/summon minecraft:cow 4.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_v"],'
'Passengers:[{id:"minecraft:pig",NoAI:1b,NoGravity:1b,Tags:["ride_r"]}]}'),
cmd(f'/ride {rider} dismount'),
cmd(f'/data get entity {rider} Pos'),
*setup('/kill @e[tag=ride_r]', '/kill @e[tag=ride_v]'),
]
def scores():
return [
cmd('/scoreboard objectives add harness dummy'),
@@ -1017,6 +1055,7 @@ def groups():
('blocks and border', world_blocks()),
('entities', entities()),
('riding teleport', riding_teleport()),
('mob riding', mob_riding()),
('scores, teams and bossbars', scores()),
('execute', execute()),
('levels', levels()),
+287
View File
@@ -0,0 +1,287 @@
#!/usr/bin/env python3
"""End-to-end check of Discord Rich Presence: real games talk to a fake Discord.
Each game gets its own fake Discord IPC server (a Unix socket in a scratch folder, pointed to by
HORIZON_DISCORD_IPC_DIR) that answers the handshake with READY and records every SET_ACTIVITY.
The game goes title -> world -> Nether -> quit through horizon-ctl, and the activities must say
"In the menus", "Singleplayer" in the Overworld, then the Nether, and be cleared on quit:
single single player on its server thread (the default)
in-frame single player ticked in the window's frame (--in-frame)
lan a host opens its world to LAN and a guest joins: the guest shows "Multiplayer",
the host "Hosting a world" with a party of 2 of 8 (lan-in-frame: the host in-frame)
setting off in horizon-extras.txt: nothing reaches Discord; the Horizon Settings switch
turns it on (the activity appears) and off (it is cleared)
late Discord starts after the game: found within the 15 s retry
python3 tools/discord_presence_e2e.py # all of them
python3 tools/discord_presence_e2e.py --check lan --bin-dir target/fast
macOS and Linux (Discord's Windows pipes aren't faked here). Games render offscreen, have no audio
and use scratch homes (lab.game_env). Needs the prepared resources in .local/horizon-client.
"""
import argparse
import json
import os
import shutil
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
try:
from . import lab
except ImportError:
import lab
ROOT = Path(__file__).resolve().parents[1]
HANDSHAKE, FRAME, CLOSE = 0, 1, 2
class FakeDiscord:
"""discord-ipc-0 in a scratch folder: READY on handshake, a reply to each command."""
def __init__(self):
# Short: Unix socket paths are limited to ~100 bytes.
self.dir = Path(tempfile.mkdtemp(prefix='hzdc-', dir='/tmp'))
self.server = None
self.activities = [] # (seconds since start, activity or None)
self.handshakes = []
self.started = time.time()
self.lock = threading.Lock()
def start(self):
"""Discord starts: its socket appears."""
self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.server.bind(str(self.dir / 'discord-ipc-0'))
self.server.listen()
threading.Thread(target=self.accept, daemon=True).start()
def accept(self):
while True:
try:
conn, _ = self.server.accept()
except OSError:
return
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
def serve(self, conn):
def read():
header = conn.recv(8, socket.MSG_WAITALL)
if len(header) < 8:
raise EOFError
op, length = struct.unpack('<II', header)
return op, json.loads(conn.recv(length, socket.MSG_WAITALL) or b'null')
def send(op, payload):
body = json.dumps(payload).encode()
conn.sendall(struct.pack('<II', op, len(body)) + body)
try:
while True:
op, msg = read()
if op == HANDSHAKE:
with self.lock:
self.handshakes.append(msg)
send(FRAME, {'cmd': 'DISPATCH', 'evt': 'READY', 'data': {'v': 1}})
elif op == FRAME and msg.get('cmd') == 'SET_ACTIVITY':
with self.lock:
self.activities.append((round(time.time() - self.started, 1), msg['args']['activity']))
send(FRAME, {'cmd': 'SET_ACTIVITY', 'nonce': msg['nonce'], 'data': msg['args']['activity']})
elif op == CLOSE:
return
except (EOFError, OSError, ValueError):
pass
finally:
conn.close()
def last(self):
with self.lock:
return self.activities[-1][1] if self.activities else 'nothing yet'
def wait(self, what, check, timeout=60):
"""Waits until the latest activity passes `check` (Discord's limit can hold one back 20 s)."""
deadline = time.time() + timeout
while time.time() < deadline:
if check(self.last()):
print(f' ok: {what}: {json.dumps(self.last())}')
return
time.sleep(0.25)
raise AssertionError(f'{what}: the last activity was {self.last()!r}; all: {self.activities}')
def close(self):
if self.server:
self.server.close()
shutil.rmtree(self.dir, ignore_errors=True)
def shows(details, state=None):
return lambda a: isinstance(a, dict) and a.get('details') == details and (state is None or a.get('state') == state)
class Game:
"""One game started by horizon-ctl in a scratch home, with its own fake Discord."""
def __init__(self, bins, name, args=(), extras=None, discord_running=True):
self.ctl = bins / 'horizon-ctl'
self.home = Path(tempfile.mkdtemp(prefix=f'hzdp-{name}-'))
if extras:
(self.home / 'horizon-extras.txt').write_text(extras)
self.socket = self.home / 'c.sock'
self.discord = FakeDiscord()
if discord_running:
self.discord.start()
extra = {'HORIZON_HOME': self.home, 'HORIZON_TELEMETRY_URL': 'off', 'HORIZON_DISCORD_IPC_DIR': self.discord.dir}
self.env = lab.game_env(**extra)
self.ctl_run('launch', '--offscreen', '--game', str(bins / 'horizon-client'), '--resources',
str(lab.RESOURCES.resolve()), *args)
def ctl_run(self, *words, timeout=600):
r = subprocess.run([str(self.ctl), '--socket', str(self.socket), *words], cwd=self.home, env=self.env,
capture_output=True, text=True, timeout=timeout)
out = r.stdout.strip().splitlines()
reply = json.loads(out[-1]) if out else {'error': r.stderr.strip()}
if r.returncode or 'error' in reply:
raise AssertionError(f'horizon-ctl {" ".join(words)}: exit {r.returncode}: {reply}')
return reply
def quit(self):
try:
self.ctl_run('quit', timeout=120)
except Exception as e: # the reply can be lost as the game exits
print(f' quit: {e}')
def close(self):
self.discord.close()
shutil.rmtree(self.home, ignore_errors=True)
def single(bins, args=()):
game = Game(bins, 'single', args=args)
d = game.discord
try:
d.wait('title screen', shows('In the menus'))
assert d.handshakes[0]['v'] == 1 and d.handshakes[0]['client_id'], d.handshakes
game.ctl_run('open', 'Presence', '5', 'creative')
game.ctl_run('wait-for', 'loaded', '--timeout', '300')
d.wait('in the world', shows('Singleplayer', 'In the Overworld'))
start = d.last()['timestamps']['start']
assert abs(start - time.time()) < 120 and 'party' not in d.last(), d.last()
game.ctl_run('command', 'execute in minecraft:the_nether run tp @s 0 80 0')
d.wait('in the Nether', shows('Singleplayer', 'In the Nether'))
assert d.last()['timestamps']['start'] == start, 'a dimension change restarted the clock'
text = json.dumps(d.activities)
assert 'Presence' not in text, f'the world name reached Discord: {text}'
game.quit()
d.wait('cleared on quit', lambda a: a is None)
finally:
game.close()
def lan(bins, host_args=()):
host = Game(bins, 'host', args=host_args)
guest = None
try:
host.ctl_run('open', 'Hosted', '5', 'creative')
host.ctl_run('wait-for', 'loaded', '--timeout', '300')
port = lab.free_port()
host.ctl_run('lan', 'open', str(port))
host.discord.wait('host, alone', lambda a: shows('Hosting a world')(a) and a['party']['size'] == [1, 8])
guest = Game(bins, 'guest')
guest.discord.wait('guest title screen', shows('In the menus'))
guest.ctl_run('connect', f'127.0.0.1:{port}', 'Guest')
guest.ctl_run('wait-for', 'loaded', '--timeout', '300')
guest.discord.wait('guest in the world', shows('Multiplayer', 'In the Overworld'))
assert '127.0.0.1' not in json.dumps(guest.discord.activities), guest.discord.activities
host.discord.wait('host with a guest', lambda a: shows('Hosting a world')(a) and a['party']['size'] == [2, 8])
guest.quit()
guest.discord.wait('guest cleared on quit', lambda a: a is None)
host.quit()
host.discord.wait('host cleared on quit', lambda a: a is None)
finally:
for g in (guest, host):
if g:
g.close()
def setting(bins):
"""Off in horizon-extras.txt: Discord never hears from the game. Turned on in Horizon Settings: the
activity appears; off again: it is cleared."""
game = Game(bins, 'setting', extras='discordPresence:false\n')
d = game.discord
try:
game.ctl_run('wait-for', 'screen', 'title')
time.sleep(3)
assert not d.handshakes and not d.activities, (d.handshakes, d.activities)
game.ctl_run('options', 'horizon')
switch = next(w for w in game.ctl_run('ui')['widgets'] if w.get('label', '').startswith('Discord Rich'))
assert switch['label'] == 'Discord Rich Presence: Off', switch
game.ctl_run('click', switch['id'])
d.wait('turned on', shows('In the menus'))
game.ctl_run('click', switch['id'])
d.wait('turned off', lambda a: a is None)
assert 'discordPresence:false' in (game.home / 'horizon-extras.txt').read_text()
print(' ok: saved off')
game.quit()
finally:
game.close()
def late(bins):
"""Discord started after the game: it is found at the next retry (every 15 s)."""
game = Game(bins, 'late', discord_running=False)
try:
game.ctl_run('wait-for', 'screen', 'title')
time.sleep(2)
game.discord.start()
started = time.time()
game.discord.wait('found Discord', shows('In the menus'), timeout=30)
print(f' ok: after {time.time() - started:.1f} s')
game.quit()
finally:
game.close()
CHECKS = {'single': single, 'in-frame': lambda b: single(b, ['--in-frame']), 'lan': lan,
'lan-in-frame': lambda b: lan(b, ['--in-frame']), 'setting': setting,
'late': late}
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--check', choices=[*CHECKS, 'all'], default='all')
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
args = parser.parse_args()
if sys.platform == 'win32':
sys.exit('the fake Discord is a Unix socket: macOS or Linux only')
if args.bin_dir:
bins = Path(args.bin_dir).resolve()
else:
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'],
cwd=ROOT, check=True)
meta = json.loads(subprocess.run(['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=ROOT,
capture_output=True, text=True, check=True).stdout)
bins = Path(meta['target_directory']) / 'fast'
if not (lab.RESOURCES / 'horizon-resources.json').exists():
sys.exit(f'no prepared resources in {lab.RESOURCES}')
results = {}
for name in CHECKS if args.check == 'all' else [args.check]:
print(f'[{name}]')
started = time.time()
try:
CHECKS[name](bins)
results[name] = True
print(f'[{name}] PASS in {time.time() - started:.0f} s')
except (AssertionError, KeyError, StopIteration, subprocess.TimeoutExpired) as e:
results[name] = False
print(f'[{name}] FAIL: {e}')
print(json.dumps(results))
sys.exit(0 if all(results.values()) else 1)
if __name__ == '__main__':
main()
+146
View File
@@ -6252,5 +6252,151 @@ CHECKS += ['crystals']
CHECK_FNS.update(crystals=check_crystals)
def check_crystal_blast(host, guest, out):
"""#1533: TNT removes a crystal without a blast; a punched crystal blasts once.
Both clients must see the surviving distant and invulnerable crystals."""
spots = apart(host, guest)
seen = {}
for label, player, other in (('host', host, guest), ('guest', guest, host)):
x, y, z = spots[label]
y += 32
player('command', command='gamemode creative')
for offset, cause in enumerate(('tnt', 'melee')):
# Leave survivors in separate arenas; the scratch world is discarded.
z = spots[label][2] + (0 if label == 'host' else 80) + offset * 40
case = f'{label}-{cause}'
host('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 25} {y - 1} {z + 5} minecraft:bedrock')
host('command', command=f'fill {x - 3} {y} {z - 3} {x + 25} {y + 4} {z + 5} minecraft:air')
positions = [[x + dx, y, z + dz] for dx, dz in ((2.5, 0.5), (12.5, 0.5), (22.5, 0.5), (4.5, 3.5))]
def remaining(game):
crystals = [p for p in game('status')['projectiles'] if p['kind'] == 'minecraft:end_crystal']
return [i for i, at in enumerate(positions)
if any(math.dist(p['position'], at) < 0.01 for p in crystals)]
for i, at in enumerate(positions):
host('command', command=f'summon minecraft:end_crystal {at[0]} {at[1]} {at[2]} {{Invulnerable:{1 if i == 3 else 0}b}}')
player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}')
other('command', command='gamemode creative')
other('command', command=f'tp @s {x + 0.5} {y} {z + 4.5}')
player('command', command='clear @s')
player.wait(20)
for game in (host, guest):
assert remaining(game) == [0, 1, 2, 3], f'{case}: crystals not tracked on {game.name}'
if cause == 'tnt':
player('command', command=f'summon minecraft:tnt {x + 0.5} {y} {z + 0.5} {{fuse:10s}}')
else:
player.raw('look-at', positions[0][0], y + 1, positions[0][2])
player.raw('mouse', 'left', 'click')
player.wait(80)
result = {game.name: remaining(game) for game in (host, guest)}
seen[case] = result
# TNT reaches the first crystal only. A direct crystal blast reaches
# the second too, but that crystal must not detonate the third.
expected = [1, 2, 3] if cause == 'tnt' else [2, 3]
assert all(ids == expected for ids in result.values()), f'{case}: expected {expected}, got {result}'
return seen
CHECKS += ['crystal_blast']
CHECK_FNS.update(crystal_blast=check_crystal_blast)
def check_boat_dismount_pose(host, guest, out):
"""Removing a boat detaches its mobs on the server and every observing client."""
x, y, z = map(math.floor, pos_of(host))
bx, bz = x + 3.5, z + 3.5
tag = 'boat_dismount_pose'
host('command', command='gamemode creative')
host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 8} {y - 1} {z + 8} minecraft:stone')
host('command', command=f'fill {x - 2} {y} {z - 2} {x + 8} {y + 4} {z + 8} minecraft:air')
host('command', command=f'summon minecraft:oak_boat {bx} {y} {bz} {{Tags:["{tag}"]}}')
for _ in range(2):
host('command', command=f'summon minecraft:husk {bx} {y} {bz} {{NoAI:1b,Tags:["{tag}"]}}')
host.wait(5)
try:
host.wait(20)
boat = next(o for o in host('status')['objects']
if o['kind'].endswith('oak_boat') and math.dist(o['position'], [bx, y, bz]) < 2)
riders = [m['id'] for m in host.raw('mobs', 64)['near']
if m['kind'] == 'minecraft:husk' and m['mount'] == boat['id']]
assert len(riders) == 2, f'the boat did not collect both husks: {riders}'
for game in (host, guest):
game.wait(10)
for rider in riders:
m = mob_seen(game, rider)
assert m and m['mount'] == boat['id'] and m['passenger'], f'{game.name} did not see seated husk {rider}: {m}'
game.raw('look-at', bx, y + 1, bz)
game.shot(out, 'boat-passengers-seated')
host('command', command=f'tp @s {bx - 3} {y} {bz} 0 0')
host.wait(5)
# Aim at the near rim, below the riders, so their boxes cannot
# intercept the creative player's one hit that destroys the boat.
host.raw('look-at', bx - 0.55, y + 0.1, bz)
host.raw('mouse', 'left', 'click')
seen = {}
for game in (host, guest):
game.wait(20)
assert all(o['id'] != boat['id'] for o in game('status')['objects']), f'{game.name} still sees the boat'
seen[game.name] = [mob_seen(game, rider) for rider in riders]
game.raw('look-at', bx, y + 1, bz)
game.shot(out, 'boat-passengers-dismounted')
for m in seen[game.name]:
assert m and m['mount'] is None and not m['passenger'], f'{game.name} still draws a removed boat\'s passenger: {m}'
return {name: [{k: m[k] for k in ('id', 'mount', 'passenger')} for m in mobs] for name, mobs in seen.items()}
finally:
host('command', command=f'kill @e[tag={tag}]')
CHECKS += ['boat-dismount-pose']
CHECK_FNS['boat-dismount-pose'] = check_boat_dismount_pose
def check_sprint_fov(host, guest, out):
"""Releasing Ctrl must preserve a sprint until W is released, then reset FOV.
PlayerInput reports keys; PlayerCommand starts/stops the sprint. Confusing
them clears the client's sprint flag while leaving its speed modifier on.
"""
seen = {}
for game in (host, guest):
game('command', command='gamemode creative')
game('command', command='effect clear @s')
game.raw('options-set', 'fovEffectScale', '1.0')
x, y, z = map(math.floor, pos_of(game))
game('command', command=f'fill {x - 2} {y} {z - 2} {x + 2} {y + 3} {z + 20} minecraft:air')
game('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 2} {y - 1} {z + 20} minecraft:stone')
game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0')
game.wait(20)
try:
game.raw('key', 'w', 'down')
game.raw('key', 'ctrl', 'down')
game.wait(10)
started = game('state')['player']
game.raw('key', 'ctrl', 'up')
game.wait(10)
released_ctrl = game('state')['player']
game.raw('key', 'w', 'up')
game.wait(20)
stopped = game('state')['player']
finally:
game.raw('key', 'ctrl', 'up')
game.raw('key', 'w', 'up')
seen[game.name] = states = {
label: {k: p[k] for k in ('sprinting', 'fov_modifier')}
for label, p in [('started', started), ('released_ctrl', released_ctrl), ('stopped', stopped)]
}
for label in ('started', 'released_ctrl'):
assert states[label]['sprinting'], f'{game.name} {label}: {states}'
assert abs(states[label]['fov_modifier'] - 1.15) < 0.002, f'{game.name} {label}: {states}'
assert not stopped['sprinting'], f'{game.name}: {states}'
assert abs(stopped['fov_modifier'] - 1.0) < 0.002, f'{game.name}: {states}'
return seen
CHECKS += ['sprint-fov']
CHECK_FNS['sprint-fov'] = check_sprint_fov
if __name__ == '__main__':
main()
+56 -13
View File
@@ -45,6 +45,11 @@ import subprocess
import sys
import time
try:
from . import parity_reach
except ImportError:
import parity_reach
ROOT = Path(__file__).resolve().parents[1]
LOCAL = ROOT / ".local"
STATE_DIR = LOCAL / "parity-runner"
@@ -652,6 +657,9 @@ def prebuild(artifacts, jobs):
LARGE_OUTPUT = 64 << 20
# Vanilla outputs above this are deleted after a pass too: rerunning those few oracles (12 harnesses on the Mac
# mini's runner) costs less than the 26 GB they held in every checkout; smaller ones stay for oracle reuse.
KEPT_ORACLE_OUTPUT = 256 << 20
OWN_DIRECTORIES = {"parity-target", "parity-runner", "rea", "logs", "gate"}
@@ -667,11 +675,12 @@ def clear_large_outputs(name, trace):
"""After a pass, delete the large files a harness regenerates on every run.
Harness outputs reach gigabytes and used to stay in every worktree. Vanilla
oracle outputs are kept, since reusing an oracle run needs them in place;
everything else large under the harness's .local directories is rebuilt on
its next run."""
oracle outputs under KEPT_ORACLE_OUTPUT are kept, since reusing an oracle
run needs them in place; everything else large under the harness's .local
directories (`<name>...` or `rust-<name>-parity`) is rebuilt on its next run."""
local = LOCAL.resolve()
keep = {os.path.realpath(line) for line in outputs_listing(name).read_text(encoding="utf-8").splitlines() if line}
own = name.split("#")[0].replace("_", "-")
directories = set()
for command in trace["commands"]:
for argument in command[1:]:
@@ -683,12 +692,13 @@ def clear_large_outputs(name, trace):
# Only the harness's own directory: another harness running beside it may be writing
# large files in a directory this one merely read (decorated_region compiles its oracle
# into chunk-generation-parity while chunk_generation writes its dumps there).
if top not in OWN_DIRECTORIES and top.startswith(name.replace("_", "-")):
if top not in OWN_DIRECTORIES and (top.startswith(own) or top == f"rust-{own}-parity"):
directories.add(local / top)
for directory in directories:
for file in (directory.rglob("*") if directory.is_dir() else []):
try:
if file.is_file() and not file.is_symlink() and file.stat().st_size >= LARGE_OUTPUT and str(file) not in keep:
size = file.stat().st_size if file.is_file() and not file.is_symlink() else 0
if size >= LARGE_OUTPUT and (str(file) not in keep or size > KEPT_ORACLE_OUTPUT):
file.unlink()
except OSError:
pass
@@ -823,8 +833,11 @@ class LocalExecutor:
environment.pop("PARITY_SHARD", None)
if shard:
environment["PARITY_SHARD"] = shard
# stdin from /dev/null: tools/parity_shim.py never reuses an oracle run that reads a pipe, and CI runners
# (and --worker's ssh) give the runner one, which kept oracle reuse off on CI.
process = subprocess.Popen([sys.executable, str(Path(__file__)), "--trace", str(trace), str(script)],
cwd=ROOT, env=environment, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
cwd=ROOT, env=environment, stdin=subprocess.DEVNULL, stdout=log,
stderr=subprocess.STDOUT, start_new_session=True)
self.running[name] = {"process": process, "started": time.monotonic(), "log": log, "expected": expected,
"slot": slot, "script": script}
return True
@@ -1224,20 +1237,44 @@ def changed_harnesses(found, records, ref):
return found_changed
def affected_harnesses(found, records, changed):
def affected_harnesses(found, records, changed, reach=True, base=None):
"""Harnesses the changed files can affect: their script or a recorded dependency (here, or in the shared
dependency lists) changed, a file every harness depends on changed, or nothing is recorded about them yet."""
dependency lists) changed, a file every harness depends on changed, or nothing is recorded about them yet.
With reach, a harness's workspace Rust sources count only if its probes can reach them (tools/parity_reach.py);
a harness whose probes can't be placed keeps them all. A changed file counts unless, compared with base (a
commit), only declarations of modules the harness doesn't reach changed (tools/parity_reach.py)."""
if changed & SHARED_INPUTS:
return set(found)
graph = None
if reach and any(path.startswith("crates/") for path in changed):
cache_path = STATE_DIR / "reach-cache.json"
try:
cache = json.loads(cache_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
cache = {}
graph = parity_reach.SourceGraph(ROOT, rust_code, cache)
affected = set()
for name, script in found.items():
dependencies = records.get(name, {}).get("dependencies")
record = records.get(name) or {}
dependencies = record.get("dependencies")
template = SHARED / "dependencies" / f"{name}.json"
if dependencies is None and template.exists():
dependencies = json.loads(template.read_text(encoding="utf-8")).get("dependencies")
if dependencies is None or Path(script).relative_to(ROOT).as_posix() in changed or \
any(path.split(KEEP)[0] in changed for path in dependencies):
record = json.loads(template.read_text(encoding="utf-8"))
dependencies = record.get("dependencies")
if dependencies is None or Path(script).relative_to(ROOT).as_posix() in changed:
affected.add(name)
continue
plain = {path.split(KEEP)[0] for path in dependencies}
if graph is not None and plain & changed:
narrowed = parity_reach.narrow(dependencies, recorded_artifacts(record), graph, changed)
if any(path.split(KEEP)[0] in changed and (children is None or parity_reach.declarations_changed(
ROOT, path.split(KEEP)[0], children, base, whole)) for path, (whole, children) in narrowed.items()):
affected.add(name)
elif plain & changed:
affected.add(name)
if graph is not None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
cache_path.write_text(json.dumps(graph.saved_cache()), encoding="utf-8")
return affected
@@ -1280,6 +1317,8 @@ def main():
parser.add_argument("--flake-rounds", type=int, default=3, help="runs required by --flake-check (default 3)")
parser.add_argument("--changed", metavar="REF", help="only harnesses the changes since the merge base with REF can "
"affect (and that have not passed with their current inputs): the pull-request check")
parser.add_argument("--by-crate", action="store_true", help="with --changed: count every Rust source a probe "
"links, not only those it can reach (tools/parity_reach.py)")
parser.add_argument("--changed-files", metavar="FILE", help="like --changed, for the changed paths listed in FILE, "
"one per line: for a copy without Git history (tools/pr_ready.py on another machine)")
args = parser.parse_args()
@@ -1316,7 +1355,11 @@ def main():
changed, since = changed_files(args.changed), f" since the merge base with {args.changed}"
if changed is None:
parser.error(f"no merge base with {args.changed}")
affected = affected_harnesses(found, records, changed)
base = None
if args.changed:
merge_base = subprocess.run(["git", "merge-base", "HEAD", args.changed], cwd=ROOT, capture_output=True, text=True)
base = merge_base.stdout.strip() or None
affected = affected_harnesses(found, records, changed, reach=not args.by_crate, base=base)
chosen = [name for name in found if name in affected and stale(name, state, hasher, environment)]
print(f"{len(changed)} files changed{since}: {len(affected)} harnesses "
f"depend on them, {len(chosen)} without a pass for their current inputs.", flush=True)
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""parity-main (.github/workflows/parity-main.yml): the vanilla harnesses run on main, a batch of merges at a time.
python3 tools/parity_main.py base # the commit this run checks from: main's last green parity-main
python3 tools/parity_main.py bisect BASE # after a failure: the first merge since BASE that broke a harness
`base` prints the newest commit on main whose parity-main run passed and that HEAD contains, else HEAD's first parent,
so a run tests every merge since the last green one (`tools/parity.py --changed <base>`), however many landed while
the previous run went on. `bisect` reads the harnesses that failed (.local/parity-runner/last-run.json), checks out
the first-parent merges between BASE and HEAD by halves and runs only those harnesses, then names the first merge they
fail on (written to $GITHUB_STEP_SUMMARY and, with --comment, on its pull request). HEAD is checked out again at the end.
"""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon")
LAST_RUN = ROOT / ".local" / "parity-runner" / "last-run.json"
def git(*arguments, check=True):
result = subprocess.run(["git", *arguments], cwd=ROOT, capture_output=True, text=True)
if check and result.returncode:
sys.exit(f"git {' '.join(arguments)}: {result.stderr.strip()}")
return result
def green_runs():
"""Head commits of main's passing parity-main runs, newest first."""
result = subprocess.run(["gh", "run", "list", "--repo", REPO, "--workflow", "parity-main", "--branch", "main",
"--status", "success", "--limit", "30", "--json", "headSha"], capture_output=True, text=True)
if result.returncode:
print(f"note: no parity-main history ({result.stderr.strip()})", file=sys.stderr)
return []
return [run["headSha"] for run in json.loads(result.stdout or "[]")]
def base(head="HEAD", runs=None):
for sha in green_runs() if runs is None else runs:
if git("merge-base", "--is-ancestor", sha, head, check=False).returncode == 0:
return git("rev-parse", sha).stdout.strip()
return git("rev-parse", f"{head}^1").stdout.strip()
def first_bad(commits, fails):
"""The first of commits (oldest first, the last known to fail; the one before them known to pass) where fails()."""
good, bad = -1, len(commits) - 1
while bad - good > 1:
middle = (good + bad) // 2
if fails(commits[middle]):
bad = middle
else:
good = middle
return commits[bad]
def harness_exists(name):
return (ROOT / "tools" / f"test_{name.split('#')[0]}_parity.py").exists()
def run_harnesses(names, timeout):
"""Whether any of the harnesses fails at the checked-out commit (those it doesn't have yet can't)."""
present = [name for name in names if harness_exists(name)]
if not present:
return False
return subprocess.run([sys.executable, "tools/parity.py", *present, "--timeout", str(timeout)], cwd=ROOT).returncode != 0
def bisect(since, timeout, comment):
failed = []
if LAST_RUN.exists():
failed = json.loads(LAST_RUN.read_text(encoding="utf-8")).get("failed") or []
if not failed:
print("No failed harness recorded: nothing to bisect.")
return 0
head = git("rev-parse", "HEAD").stdout.strip()
commits = git("rev-list", "--first-parent", "--reverse", f"{since}..{head}").stdout.split()
if not commits:
print("No merge since the base.")
return 0
def fails(commit):
print(f"--- {commit[:9]} {git('log', '-1', '--format=%s', commit).stdout.strip()}", flush=True)
git("checkout", "-q", "--detach", commit)
return run_harnesses(failed, timeout)
try:
culprit = first_bad(commits, fails) if len(commits) > 1 else commits[0]
finally:
git("checkout", "-q", "--detach", head)
subject = git("log", "-1", "--format=%s", culprit).stdout.strip()
number = re.search(r"Merge pull request #(\d+)", subject)
line = (f"parity-main: {', '.join(failed)} first fail at {culprit[:9]} ({subject}), "
f"of {len(commits)} merges since {since[:9]}.")
print(line)
if os.environ.get("GITHUB_STEP_SUMMARY"):
with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary:
summary.write(f"### {line}\n")
if comment and number:
url = f"{os.environ.get('GITHUB_SERVER_URL', 'https://github.com')}/{REPO}/actions/runs/{os.environ.get('GITHUB_RUN_ID', '')}"
body = (f"🤖 Agent: parity-main found that this merge breaks {', '.join(f'`{name}`' for name in failed)} on main "
f"(bisected over {len(commits)} merges: {url}). Releases wait until parity-main passes again.")
subprocess.run(["gh", "pr", "comment", number.group(1), "--repo", REPO, "--body", body])
return 0
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("base")
bisecting = commands.add_parser("bisect")
bisecting.add_argument("since", help="the last commit known to pass (the run's base)")
bisecting.add_argument("--timeout", type=int, default=2400, help="seconds per harness")
bisecting.add_argument("--comment", action="store_true", help="comment on the breaking merge's pull request")
args = parser.parse_args()
if args.command == "base":
print(base())
return 0
return bisect(args.since, args.timeout, args.comment)
if __name__ == "__main__":
sys.exit(main())
+768
View File
@@ -0,0 +1,768 @@
"""Which of a harness's Rust sources its probes can reach, for `parity.py --changed`.
Cargo's dep-info names every source file of every crate a probe links, so a change anywhere in horizon-client
selected every harness whose probe links horizon-client. This module narrows a harness's recorded dependencies to
the files holding an item its entry points (the probe modules it ran, the binaries it built) can reach, over a graph
of the workspace's current sources whose nodes are items:
- everything in an entry is reached, and so is everything in a Rust file the module tree doesn't place (an
`include!`d source);
- a module is open when it is a crate root, holds reached code, or is named in a path (`name::`, `use ...name`) by
reached code while its parent is open;
- a free item (fn, struct, enum, union, trait, type, const, static, an item-level macro call's items) is reached when
reached code in its own module or below it mentions its name, or when its module is open and reached code names
it in a path or an import, or when its module is glob-imported (`use m::*`) and its name is mentioned;
- an inherent impl's methods and constants are reached one by one, by name, once their type is; a trait impl once
its trait and its type are (a std or outside name always is, a generic parameter needs nothing); a macro once
invoked; a `pub use` like a free item named by everything it imports;
- "a crate's reached code" covers the crates it names (`horizon_world::`), directly or through one that does, and
code under `#[cfg(test)]` or `#[test]` is left out (probes are never test builds).
Names match by spelling, so a file can be kept for a name it never meant: the graph only over-approximates. A
reached file's parent modules count through their `mod` declarations of it (parity.py compares those with the merge
base). Everything that isn't a workspace Rust source stays a dependency, except a crate's non-Rust files (shaders,
assets, fonts) that only unreached sources name; a dependency that no longer exists counts as changed, and Rust files
a change adds take part.
"""
import hashlib
from pathlib import Path, PurePosixPath
import re
import subprocess
IDENT = r"[A-Za-z_]\w*"
WORD = re.compile(rf"\b({IDENT})\b")
MOD_DECLARATION = re.compile(rf"\bmod\s+({IDENT})\s*;")
INLINE_MOD = re.compile(rf"\bmod\s+({IDENT})\s*\{{")
PATH_ATTRIBUTE = re.compile(r'#\[\s*path\s*=\s*"([^"]+)"\s*\]\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*;$')
BRACE = re.compile(r"[{}]")
TEST_ONLY = re.compile(r"#\[\s*(?:cfg\s*\(\s*test\s*\)|test)\s*\]")
TEST_MODULE = re.compile(r"#\[\s*cfg\s*\(\s*test\s*\)\s*\]\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*;$")
SPLIT = re.compile(r"[{}()\[\];]")
ITEM = re.compile(rf"(?:pub(?:\s*\([^)]*\))?\s+)?(?:(?:unsafe|async|const|extern|default|auto)\s+)*"
rf"(fn|struct|enum|union|trait|type|const|static|impl|mod|use|macro_rules\s*!|extern\s+crate)"
rf"(?!\w)\s*(?:mut\s+)?({IDENT})?")
PATH_BEFORE = re.compile(rf"\b({IDENT})\s*::")
PATH_AFTER = re.compile(rf"::\s*({IDENT})")
MACRO_USE = re.compile(rf"\b({IDENT})\s*!\s*[(\[{{]")
MACRO_CALL = re.compile(rf"({IDENT}(?:\s*::\s*{IDENT})*)\s*!")
DEFINED_INSIDE = re.compile(rf"\b(?:fn|struct|enum|union|trait|type|const|static)\s+({IDENT})")
NESTED_IMPL = re.compile(r"^[ \t]*(?:unsafe\s+)?impl\b([^{;]*)\{", re.MULTILINE)
QUALIFIED = re.compile(rf"{IDENT}(?:\s*::\s*{IDENT})*")
GLOB_IMPORT = re.compile(r"\buse\s[^;]*::\s*\*")
# File names a source may name in a literal (include_str!, include_bytes!, a path it reads). A file of another kind
# is never "named", so it always counts.
FILE_NAME = re.compile(r"[\w-]+\.(?:wgsl|glsl|json|png|ttf|otf|svg|txt|toml|ogg|wav|nbt|bin|dat|csv|mcmeta|wit|wasm)\b")
TYPE_KINDS = {"struct", "enum", "union", "trait", "type", "macro_call"}
# Names an impl header can take from outside the workspace: std's prelude and primitive types, and the std and serde
# traits a glob import may bring. A glob-imported name outside this list is taken to be the workspace's.
STD_NAMES = {"Display", "Error", "Read", "Write", "Seek", "BufRead", "Deref", "DerefMut", "Index", "IndexMut", "Add",
"Sub", "Mul", "Div", "Rem", "Neg", "Not", "BitAnd", "BitOr", "BitXor", "Shl", "Shr", "AddAssign",
"SubAssign", "MulAssign", "DivAssign", "RemAssign", "BitAndAssign", "BitOrAssign", "BitXorAssign",
"Borrow", "BorrowMut", "Future", "Any", "FromStr", "Hasher", "BuildHasher", "Formatter", "Ordering",
"Serialize", "Deserialize", "Serializer", "Deserializer", "Visitor", "Termination", "Sum", "Product",
"Wake", "Cow", "Rc", "Arc", "Mutex", "RwLock", "Cell", "RefCell", "HashMap", "HashSet", "BTreeMap",
"BTreeSet", "VecDeque"}
PRELUDE = {"Option", "Some", "None", "Result", "Ok", "Err", "Vec", "String", "Box", "ToString", "ToOwned", "Clone",
"Copy", "Send", "Sync", "Sized", "Unpin", "Drop", "Fn", "FnMut", "FnOnce", "From", "Into", "TryFrom",
"TryInto", "AsRef", "AsMut", "Default", "Eq", "PartialEq", "Ord", "PartialOrd", "Iterator", "Extend",
"IntoIterator", "DoubleEndedIterator", "ExactSizeIterator", "FromIterator", "Debug", "Hash",
"bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128",
"isize", "f32", "f64"}
STD_NAMES |= PRELUDE
KEYWORDS = {"crate", "self", "super", "Self", "pub", "in", "as", "use", "for", "where", "dyn", "mut", "const", "fn",
"unsafe", "impl", "std", "core", "alloc", "let", "if", "else", "match", "return", "struct", "enum", "mod",
"type", "static", "trait", "true", "false", "loop", "while", "move", "ref", "break", "continue", "async",
"await", "extern", "union"}
def segments(code, start, end):
"""The item-level pieces of code[start:end]: each ends at a `;` or a `}` outside any bracket."""
found, begin, depth = [], start, 0
for match in SPLIT.finditer(code, start, end):
character = match.group()
if character in "{([":
depth += 1
elif character in "})]":
depth -= 1
if character == "}" and depth == 0:
found.append((begin, match.end()))
begin = match.end()
elif depth == 0:
found.append((begin, match.end()))
begin = match.end()
if code[begin:end].strip():
found.append((begin, end))
return found
def skip_attributes(code, index, end):
"""The offset of the first non-space character after the attributes (`#[...]`, `#![...]`) starting at index."""
while True:
while index < end and code[index].isspace():
index += 1
if not code.startswith("#", index) or not re.match(r"#!?\[", code[index:index + 3]):
return index
depth = 0
for position in range(code.index("[", index), end):
depth += {"[": 1, "]": -1}.get(code[position], 0)
if depth == 0:
index = position + 1
break
else:
return end
def body_of(code, start, end):
"""The range inside an item's outermost `{ }` block, or None."""
opening = code.find("{", start, end)
closing = code.rfind("}", start, end)
return (opening + 1, closing) if 0 <= opening < closing else None
def words(text):
return set(WORD.findall(text)) - KEYWORDS
def qualified_words(text):
"""Names a piece of code reaches through a path (`a::b`: b), the way items of other modules are named."""
return set(PATH_AFTER.findall(text)) - KEYWORDS
def path_words(text):
"""Names a piece of code uses as path segments (`a::`, `::b`), where module names appear."""
return set(PATH_BEFORE.findall(text)) | set(PATH_AFTER.findall(text))
def parse_items(code, start, end, items):
"""Append the items of code[start:end] (a file or an inline module's body) to items, as dicts."""
for begin, finish in segments(code, start, end):
head = skip_attributes(code, begin, finish)
text = code[head:finish]
if not text.strip(" \n\t;") or TEST_ONLY.search(code[begin:head]):
continue # compiled into tests only, never into a probe
match = ITEM.match(text)
kind = re.sub(r"\s+", "", match.group(1)) if match else None
name = match.group(2) if match else None
if kind == "mod":
body = body_of(code, head, finish)
if body:
parse_items(code, body[0], body[1], items)
continue
if kind in ("externcrate", None) and not MACRO_CALL.match(text):
if kind is None:
items.append({"kind": "glue", "mentions": sorted(words(text)), "paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))})
continue
if kind is None: # an item-level macro call: it may define items
items.append({"kind": "macro_call", "names": sorted(set(DEFINED_INSIDE.findall(text))),
"macro": MACRO_CALL.match(text).group(1).split("::")[-1].strip(),
"mentions": sorted(words(text)), "paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))})
elif kind == "use":
head_word = re.match(rf"\s*(?:::\s*)?({IDENT})", text[match.end(1):])
items.append({"kind": "use", "public": text.startswith("pub"), "names": sorted(words(text)),
"head": head_word.group(1) if head_word else "", "glob": bool(re.search(r"::\s*\*", text)),
"mentions": sorted(words(text)), "paths": sorted(words(text)), "qualified": sorted(words(text)),
"invokes": []})
elif kind == "impl":
body = body_of(code, head, finish)
subject = code[head + match.end(1) - match.start(): body[0] - 1 if body else finish]
inherent = not re.search(r"\bfor\b", impl_subject(subject)[1])
if inherent and body:
members = []
for member_begin, member_end in segments(code, body[0], body[1]):
member = code[skip_attributes(code, member_begin, member_end):member_end]
found = ITEM.match(member)
members.append({"name": found.group(2) if found else None, "mentions": sorted(words(member)),
"paths": sorted(path_words(member)), "qualified": sorted(qualified_words(member)), "invokes": sorted(set(MACRO_USE.findall(member)))})
items.append({"kind": "impl", "subject": subject, "inherent": True, "members": members,
"mentions": sorted(words(subject)), "paths": sorted(path_words(subject)), "qualified": sorted(qualified_words(subject)), "invokes": sorted(set(MACRO_USE.findall(subject)))})
else:
items.append({"kind": "impl", "subject": subject, "inherent": False, "mentions": sorted(words(text)),
"paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))})
else:
kind = "macro" if kind.startswith("macro_rules") else kind
items.append({"kind": kind, "names": [name] if name else [], "mentions": sorted(words(text)),
"defines": sorted(set(DEFINED_INSIDE.findall(text))) if kind == "macro" else [],
"paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))})
if kind in ("fn", "const", "static"):
# An impl inside a function body still holds for the whole program.
for header in NESTED_IMPL.findall(text):
items.append({"kind": "impl", "subject": header, "inherent": False,
"mentions": sorted(words(text)), "paths": sorted(path_words(text)), "qualified": sorted(qualified_words(text)), "invokes": sorted(set(MACRO_USE.findall(text)))})
def crate_roots(crate_dir):
"""A crate's root files: its library, binaries and examples."""
roots = [crate_dir / "src" / "lib.rs", crate_dir / "src" / "main.rs"]
for folder in (crate_dir / "src" / "bin", crate_dir / "examples"):
if folder.is_dir():
roots += sorted(folder.glob("*.rs")) + sorted(folder.glob("*/main.rs"))
return [root for root in roots if root.is_file()]
class SourceGraph:
"""The workspace's Rust sources, parsed once: what each file names, defines and declares."""
def __init__(self, root, rust_code, cache=None):
"""cache: a dict of earlier parses by content digest, which the graph reuses and adds to (parity.py keeps it
in .local/parity-runner/reach-cache.json)."""
self.root = Path(root)
self.rust_code = rust_code
self.cache = {} if cache is None else cache
self.used = set()
self.files = {}
self.parent = {} # module file -> the file declaring it
self.module_name = {}
self.roots = set()
self.target_cache = {}
self.workspace_heads = None
self.test_only = set() # modules compiled into tests only
self.tables = None
self.root_of = {} # source -> the root of its target (lib.rs, a bin's or an example's main file)
self.results = {} # (entries, universe) -> reachable files
for manifest in sorted((self.root / "crates").glob("*/Cargo.toml")):
for crate_root in crate_roots(manifest.parent):
path = self.relative(crate_root)
self.roots.add(path)
self.root_of[path] = path
self.place(path, crate_root.parent, set())
def entries(self, artifacts, rust):
"""The root files of the probes and binaries a harness built (its record's artifacts), among its Rust
dependencies: for a crate's probe binary, the probe modules it ran (parity.only_probes_run kept only those).
None when an artifact can't be placed."""
found = set()
for kind, name, *rest in artifacts:
selection = rest[1] if len(rest) > 1 else []
packages = [value for flag, value in zip(selection, selection[1:]) if flag == "-p"] or \
[manifest.parent.name for manifest in sorted((self.root / "crates").glob("*/Cargo.toml"))]
roots = set()
for package in packages:
crate = self.root / "crates" / package
targets = self.targets(crate)
if kind in ("example", "examples"):
candidates = [path for target, (target_kind, path) in targets.items()
if target_kind == "example" and (not name or target == name)]
else:
candidates = [path for target, (target_kind, path) in targets.items()
if target_kind == "bin" and (not name or target == name)]
for path in candidates:
if path.endswith("/examples/probe/main.rs"):
# The probes it ran, and the dispatch and support modules they use (only_probes_run kept
# those); the binary's root, which only declares them, so their own submodules are placed.
folder = path.removesuffix("main.rs")
roots |= {dependency for dependency in rust if dependency.startswith(folder)
and "/" not in dependency.removeprefix(folder).removeprefix("support/")}
if roots:
roots.add(path)
elif path in rust:
roots.add(path)
if not roots:
return None
found |= roots
return found or None
def targets(self, crate):
"""A crate's bins and examples: {target name: (kind, root file)}, from its Cargo.toml and Cargo's defaults."""
if crate in self.target_cache:
return self.target_cache[crate]
found = {}
manifest = (crate / "Cargo.toml").read_text(encoding="utf-8") if (crate / "Cargo.toml").is_file() else ""
package = re.search(r'^\[package\][^\[]*?^name\s*=\s*"([^"]+)"', manifest, re.MULTILINE | re.DOTALL)
if (crate / "src" / "main.rs").is_file() and package:
found[package.group(1)] = ("bin", self.relative(crate / "src" / "main.rs"))
for kind, folder in (("bin", crate / "src" / "bin"), ("example", crate / "examples")):
for path in sorted(folder.glob("*.rs")) + sorted(folder.glob("*/main.rs")):
found[path.stem if path.name != "main.rs" else path.parent.name] = (kind, self.relative(path))
for kind, table in re.findall(r"^\[\[(bin|example)\]\]([^\[]*)", manifest, re.MULTILINE):
name = re.search(r'^name\s*=\s*"([^"]+)"', table, re.MULTILINE)
path = re.search(r'^path\s*=\s*"([^"]+)"', table, re.MULTILINE)
if name and path and (crate / path.group(1)).is_file():
found[name.group(1)] = (kind, self.relative(crate / path.group(1)))
self.target_cache[crate] = found
return found
def target(self, path):
"""The Cargo target a source belongs to: the root file of the library, bin or example whose module tree
holds it (a file nothing places is its own)."""
return self.root_of.get(path, path)
def is_library(self, path):
return self.target(path).endswith("/src/lib.rs")
def relative(self, path):
return Path(path).resolve().relative_to(self.root.resolve()).as_posix()
def place(self, path, module_dir, seen):
"""Walk the module tree from a file: record each declared module's file, parent and name."""
if path in seen:
return
seen.add(path)
parsed = self.parse(path)
if parsed is None:
return
for name, nesting, attribute, test in parsed["declarations"]:
if attribute is not None:
if nesting:
continue # a #[path] inside an inline module: unplaced, so always kept
candidates = [(self.root / path).parent / attribute]
else:
folder = module_dir.joinpath(*nesting)
candidates = [folder / f"{name}.rs", folder / name / "mod.rs"]
for candidate in candidates:
if candidate.is_file():
child = self.relative(candidate)
self.parent.setdefault(child, path)
self.module_name.setdefault(child, name)
self.root_of.setdefault(child, self.root_of[path])
if test or path in self.test_only:
self.test_only.add(child)
child_dir = candidate.parent if candidate.name == "mod.rs" or attribute is not None \
else candidate.parent / candidate.stem
self.place(child, child_dir, seen)
break
def parse(self, path):
if path in self.files:
return self.files[path]
try:
data = (self.root / path).read_bytes()
except OSError:
self.files[path] = None
return None
digest = hashlib.sha256(data).hexdigest()
self.used.add(digest)
if digest in self.cache:
self.files[path] = parsed = self.cache[digest]
return parsed
raw = data.decode("utf-8", errors="replace")
code = self.rust_code(raw) # same length as raw: literals and comments blanked
opening = {match.end() - 1: match.group(1) for match in INLINE_MOD.finditer(code)}
events = sorted([(match.start(), match) for match in BRACE.finditer(code)]
+ [(match.start(), match) for match in MOD_DECLARATION.finditer(code)], key=lambda event: event[0])
declarations, stack, depth = [], [], 0
for index, match in events:
if match.group() == "{":
depth += 1
if index in opening:
stack.append((opening[index], depth))
elif match.group() == "}":
if stack and stack[-1][1] == depth:
stack.pop()
depth -= 1
else:
window = " ".join(raw[max(0, index - 300):match.end()].split())
attribute = PATH_ATTRIBUTE.search(window)
declarations.append([match.group(1), [name for name, _ in stack], attribute.group(1) if attribute else None,
bool(TEST_MODULE.search(window))])
items = []
parse_items(code, 0, len(code), items)
self.files[path] = parsed = {
"declarations": declarations,
"items": items,
"glob": bool(GLOB_IMPORT.search(code)),
"file_names": sorted(set(FILE_NAME.findall(raw))),
}
self.cache[digest] = parsed
return parsed
def saved_cache(self):
"""The parses of the files this graph read, to keep for the next run."""
return {digest: self.cache[digest] for digest in self.used if digest in self.cache}
def requirement(self, path, item):
"""For an impl: for its trait and for its type, [names the file defines, other workspace names], one of
which must be a reached type or trait (of this file, of a crate it sees) before the impl can matter; both
empty: nothing of the workspace is needed. A name is the workspace's when the path naming it starts in the
workspace, or the file defines it, imports it from the workspace or may glob-import it; otherwise (std's,
another crate's, the prelude's) it needs nothing."""
if "requires" in item:
return item["requires"]
if self.workspace_heads is None:
self.workspace_heads = {"crate", "self", "super"} | set(self.module_name.values()) | {
manifest.parent.name.replace("-", "_") for manifest in (self.root / "crates").glob("*/Cargo.toml")}
parsed = self.parse(path)
defined = {name for other in parsed["items"] for name in other.get("names", ()) if other["kind"] != "use"}
workspace_imports = {name for other in parsed["items"] if other["kind"] == "use"
and other["head"] in self.workspace_heads for name in other["names"]}
parameters, subject = impl_subject(item["subject"])
parts = []
for part in re.split(r"\bfor\b", subject, maxsplit=1):
names, own = set(), set()
for match in QUALIFIED.finditer(part):
segments_ = [segment.strip() for segment in match.group().split("::")]
name = segments_[-1]
if name in parameters or name in KEYWORDS:
continue
if len(segments_) > 1:
if segments_[0] in self.workspace_heads:
names.add(name)
elif name in defined:
own.add(name)
elif name in workspace_imports or (parsed["glob"] and name not in STD_NAMES):
names.add(name)
parts.append([sorted(own), sorted(names)])
item["requires"] = parts
return parts
def index(self):
"""Lookup tables over every placed source, built once: which crates each crate sees, the nodes (items, an
inherent impl's members) by the names they define and the types they need, the modules by name."""
if self.tables is not None:
return self.tables
idents = {manifest.parent.name.replace("-", "_"): manifest.parent.name
for manifest in (self.root / "crates").glob("*/Cargo.toml")}
paths = [path for path in self.files if self.files[path] is not None and path not in self.test_only]
sees = {}
for path in paths:
named = {word for item in self.files[path]["items"] for word in item["mentions"]} & idents.keys()
sees.setdefault(crate_of(path), {crate_of(path)}).update(idents[name] for name in named)
changed = True
while changed:
changed = False
for crate, seen in sees.items():
wider = set().union(*(sees.get(other, {other}) for other in seen))
if not wider <= seen:
seen |= wider
changed = True
seen_by = {} # crate -> the crates that see it
for crate, seen in sees.items():
for other in seen:
seen_by.setdefault(other, set()).add(crate)
# What a call of a workspace macro defines: what its definition's body defines.
expands = {}
for path in paths:
for item in self.files[path]["items"]:
if item["kind"] == "macro":
for name in item["names"]:
expands.setdefault(name, set()).update(item["defines"])
names_of, by_name, by_file_name, by_type, by_module, children, seeds = {}, {}, {}, {}, {}, {}, []
for path in paths:
crate = crate_of(path)
if path in self.module_name:
by_module.setdefault((crate, self.module_name[path]), []).append(path)
children.setdefault(self.parent[path], []).append(path)
for index, item in enumerate(self.files[path]["items"]):
node = (path, index, None)
names = set(item.get("names", ()))
if item["kind"] == "macro_call":
names |= expands.get(item["macro"], set())
names_of[node] = names
if item["kind"] == "glue":
seeds.append(node)
elif item["kind"] == "macro_call" and not names:
# A macro call defining nothing by name may still expand to impls: it counts once a type or
# trait it mentions is reached.
for name in item["mentions"]:
by_type.setdefault(name, []).append(node)
elif item["kind"] == "impl":
required = {name for own, foreign in self.requirement(path, item) for name in own + foreign}
members = [(path, index, member) for member in range(len(item["members"]))] if item["inherent"] else []
for member_node in members:
name = item["members"][member_node[2]]["name"]
names_of[member_node] = set()
if name:
by_name.setdefault(name, []).append(member_node)
for name in required:
for other in [node] + members:
by_type.setdefault(name, []).append(other)
if not required:
seeds.append(node)
seeds += [member_node for member_node in members if not item["members"][member_node[2]]["name"]]
else:
for name in names:
by_name.setdefault(name, []).append(node)
by_file_name.setdefault((path, name), []).append(node)
self.tables = dict(idents=idents, sees=sees, seen_by=seen_by, names_of=names_of, by_name=by_name,
by_file_name=by_file_name, by_type=by_type, by_module=by_module, children=children,
seeds=seeds, node_sets={})
return self.tables
def reachable(self, entries, universe, reasons=None):
"""The files of universe (workspace Rust sources) holding an item reachable from entries (by the rules in
this module's doc), and the entries. reasons, a dict, gets why each file was reached (for debugging)."""
# Searching every source of the crates involved (not only those Cargo listed) only adds reach, and lets
# harnesses with the same entries (the game binary's) share one search.
crates = frozenset(crate_of(path) for path in universe)
key = (frozenset(entries), crates)
if reasons is None and key in self.results:
return self.results[key] & set(universe)
everything = {path for path in self.files if crate_of(path) in crates} | set(universe)
files = self.search(entries, everything, reasons)
self.results[key] = files
return files & set(universe)
def search(self, entries, universe, reasons):
targets = {self.target(path) for path in entries}
universe = {path for path in universe if (self.is_library(path) or self.target(path) in targets)
and path not in self.test_only}
tables = self.index()
idents, sees, seen_by, names_of = tables["idents"], tables["sees"], tables["seen_by"], tables["names_of"]
node_sets = tables["node_sets"]
by_name, by_file_name, by_type = tables["by_name"], tables["by_file_name"], tables["by_type"]
by_module, children = tables["by_module"], tables["children"]
seeds = [node for node in tables["seeds"] if node[0] in universe]
for path in universe:
if (path in entries or (path not in self.parent and path not in self.roots)) and self.parse(path):
seeds += [(path, index, None) for index in range(len(self.parse(path)["items"]))]
def names(node):
return names_of.get(node, set())
def sets_of(node, item):
"""A node's mentions, path words, qualified names and macro calls, as sets (parses keep lists)."""
if node not in node_sets:
source = item["members"][node[2]] if node[2] is not None else item
node_sets[node] = {key: set(source.get(key, ())) for key in ("mentions", "paths", "qualified", "invokes")}
return node_sets[node]
def item_of(node):
return self.parse(node[0])["items"][node[1]]
reached, opened, globbed, files, queue = set(), set(), set(), set(), []
# name -> the crates whose reached code mentions it plainly, names it in a path or an import, invokes it.
mentioned, qualified, invoked = {}, {}, {}
done = {"mentions": {}, "qualified": {}, "invokes": {}, "paths": {}} # crate -> names already handled
path_names, types = {}, {} # by crate
local = {} # file -> plain mentions by reached code in it or below it (child modules may `use super::*`)
local_types = {} # file -> its reached types and traits
def heard(table, name, crate):
"""Whether a crate that can see crate's items has name in table."""
sources = table.get(name)
return bool(sources) and not sources.isdisjoint(seen_by.get(crate, {crate}))
def ready(node):
path, index, member = node
item = item_of(node)
crate = crate_of(path)
if item["kind"] == "impl":
visible = visible_types(crate)
here = local_types.get(path, set())
if not all((not own and not foreign) or here.intersection(own) or visible.intersection(foreign)
for own, foreign in self.requirement(path, item)):
return False
name = item["members"][member]["name"] if member is not None else None
return name is None or heard(mentioned, name, crate) # a method: called by its name
if item["kind"] == "macro_call" and not names(node):
return not visible_types(crate).isdisjoint(item["mentions"])
names_ = names(node)
if item["kind"] == "macro":
return any(heard(invoked, name, crate) for name in names_)
if item["kind"] == "use" and item["glob"]:
return path in opened
nearby = local.get(path, ())
if any(name in nearby for name in names_):
return True # named in its own module, or below it
if item["kind"] == "use" and not item["public"]:
return False
if path in opened and any(heard(qualified, name, crate) for name in names_):
return True # named through a path, or imported
return path in globbed and any(heard(mentioned, name, crate) for name in names_)
visible_cache = {}
def visible_types(crate):
"""The reached types and traits of the crates a crate sees (cached until a type is reached)."""
if crate not in visible_cache:
visible_cache[crate] = set().union(*(types.get(other, set()) for other in sees.get(crate, {crate})))
return visible_cache[crate]
def wake(nodes, why):
for other in nodes:
if other not in reached and other[0] in universe and ready(other):
reach(other, why)
def open_module(path, why):
pending = [path]
while pending:
current = pending.pop()
if current in opened:
continue
opened.add(current)
crate = crate_of(current)
pending += [child for child in children.get(current, ())
if child in universe and self.module_name[child] in path_names.get(crate, ())]
parsed = self.parse(current)
wake([(current, index, None) for index, item in enumerate(parsed["items"] if parsed else ())
if item["kind"] != "impl"], f"{current} opened ({why})")
def reach(node, why):
if node in reached:
return
reached.add(node)
queue.append(node)
path, _, member = node
item = item_of(node)
if (item["kind"] == "use" and not item["public"]) or (item["kind"] == "impl" and item["inherent"] and member is None):
return
if path not in files:
files.add(path)
if reasons is not None:
reasons[path] = why
for path in universe:
if path.endswith("/src/lib.rs") or path in entries or path not in self.parent:
open_module(path, "crate root or entry")
for node in seeds:
reach(node, "entry" if node[0] in entries else "always counted")
for path in entries & universe:
files.add(path)
if reasons is not None:
reasons.setdefault(path, "entry")
while queue:
node = queue.pop()
path, index, member = node
item = item_of(node)
crate = crate_of(path)
label = (item.get("names") or [item["kind"]])[0] if member is None else item["members"][member]["name"]
source = sets_of(node, item)
why = f"{path} ({label})"
# Plain mentions reach items of this file and of the modules above it.
ancestor, new = path, source["mentions"]
while ancestor is not None and new:
known = local.setdefault(ancestor, set())
new = new - known
known |= new
for name in new:
wake(by_file_name.get((ancestor, name), ()), f"{why} mentions {name}")
ancestor = self.parent.get(ancestor)
if item["kind"] == "use" and item["glob"]:
for name in item["names"]:
for target in sees.get(crate, {crate}):
for module in list(by_module.get((target, name), ())) + \
([f"crates/{idents[name]}/src/lib.rs"] if name in idents else []):
if module not in globbed and module in universe:
globbed.add(module)
wake([(module, index, None) for index in range(len(self.parse(module)["items"]))]
if self.parse(module) else [], f"{why} glob-imports {name}")
visible_to = sees.get(crate, {crate})
new = source["paths"] - done["paths"].setdefault(crate, set())
done["paths"][crate] |= new
for name in new:
for target in visible_to:
path_names.setdefault(target, set()).add(name)
for module in by_module.get((target, name), ()):
if module in universe and self.parent[module] in opened:
open_module(module, f"{why} names {name}")
for key, table, wanted in (("qualified", qualified, lambda other: True),
("invokes", invoked, lambda other: item_of(other)["kind"] == "macro"),
("mentions", mentioned, lambda other: other[2] is not None or other[0] in globbed)):
new = source[key] - done[key].setdefault(crate, set())
done[key][crate] |= new
for name in new:
table.setdefault(name, set()).add(crate)
wake([other for other in by_name.get(name, ()) if crate_of(other[0]) in visible_to and wanted(other)],
f"{why} {key} {name}")
if item["kind"] in TYPE_KINDS and member is None:
own = types.setdefault(crate, set())
local_types.setdefault(path, set()).update(names(node))
if not names(node) <= own:
own |= names(node)
visible_cache.clear()
seeing = seen_by.get(crate, {crate})
for name in names(node): # also when the crate has one by that name already: impls of this one
wake([other for other in by_type.get(name, ()) if crate_of(other[0]) in seeing],
f"implements for {name}, defined in {path}")
return files
def impl_subject(header):
"""An impl header (the text after `impl`): its generic parameters' names, and the rest without its where clause
(the trait and the type it is for)."""
header, parameters = header.strip(), set()
if header.startswith("<"):
depth = 0
for index, character in enumerate(header):
depth += {"<": 1, ">": -1}.get(character, 0)
if depth == 0:
generics, header = header[1:index], header[index + 1:]
parameters = {match.group(1) for match in re.finditer(rf"(?:^|,)\s*(?:const\s+)?({IDENT})", generics)}
break
return parameters, re.split(r"\bwhere\b", header)[0]
def crate_of(path):
return path.split("/", 2)[1]
def is_workspace_rust(path):
parts = PurePosixPath(path).parts
return len(parts) > 2 and parts[0] == "crates" and path.endswith(".rs")
DECLARATION_LINE = re.compile(rf"\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+({IDENT})\s*;")
def declarations(text, names, keep_rest):
"""A Rust file's `mod` declarations of names, each with the attribute lines just above it; with keep_rest, the
whole text except the declarations of other modules instead."""
lines, found, attributes = text.splitlines(), [], []
for line in lines:
if line.strip().startswith("#[") and not line.strip().startswith("#!["):
attributes.append(line.strip())
continue
match = DECLARATION_LINE.match(line)
if match and match.group(1) in names:
found += attributes + [line.strip()]
elif keep_rest and not match:
found += attributes + [line]
attributes = []
return "\n".join(found + attributes)
def declarations_changed(root, path, children, base, whole):
"""Whether a changed file differs from the commit base in what a harness depends on: for a module parent, its
`mod` declarations of the reached children; for a whole file (whole), everything but its declarations of other
modules (adding a module beside reached ones changes nothing). True without a base, or if either side is
missing."""
if base is None:
return True
try:
head = (Path(root) / path).read_text(encoding="utf-8", errors="replace")
before = subprocess.run(["git", "show", f"{base}:{path}"], cwd=root, capture_output=True, text=True, check=True).stdout
except (OSError, subprocess.CalledProcessError):
return True
return declarations(head, children, whole) != declarations(before, children, whole)
def narrow(dependencies, artifacts, graph, changed=()):
"""A harness's dependencies narrowed to what its entry points can reach: {dependency: (whole, children)}, where
whole says the file counts for its own content (else only through its `mod` declarations of children, as a
module ancestor of a reached file) and children are its reached child modules. Without known entry points (a
probe or binary the harness built that isn't found here), every dependency is kept whole."""
plain = [dependency.split("#keep:")[0] for dependency in dependencies]
crates = {PurePosixPath(path).parts[1] for path in plain if path.startswith("crates/")}
rust = {path for path in plain if is_workspace_rust(path)}
added = {path for path in changed if is_workspace_rust(path) and PurePosixPath(path).parts[1] in crates
and path not in rust and (graph.root / path).is_file()}
entries = graph.entries(artifacts, rust)
if entries is None:
return {dependency: (True, None) for dependency in dependencies}
missing = {path for path in rust if graph.parse(path) is None}
reached = graph.reachable(entries, rust | added | entries) | missing
named, named_in_crate = set(), {}
for path in rust | added:
parsed = graph.parse(path)
file_names = set(parsed["file_names"]) if parsed else set()
if path in reached:
named |= file_names
named_in_crate.setdefault(PurePosixPath(path).parts[1], set()).update(file_names)
kept = {}
for dependency, path in zip(dependencies, plain):
if is_workspace_rust(path):
if path in reached:
kept[dependency] = (True, set())
elif not path.startswith("crates/") or path.endswith(("Cargo.toml", "build.rs")) \
or PurePosixPath(path).name in named \
or PurePosixPath(path).name not in named_in_crate.get(PurePosixPath(path).parts[1], ()):
kept[dependency] = (True, None)
for path in sorted(added & reached):
kept[path] = (True, set())
for path in sorted(reached):
child = path
while child in graph.parent:
parent = graph.parent[child]
kept.setdefault(parent, (False, set()))[1].add(graph.module_name[child])
child = parent
return kept
+4 -2
View File
@@ -108,7 +108,7 @@ def touched_crates(paths, packages):
def area(path):
"""The part of the project a path belongs to; None for what goes with any change (docs, tests, harnesses)."""
if is_doc(path) or path.startswith(("tests/", "mods/", "docs/")) or path == "research-lock.json" or \
if is_doc(path) or path.startswith(("tests/", "mods/", "docs/", "roadmap/")) or path == "research-lock.json" or \
(path.startswith("tools/") and not path.startswith("tools/ci/")):
return None
if path.startswith(("launcher/", "crates/horizon-prepare/")):
@@ -288,7 +288,9 @@ def plan(args, base, changed, crates_of, libraries, dependencies):
"""The checks for these changed files, in the order they run."""
rust = any(workspace_rust(path) for path in changed)
launcher = any(launcher_rust(path) for path in changed)
python = any(path.endswith(".py") or path.startswith(("tests/", "tools/")) for path in changed)
# The Python tests also hold ROADMAP.md to roadmap/roadmap.toml (tests/test_roadmap.py).
python = any(path.endswith(".py") or path.startswith(("tests/", "tools/", "roadmap/")) or path == "ROADMAP.md"
for path in changed)
crates = touched_crates(changed, crates_of) if rust or TOKENS in changed else []
# An unrecognised Rust path must not silently skip validation.
if rust and crates == []:
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""The prepared output's version: what keeps `OUTPUT_VERSION` (crates/horizon-prepare/src/lib.rs) honest.
The launcher copies a prepared version's resources (`.local/horizon-client/<version>`) to a newly installed
one when both pin the same Minecraft jars and their preparers declare the same `OUTPUT_VERSION`, so a release
that changes the preparer's code without changing what it makes asks nobody to prepare again. The number is
bumped by hand; this tool catches a change to the output without a bump.
crates/horizon-prepare/output-versions.txt lists every `OUTPUT_VERSION` with the digest of what it prepares.
It only grows: the last line is the current version, and a change to the output appends a line.
python3 tools/prepare_output.py digest [RESOURCES] the digest of a preparation
python3 tools/prepare_output.py check [--base SHA] [--cache] [RESOURCES]
fails when RESOURCES (default: this checkout's .local/horizon-client/<version>, as CI prepares it) is
not what the last line says, or when the file changed other than by appending since SHA. --cache keeps
the digest beside RESOURCES (CI: a preparation never changes once made; it takes ~30 s to compute)
The digest covers every file of the preparation, canonicalised where the preparer is not deterministic between
runs (verified across the CI runners): JSON is compared as data (key order, the order of each `tags` list of
creative-inventory.json, and the addresses in `$$Lambda/0x...` class names don't count); logs, compiled classes,
the sounds (copied from the player's launcher by another step) and the manifest's file hashes (raw bytes) don't
count. The manifest's own scalar fields (schema, data version, jar hashes, file count) do.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
VERSIONS = 'crates/horizon-prepare/output-versions.txt'
LIB = 'crates/horizon-prepare/src/lib.rs'
MANIFEST = 'horizon-resources.json'
LAMBDA = re.compile(r'\$\$Lambda/0x[0-9a-fA-F]+')
CONSTANT = re.compile(r'^pub const OUTPUT_VERSION: u32 = (\d+);', re.M)
def canonical_json(value, key=''):
if isinstance(value, dict):
return {k: canonical_json(v, k) for k, v in value.items()}
if isinstance(value, list):
items = [canonical_json(v, key) for v in value]
if key == 'tags' and all(isinstance(x, list) and all(isinstance(t, str) for t in x) for x in items):
items = [sorted(x) for x in items]
return items
if isinstance(value, str):
return LAMBDA.sub('$$Lambda', value)
return value
def canonical(rel: str, data: bytes) -> bytes:
if rel == MANIFEST:
manifest = json.loads(data)
scalars = {k: v for k, v in manifest.items() if not isinstance(v, (dict, list))}
return json.dumps(scalars, sort_keys=True).encode()
if rel.endswith('.json'):
try:
value = json.loads(data)
except ValueError:
return data
return json.dumps(canonical_json(value), sort_keys=True).encode()
return data
def skipped(rel: str) -> bool:
parts = rel.split('/')
return rel.endswith(('.log', '.class')) or parts[:3] == ['assets', 'minecraft', 'sounds'] \
or rel == 'assets/minecraft/sounds.json'
def digest(resources: Path) -> tuple[str, int]:
"""The digest of a preparation, and how many files it covers."""
if not (resources / MANIFEST).is_file():
raise SystemExit(f'{resources} is not a preparation: no {MANIFEST}')
files = []
for dirpath, dirs, names in os.walk(resources):
dirs.sort()
for name in names:
path = Path(dirpath) / name
rel = path.relative_to(resources).as_posix()
if path.is_symlink() or skipped(rel):
continue
files.append(rel)
total = hashlib.sha256()
for rel in sorted(files):
data = hashlib.sha256(canonical(rel, (resources / rel).read_bytes())).hexdigest()
total.update(f'{rel}\0{data}\n'.encode())
return total.hexdigest(), len(files)
def parse_versions(text: str) -> list[tuple[int, str]]:
out = []
for line in text.splitlines():
line = line.strip()
if not line or line.startswith('#'):
continue
number, value = line.split()
out.append((int(number), value))
return out
def problems(versions: list[tuple[int, str]], constant: int | None) -> list[str]:
found = []
if not versions:
return [f'{VERSIONS} lists no version']
if [n for n, _ in versions] != list(range(1, len(versions) + 1)):
found.append(f'{VERSIONS}: the versions must be 1, 2, 3... in order')
if len({d for _, d in versions}) != len(versions):
found.append(f'{VERSIONS}: two versions with the same digest')
if constant != versions[-1][0]:
found.append(f'{LIB} says OUTPUT_VERSION = {constant}, {VERSIONS} ends at {versions[-1][0]}')
return found
def default_resources() -> Path:
lock = json.loads((ROOT / 'research-lock.json').read_text())
return ROOT / '.local/horizon-client' / lock['minecraft']['version']
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
parser.add_argument('command', choices=['digest', 'check'])
parser.add_argument('resources', nargs='?', type=Path)
parser.add_argument('--base', help='the commit the change is based on (check: the file only grew since)')
parser.add_argument('--cache', action='store_true', help='keep the digest beside the preparation')
args = parser.parse_args()
resources = (args.resources or default_resources()).resolve()
tool = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()[:16]
cache = resources.parent / f'.output-digest-{resources.name}-{tool}'
if args.cache and cache.is_file():
value, count = cache.read_text().split()
else:
value, count = digest(resources)
if args.cache:
cache.write_text(f'{value} {count}\n')
if args.command == 'digest':
print(value)
return 0
versions = parse_versions((ROOT / VERSIONS).read_text())
match = CONSTANT.search((ROOT / LIB).read_text())
found = problems(versions, int(match.group(1)) if match else None)
if args.base:
shown = subprocess.run(['git', 'show', f'{args.base}:{VERSIONS}'], cwd=ROOT, capture_output=True, text=True)
if shown.returncode == 0:
before = parse_versions(shown.stdout)
if versions[:len(before)] != before:
found.append(f'{VERSIONS} changed lines it already had (since {args.base[:12]}): '
'a new output gets a new version, appended')
current = versions[-1] if versions else (0, '')
if value != current[1]:
known = [n for n, d in versions if d == value]
if known:
found.append(f'the preparation is OUTPUT_VERSION {known[0]}\'s output, but OUTPUT_VERSION is {current[0]}')
else:
found.append(
f'the prepared output changed ({count} files, digest {value}) but OUTPUT_VERSION is still '
f'{current[0]}. Players would keep resources prepared by the old preparer. Bump it:\n'
f' set `pub const OUTPUT_VERSION: u32 = {current[0] + 1};` in {LIB}\n'
f' append `{current[0] + 1} {value}` to {VERSIONS}\n'
' (if the change is only a nondeterminism this tool should ignore, teach canonical() instead)')
for problem in found:
print(f'::error::{problem}' if os.environ.get('GITHUB_ACTIONS') else f'error: {problem}', file=sys.stderr)
if not found:
print(f'prepared output: OUTPUT_VERSION {current[0]} ({count} files, {value[:16]})')
return 1 if found else 0
if __name__ == '__main__':
sys.exit(main())
+26 -8
View File
@@ -414,13 +414,26 @@ def gather(kind, head, releases=None):
return last, prs
def green_main_head():
"""The newest commit on main whose checks passed: what an automatic release builds."""
runs = gh_json("run", "list", "--repo", REPO, "--workflow", "checks", "--branch", "main", "--event", "push",
def passed_on(workflow, sha):
"""Whether the newest finished push run of workflow on main for commit sha passed."""
runs = gh_json("run", "list", "--repo", REPO, "--workflow", workflow, "--branch", "main", "--event", "push",
"--commit", sha, "--limit", "5", "--json", "status,conclusion")
done = [entry for entry in runs if entry["status"] == "completed" and entry["conclusion"] != "cancelled"]
return bool(done) and done[0]["conclusion"] == "success"
def green_main_head(parity=False):
"""The newest commit on main whose checks passed: what an automatic release builds. With parity (game
releases), the newest commit parity-main passed on, if its checks passed too: parity-main runs on batches of
merges, so the commits a run skipped are covered by the next one, and a superseded run counts for nothing."""
workflow = "parity-main" if parity else "checks"
runs = gh_json("run", "list", "--repo", REPO, "--workflow", workflow, "--branch", "main", "--event", "push",
"--limit", "10", "--json", "headSha,status,conclusion")
for entry in runs:
if entry["status"] == "completed":
return entry["headSha"] if entry["conclusion"] == "success" else None
if entry["status"] == "completed" and entry["conclusion"] != "cancelled":
if entry["conclusion"] != "success":
return None
return entry["headSha"] if not parity or passed_on("checks", entry["headSha"]) else None
return None
@@ -437,7 +450,7 @@ def main():
parser.add_argument("--kind", choices=["game", "launcher"], required=True)
parser.add_argument("--head", help="the commit to release (default: the newest commit on main whose checks passed)")
parser.add_argument("--tag", help="notes: the release's tag")
parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle or while paused")
parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle, while paused or before parity-main passed")
parser.add_argument("--out", type=Path, help="notes: write title.txt and body.md here")
parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)")
parser.add_argument("--smoke", type=Path, help="gate: the release smoke test's report (smoke-test.json)")
@@ -456,9 +469,12 @@ def main():
summary.write(f"### {line}\n")
return 1 if problem else 0
head = args.head or green_main_head()
# Game releases ship only a commit the vanilla harnesses passed on (parity-main, docs/release-flow.md).
parity = args.kind == "game" and args.command == "decide" and not args.force
head = args.head or green_main_head(parity)
if not head:
result = {"release": False, "reason": "main's latest checks did not pass"}
result = {"release": False, "reason": "main's latest checks did not pass" + (
" or parity-main did not pass on them" if parity else "")}
print(json.dumps(result, indent=1))
write_outputs({"release": "false", "reason": result["reason"]})
return 0
@@ -482,6 +498,8 @@ def main():
blockers = open_blockers() if args.kind == "game" else []
release, reason = decision(args.kind, prs, now, os.environ.get("RELEASES_PAUSED") == "1", args.force, new_line,
blockers)
if release and args.head and parity and not (passed_on("parity-main", head) and passed_on("checks", head)):
release, reason = False, f"waiting for checks and parity-main to pass on {head[:9]}"
minor = any("feature" in pr["labels"] for pr in prs if pr["paths"])
tag = next_game_tag(tags, now.date(), line) if args.kind == "game" else next_launcher_tag(tags, minor, line)
result = {
+612
View File
@@ -0,0 +1,612 @@
#!/usr/bin/env python3
"""Horizon's roadmap: roadmap/roadmap.toml is the source, ROADMAP.md is generated from it.
python3 tools/roadmap.py build write ROADMAP.md and website/data/roadmap.json
python3 tools/roadmap.py build --check fail when either is out of date (CI)
python3 tools/roadmap.py check --offline the file's own rules (CI)
python3 tools/roadmap.py check the same, then GitHub: links resolve, no stale Now item
python3 tools/roadmap.py sync [--dry-run] items whose pull requests all merged become shipped,
with the release they went out in
python3 tools/roadmap.py labels [--dry-run] a `roadmap:<id>` label per item on GitHub, and on the open
pull requests the item links
The online commands read GitHub with GITHUB_TOKEN, GH_TOKEN or `gh auth token`. Maintenance: roadmap/README.md.
"""
import argparse
import datetime
import json
import os
import re
import subprocess
import sys
import tomllib
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SOURCE = ROOT / "roadmap" / "roadmap.toml"
OUTPUT = ROOT / "ROADMAP.md"
# What the website's hub reads (website/build.mjs), and serves at /data/roadmap.json for Kira and others.
SITE_DATA = ROOT / "website" / "data" / "roadmap.json"
# The journal's weekly summaries, one file per ISO week: roadmap/journal/2026-43.md (roadmap/README.md).
JOURNAL = ROOT / "roadmap" / "journal"
WEEK = re.compile(r"(\d{4})-(\d{2})\.md$")
REPO = "ludovic111/horizon"
SITE = "https://playhorizon.dev/hub"
STATUSES = {
"now": "Now",
"next": "Next",
"later": "Later",
"help-wanted": "Help wanted",
"shipped": "Recently shipped",
}
PLAIN_MAX = 240 # one post's worth, so a shipped item can be announced as written
TITLE_MAX = 70
FOCUS_RANGE = (3, 5)
STALE_DAYS = 14 # a Now item needs an open pull request, or one merged this recently
LABEL_PREFIX = "roadmap:"
# GitHub label colours by status, from the design system's palette.
LABEL_COLOURS = {"now": "5b3fd6", "next": "9a86ff", "later": "c5c7d1", "help-wanted": "1d7a48", "shipped": "646875"}
ITEM_KEYS = {"id", "title", "status", "area", "plain", "dev", "links", "focus", "ongoing", "shipped_in", "post",
"announce"}
ISSUE = re.compile(r"#(\d+)$")
ID = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*$")
# An item is the anchor playhorizon.dev/hub#<id>: it can't take the name of a tab, a section or a heading.
RESERVED = {"main", "overview", "roadmap", "board", "journal", "contribute", "report", "suggest", "contributors",
"hub-data", *STATUSES}
RESERVED_PREFIXES = ("h-", "tab-", "col-", "week-", "journal-")
RELEASE = re.compile(r"(v\d[\w.]*|launcher@\d[\w.]*|launcher-v\d[\w.]*|website)$")
MONTHS = ("January|February|March|April|June|July|August|September|October|November|December")
# Kira's rule: no dates and no promises of when. "Coming soon" is the one allowed phrase.
DATE = re.compile(
rf"\b(?:{MONTHS})\b|\bMay \d|(?<![#\w.])20\d\d(?!\w|\.\d)|\bQ[1-4]\b|\btomorrow\b|\btonight\b"
r"|\b(?:next|this) (?:week|month|year)\b|\bin \d+ (?:days?|weeks?|months?)\b|\bby the end of\b",
re.IGNORECASE)
MONTH_CASE = re.compile(rf"\b(?:{MONTHS})\b")
def load(path=SOURCE):
with open(path, "rb") as source:
return tomllib.load(source)
def link_url(link):
"""Where a link points: "#12" is an issue or a pull request (GitHub redirects one to the other)."""
match = ISSUE.match(link)
if match:
return f"https://github.com/{REPO}/issues/{match[1]}"
return link
def dated(text):
"""The first date or deadline in the text, or None. A month counts only capitalised ("march" is a verb)."""
for match in DATE.finditer(text):
if match[0].lower() not in MONTHS.lower().split("|") or MONTH_CASE.fullmatch(match[0]):
return match[0]
return None
def validate(data, root=ROOT):
"""The file's own rules, without the network. Returns a list of problems."""
problems = []
overview = data.get("overview", {})
for key in ("today_plain", "today_dev", "help_plain", "help_dev"):
if not str(overview.get(key, "")).strip():
problems.append(f"overview: {key} is missing")
areas = [area.get("id") for area in data.get("area", [])]
if len(set(areas)) != len(areas):
problems.append("areas: an id appears twice")
seen = set()
items = data.get("item", [])
for index, item in enumerate(items):
where = f"item {item.get('id') or index + 1}"
for key in sorted(set(item) - ITEM_KEYS):
problems.append(f"{where}: unknown key {key!r}")
for key in ("id", "title", "status", "area", "plain", "dev"):
if not str(item.get(key, "")).strip():
problems.append(f"{where}: {key} is missing")
ident = item.get("id", "")
if ident and not ID.match(ident):
problems.append(f"{where}: ids are lowercase words joined by dashes")
if ident in RESERVED or ident.startswith(RESERVED_PREFIXES):
problems.append(f"{where}: the id is taken by the hub page (hub#{ident} is a tab, a section or a heading)")
if ident in seen:
problems.append(f"{where}: the id appears twice")
seen.add(ident)
status = item.get("status")
if status not in STATUSES:
problems.append(f"{where}: status {status!r} is not one of {', '.join(STATUSES)}")
if item.get("area") not in areas:
problems.append(f"{where}: area {item.get('area')!r} is not declared in an [[area]]")
if len(item.get("title", "")) > TITLE_MAX:
problems.append(f"{where}: the title is longer than {TITLE_MAX} characters")
for key in ("plain", "post"):
if len(item.get(key, "")) > PLAIN_MAX:
problems.append(f"{where}: {key} is {len(item[key])} characters, at most {PLAIN_MAX}")
for key in ("title", "plain", "dev", "post"):
found = dated(item.get(key, ""))
if found:
problems.append(f"{where}: {key} names a date or a deadline ({found!r}); the roadmap has none")
shipped_in = item.get("shipped_in")
if status == "shipped":
if not shipped_in:
problems.append(f"{where}: a shipped item needs shipped_in (a release tag, or \"website\")")
elif not RELEASE.match(shipped_in):
problems.append(f"{where}: shipped_in {shipped_in!r} is not a release tag or \"website\"")
elif shipped_in:
problems.append(f"{where}: only shipped items have shipped_in")
for key in ("focus", "ongoing", "announce"):
if key in item and not isinstance(item[key], bool):
problems.append(f"{where}: {key} is true or false")
if item.get("ongoing") and status not in ("now", "next", "later"):
problems.append(f"{where}: only Now, Next and Later items are ongoing")
if item.get("focus") and status != "now":
problems.append(f"{where}: only Now items can be in focus")
links = item.get("links", [])
if not isinstance(links, list):
problems.append(f"{where}: links is a list")
links = []
if not links and status != "later":
problems.append(f"{where}: needs at least one link (an issue, a pull request or a doc)")
for link in links:
if ISSUE.match(link) or link.startswith("https://"):
continue
if link.startswith(("/", "http:")) or ".." in link or not (root / link).exists():
problems.append(f"{where}: link {link!r} is neither #N, https:// nor a path in the repository")
problems += weeks()[1] if root == ROOT else []
focus = sum(1 for item in items if item.get("focus"))
low, high = FOCUS_RANGE
if not low <= focus <= high:
problems.append(f"focus: {focus} items are in focus, the overview wants {low} to {high}")
return problems
def areas_in_order(data):
return [(area["id"], area["name"]) for area in data.get("area", [])]
def by_area(data, status):
"""The items of a status, grouped by area in the areas' order, each group in the file's order."""
items = [item for item in data.get("item", []) if item.get("status") == status]
return [(name, [item for item in items if item["area"] == key])
for key, name in areas_in_order(data) if any(item["area"] == key for item in items)]
def linkify(text, links=()):
"""Markdown links for the text's #N, and for the item's own paths and URLs where the text names them."""
text = re.sub(r"(?<![\w\[/])#(\d+)\b", lambda m: f"[#{m[1]}]({link_url('#' + m[1])})", text)
for link in links:
if not ISSUE.match(link):
text = re.sub(rf"(?<![\w/\[])(?<!\]\(){re.escape(link)}(?![\w/])", f"[{link}]({link})", text, count=1)
return text
def link_list(links):
return " · ".join(f"[{link}]({link_url(link)})" for link in links)
def render(data):
"""ROADMAP.md, from the parsed TOML."""
overview = data["overview"]
items = data.get("item", [])
out = [
"# Horizon roadmap",
"",
"<!-- Generated by tools/roadmap.py from roadmap/roadmap.toml: edit that file, then run"
" `python3 tools/roadmap.py build`. -->",
"",
"What is being done on Horizon, what comes next and where you can help. There are no dates: things are"
" Now, Next or Later. Each item is said in plain words, with the technical picture folded under it."
f" The same roadmap, with a Simple / Technical switch, the board, the journal and how to help, is on"
f" [playhorizon.dev/hub]({SITE}). Pull requests carry the `roadmap:<id>` label of their item.",
"",
"## At a glance",
"",
overview["today_plain"].strip(),
"",
"**Being done now**",
"",
]
out += [f"- **{item['title']}**: {item['plain'].strip()}" for item in items if item.get("focus")]
nexts = [item["title"] for item in items if item.get("status") == "next"]
if nexts:
out += ["", "**Next**: " + "; ".join(nexts) + "."]
out += ["", f"**How to help**: {overview['help_plain'].strip()}", "",
f"**Developers**: {overview['help_dev'].strip()}"]
for status, heading in STATUSES.items():
groups = by_area(data, status)
if not groups:
continue
out += ["", f"## {heading}"]
if status == "shipped":
# Newest first: the file's order, where `sync` puts each newly shipped item on top.
out += [""] + [f"- **{item['title']}** ({item['shipped_in']}): {item['plain'].strip()} "
f"{link_list(item['links'])}" for item in items if item.get("status") == status]
continue
for area, group in groups:
out += ["", f"### {area}"]
for item in group:
out += ["", f"#### {item['title']}", "", item["plain"].strip(), "",
"<details><summary>Technical</summary>", "", linkify(item["dev"].strip(), item.get("links", []))]
more = [link for link in item.get("links", []) if not re.search(rf"{re.escape(link)}\b", item["dev"])]
if more:
out += ["", "More: " + link_list(more)]
out += ["", "</details>"]
return "\n".join(out) + "\n"
def weeks(directory=JOURNAL):
"""The weekly summaries, newest first: {"week", "date" (its Monday), "title", "plain", "dev"}, and problems."""
entries, problems = [], []
for path in sorted(directory.glob("*.md"), reverse=True) if directory.exists() else []:
name = WEEK.match(path.name)
text = path.read_text()
parts = re.match(r"# (.+)\n\n(.+?)\n\n## Technical\n\n(.+)", text.strip() + "\n", re.S)
if not name or not 1 <= int(name[2]) <= 53:
problems.append(f"journal/{path.name}: name it by its ISO week, like 2026-43.md")
continue
if not parts:
problems.append(f"journal/{path.name}: needs '# Title', the plain text, then '## Technical' and its text")
continue
monday = datetime.date.fromisocalendar(int(name[1]), int(name[2]), 1)
entries.append({"week": path.stem, "date": monday.isoformat(), "title": parts[1].strip(),
"plain": " ".join(parts[2].split()), "dev": " ".join(parts[3].split())})
return entries, problems
def site_data(data):
"""website/data/roadmap.json: the items as the hub and Kira read them, in the file's order."""
keys = ("id", "title", "status", "area", "plain", "dev", "links", "focus", "ongoing", "shipped_in", "post",
"announce")
out = {
"format": "horizon-roadmap",
"version": 1,
"source": "roadmap/roadmap.toml",
"overview": {key: " ".join(value.split()) for key, value in data["overview"].items()},
"statuses": [{"id": key, "name": name} for key, name in STATUSES.items()],
"areas": [{"id": key, "name": name} for key, name in areas_in_order(data)],
"items": [{key: (" ".join(item[key].split()) if isinstance(item[key], str) else item[key])
for key in keys if key in item} for item in data.get("item", [])],
"journal": weeks()[0],
}
return json.dumps(out, indent=1, ensure_ascii=False) + "\n"
def outputs(data):
"""Every generated file and its content."""
return {OUTPUT: render(data), SITE_DATA: site_data(data)}
# --- GitHub ---------------------------------------------------------------------------------------------------
def token():
for name in ("GITHUB_TOKEN", "GH_TOKEN"):
if os.environ.get(name):
return os.environ[name]
try:
return subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
sys.exit("roadmap: reading GitHub needs GITHUB_TOKEN, GH_TOKEN or `gh auth login` (or use --offline)")
def numbers_in(data):
return sorted({int(ISSUE.match(link)[1]) for item in data.get("item", [])
for link in item.get("links", []) if ISSUE.match(link)})
def github_states(numbers, auth):
"""{number: {"kind": "Issue" | "PullRequest", "state", "merged_at", "merge_commit", "paths"}} for those
that exist, in one GraphQL request per hundred numbers."""
owner, name = REPO.split("/")
states = {}
for start in range(0, len(numbers), 100):
fields = "\n".join(
f"n{n}: issueOrPullRequest(number: {n}) {{ __typename "
"... on Issue { state } "
"... on PullRequest { state mergedAt mergeCommit { oid } files(first: 100) { nodes { path } } "
"labels(first: 50) { nodes { name } } } }"
for n in numbers[start:start + 100])
query = f'query {{ repository(owner: "{owner}", name: "{name}") {{ {fields} }} }}'
request = urllib.request.Request(
"https://api.github.com/graphql", data=json.dumps({"query": query}).encode(),
headers={"Authorization": f"bearer {auth}", "User-Agent": "horizon-roadmap"})
with urllib.request.urlopen(request, timeout=30) as response:
answer = json.load(response)
for key, node in (answer.get("data", {}).get("repository") or {}).items():
if node:
states[int(key[1:])] = {
"kind": node["__typename"],
"state": node["state"],
"merged_at": node.get("mergedAt"),
"merge_commit": (node.get("mergeCommit") or {}).get("oid"),
"paths": [file["path"] for file in ((node.get("files") or {}).get("nodes") or [])],
"labels": [label["name"] for label in ((node.get("labels") or {}).get("nodes") or [])],
}
return states
def pull_requests(item, states):
return [states[n] for n in (int(ISSUE.match(link)[1]) for link in item.get("links", []) if ISSUE.match(link))
if n in states and states[n]["kind"] == "PullRequest"]
def open_issues(item, states):
return [n for n in (int(ISSUE.match(link)[1]) for link in item.get("links", []) if ISSUE.match(link))
if n in states and states[n]["kind"] == "Issue" and states[n]["state"] == "OPEN"]
def online_problems(data, states, now):
"""What only GitHub can tell: links that don't exist, Now items nobody works on, Help wanted items already
done, items `sync` would ship."""
problems, notes = [], []
recent = now - datetime.timedelta(days=STALE_DAYS)
for item in data.get("item", []):
where = f"item {item['id']}"
for link in item.get("links", []):
match = ISSUE.match(link)
if match and int(match[1]) not in states:
problems.append(f"{where}: {link} is neither an issue nor a pull request of {REPO}")
pulls = pull_requests(item, states)
status = item.get("status")
if status == "now":
alive = [p for p in pulls if p["state"] == "OPEN" or
(p["merged_at"] and datetime.datetime.fromisoformat(p["merged_at"]) >= recent)]
if not alive:
problems.append(f"{where}: stale: Now, but no open pull request and none merged in the last "
f"{STALE_DAYS} days (link the work, or move it to Next or Later)")
if status == "help-wanted":
issues = [states[int(ISSUE.match(link)[1])] for link in item.get("links", [])
if ISSUE.match(link) and int(ISSUE.match(link)[1]) in states]
if issues and all(i["state"] != "OPEN" for i in issues):
problems.append(f"{where}: every linked issue and pull request is closed: ship or drop it")
if status != "shipped" and pulls and all(p["state"] == "MERGED" for p in pulls):
if item.get("ongoing"):
notes.append(f"{where}: ongoing, and all its pull requests merged: link the new ones")
elif not open_issues(item, states):
notes.append(f"{where}: all its pull requests merged: `python3 tools/roadmap.py sync` ships it "
"once a release has them")
return problems, notes
# --- sync -----------------------------------------------------------------------------------------------------
def family(paths):
"""Which releases carry a change: the launcher's, the website (deployed from main) or the game's."""
if paths and all(path.startswith("launcher/") for path in paths):
return "launcher"
if paths and all(path.startswith("website/") for path in paths):
return "website"
return "game"
def first_release(commit, kind):
"""The oldest release tag of this kind that contains the commit, or None while none does."""
if kind == "website":
return "website"
tags = subprocess.run(["git", "tag", "--contains", commit, "--sort=creatordate"], cwd=ROOT,
capture_output=True, text=True).stdout.split()
wanted = (lambda tag: tag.startswith(("launcher@", "launcher-v"))) if kind == "launcher" else \
(lambda tag: re.match(r"v\d", tag))
return next((tag for tag in tags if wanted(tag)), None)
def release_of(pulls):
"""The release that shipped the last of these merged pull requests, or None."""
kinds = {family(p["paths"]) for p in pulls}
kind = "game" if "game" in kinds or len(kinds) > 1 else kinds.pop()
latest = max(pulls, key=lambda p: p["merged_at"])
return first_release(latest["merge_commit"], kind) if latest["merge_commit"] else None
def item_span(lines, ident):
"""[start, end) of the item's lines: its [[item]] header to its last key, without the comments that follow."""
starts = [i for i, line in enumerate(lines) if line.strip() == "[[item]]"]
for position, start in enumerate(starts):
end = starts[position + 1] if position + 1 < len(starts) else len(lines)
if not any(re.match(rf'id\s*=\s*"{re.escape(ident)}"\s*$', line) for line in lines[start:end]):
continue
while end > start and (not lines[end - 1].strip() or re.match(r"#(\s|-|$)", lines[end - 1])):
end -= 1
return start, end
raise KeyError(ident)
def mark_shipped(text, ident, release):
"""The TOML with this item shipped in `release`, moved to the top of the shipped items (newest first)."""
lines = text.split("\n")
start, end = item_span(lines, ident)
block = [line for line in lines[start:end] if not line.startswith("shipped_in")]
block = [f'status = "shipped"\nshipped_in = "{release}"' if re.match(r"status\s*=", line) else line
for line in block]
block = [line for line in block if not re.match(r"focus\s*=", line)]
rest = lines[:start] + lines[end:]
# Drop the blank line the block leaves behind.
if start < len(rest) and start > 0 and not rest[start - 1].strip() and not rest[start].strip():
del rest[start]
shipped = [i for i, line in enumerate(rest) if re.match(r'status\s*=\s*"shipped"', line)]
if shipped:
header = max(i for i in range(shipped[0] + 1) if rest[i].strip() == "[[item]]")
rest[header:header] = block + [""]
else:
rest += [""] + block
return "\n".join(rest)
def sync(data, text, states):
"""Ship every item whose linked pull requests all went out in a release and whose linked issues are all
closed, unless it is ongoing. Returns the new text and what happened."""
log = []
for item in data.get("item", []):
if item.get("status") == "shipped":
continue
pulls = pull_requests(item, states)
# An ongoing item, or one with an open issue, still has work left whatever its pull requests say.
if item.get("ongoing") or open_issues(item, states):
continue
if not pulls or any(p["state"] != "MERGED" for p in pulls):
continue
release = release_of(pulls)
if release is None:
log.append(f"{item['id']}: merged, waiting for a release")
continue
text = mark_shipped(text, item["id"], release)
log.append(f"{item['id']}: shipped in {release}")
return text, log
# --- labels ---------------------------------------------------------------------------------------------------
def label_of(item):
"""The GitHub label of an item: its name, colour and description (GitHub allows 100 characters)."""
description = f"Roadmap, {STATUSES[item['status']].lower()}: {item['title']}"
return {"name": LABEL_PREFIX + item["id"], "color": LABEL_COLOURS[item["status"]], "description": description[:100]}
def label_changes(data, existing, states):
"""What `labels` does: [(action, label or number, payload)] for labels to create or update, and open pull
requests linked from an item that lack its label. existing: {name: {"color", "description"}}; states as
github_states, plus each pull request's "labels"."""
changes = []
for item in data.get("item", []):
label = label_of(item)
have = existing.get(label["name"])
if have is None:
changes.append(("create", label["name"], label))
elif (have.get("color", "").lower(), have.get("description") or "") != (label["color"], label["description"]):
changes.append(("update", label["name"], label))
for link in item.get("links", []):
match = ISSUE.match(link)
state = states.get(int(match[1])) if match else None
if state and state["kind"] == "PullRequest" and state["state"] == "OPEN" and \
label["name"] not in state.get("labels", []):
changes.append(("add", int(match[1]), label["name"]))
stale = sorted(set(existing) - {LABEL_PREFIX + item["id"] for item in data.get("item", [])})
return changes, [name for name in stale if name.startswith(LABEL_PREFIX)]
def github_rest(method, path, auth, body=None):
request = urllib.request.Request(
f"https://api.github.com{path}", method=method, data=None if body is None else json.dumps(body).encode(),
headers={"Authorization": f"bearer {auth}", "Accept": "application/vnd.github+json",
"User-Agent": "horizon-roadmap"})
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response) if response.status != 204 else None
def existing_labels(auth):
labels, page = {}, 1
while True:
batch = github_rest("GET", f"/repos/{REPO}/labels?per_page=100&page={page}", auth)
labels.update({label["name"]: label for label in batch})
if len(batch) < 100:
return labels
page += 1
# --- commands -------------------------------------------------------------------------------------------------
def report(problems):
for problem in problems:
print(f"roadmap: {problem}", file=sys.stderr)
return 1 if problems else 0
def command_build(args):
data = load()
problems = validate(data)
if problems:
return report(problems)
files = outputs(data)
if args.check:
stale = [path for path, text in files.items() if not path.exists() or path.read_text() != text]
return report([f"{path.relative_to(ROOT)} is out of date: run `python3 tools/roadmap.py build`"
for path in stale])
for path, text in files.items():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
print(f"roadmap: wrote {path.relative_to(ROOT)}")
return 0
def command_check(args):
data = load()
problems = validate(data)
if not problems and not args.offline:
states = github_states(numbers_in(data), token())
online, notes = online_problems(data, states, datetime.datetime.now(datetime.timezone.utc))
problems += online
for note in notes:
print(f"roadmap: {note}")
if not problems:
print(f"roadmap: {len(data.get('item', []))} items, all good")
return report(problems)
def command_sync(args):
data = load()
problems = validate(data)
if problems:
return report(problems)
subprocess.run(["git", "fetch", "--quiet", "--tags", "origin"], cwd=ROOT, check=False)
text, log = sync(data, SOURCE.read_text(), github_states(numbers_in(data), token()))
for line in log:
print(f"roadmap: {line}")
if args.dry_run or text == SOURCE.read_text():
return 0
new = tomllib.loads(text)
if len(new.get("item", [])) != len(data.get("item", [])) or validate(new):
return report(["sync produced an invalid file; nothing written"] + validate(new))
SOURCE.write_text(text)
for path, content in outputs(new).items():
path.write_text(content)
print("roadmap: wrote roadmap/roadmap.toml, ROADMAP.md and website/data/roadmap.json")
return 0
def command_labels(args):
data = load()
problems = validate(data)
if problems:
return report(problems)
auth = token()
changes, stale = label_changes(data, existing_labels(auth), github_states(numbers_in(data), auth))
for action, target, payload in changes:
print(f"roadmap: {action} {target}" + (f" ({payload})" if action == "add" else ""))
if args.dry_run:
continue
if action == "create":
github_rest("POST", f"/repos/{REPO}/labels", auth, payload)
elif action == "update":
github_rest("PATCH", f"/repos/{REPO}/labels/{urllib.parse.quote(target, safe='')}", auth,
{"color": payload["color"], "description": payload["description"]})
else:
github_rest("POST", f"/repos/{REPO}/issues/{target}/labels", auth, {"labels": [payload]})
for name in stale:
print(f"roadmap: {name} names no item any more: rename or delete it by hand (it stays on its pull requests)")
if not changes:
print("roadmap: labels up to date")
return 0
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
commands = parser.add_subparsers(dest="command", required=True)
build = commands.add_parser("build", help="write ROADMAP.md")
build.add_argument("--check", action="store_true", help="fail when ROADMAP.md is out of date")
check = commands.add_parser("check", help="the roadmap's rules, and GitHub's state of its links")
check.add_argument("--offline", action="store_true", help="skip GitHub")
sync_command = commands.add_parser("sync", help="ship the items whose pull requests all merged")
sync_command.add_argument("--dry-run", action="store_true", help="say what would change, write nothing")
labels = commands.add_parser("labels", help="a roadmap:<id> label per item, on its linked open pull requests")
labels.add_argument("--dry-run", action="store_true", help="say what would change, change nothing")
args = parser.parse_args(argv)
return {"build": command_build, "check": command_check, "sync": command_sync,
"labels": command_labels}[args.command](args)
if __name__ == "__main__":
sys.exit(main())
+3
View File
@@ -5,6 +5,7 @@ import json
import os
from pathlib import Path
import platform
import shutil
import subprocess
import tempfile
@@ -37,6 +38,8 @@ def main():
if args.prepare:
lab.prepare()
lock, jars, libraries = test_rust_parity.verify_artifacts()
for earlier in directory.glob("run-*"): # one run per run used to stay behind: 5 GB here after a few weeks
shutil.rmtree(earlier, ignore_errors=True)
base = Path(tempfile.mkdtemp(prefix="run-", dir=directory))
oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java"
sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/probe/collision_fixture.rs"]
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""What a player holds on the cursor when they die, on a dedicated server, against vanilla's, seen by a vanilla client.
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world
vanilla generated first, with Alice an operator in survival and keep_inventory off. LocatorBarClient (a player made
of vanilla's protocol code) is given seven diamonds, picks them up onto its inventory menu's cursor (a PICKUP click)
ten blocks from the spawn, runs /kill on itself, waits on the death screen and respawns (PERFORM_RESPAWN). Twenty
ticks after dying vanilla removes the dead player (LivingEntity.tickDeath), and Player.remove's
inventoryMenu.removed drops the cursor's stack where it died. Alice then asks whether an item lies around the death
site; the reply, and the inventory slots, respawns and teleports she is sent from the death on, are compared
exactly.
"""
import sys
try:
from . import test_locator_bar_parity as locator
except ImportError:
import test_locator_bar_parity as locator
NAME = 'cursor-death-parity'
# server_dir and generate_world write these server.properties.
locator.PROPERTIES = dict(locator.PROPERTIES, gamemode='survival')
SCRIPT = [
('setup', ['cmd Alice gamerule keep_inventory false', 'cmd Alice clear @s',
'cmd Alice give @s minecraft:diamond 7', 'cmd Alice tp @s 10.5 -60 0.5']),
# Hotbar slot 0 is the inventory menu's slot 36.
('pickup', ['pickup Alice 36']),
('death', ['cmd Alice kill @s']),
('respawn', ['respawn Alice']),
('check', ['chat on', 'cmd Alice execute if entity @e[type=minecraft:item,x=10.5,y=-60,z=0.5,distance=..4]']),
]
def shown(lines):
"""Alice's slots, respawns, teleports and chat from the death on."""
return [line for line in lines if len(parts := line.split(' ', 3)) >= 3
and parts[1] in ('step=death', 'step=respawn', 'step=check')
and parts[2] in ('slot', 'inventory', 'respawn', 'teleport', 'chat')]
def check(vanilla, _):
if not any(l.startswith('Alice step=check chat') for l in vanilla):
return 'vanilla answered no check command'
return None
def main():
lines = locator.one_player(NAME, SCRIPT, shown, check, 'A player dying with a stack on the inventory menu cursor '
'(keep_inventory off) and respawning on a dedicated server: the stack is dropped '
'where it died, not kept.')
print(f'cursor death: {len(lines)} lines identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')
+3
View File
@@ -9,6 +9,7 @@ from pathlib import Path
import platform
import random
import struct
import shutil
import subprocess
import tempfile
@@ -273,6 +274,8 @@ def main():
if args.prepare:
lab.prepare()
lock, jars, libraries = test_rust_parity.verify_artifacts()
for earlier in directory.glob("run-*"): # one run per run used to stay behind: 5 GB here after a few weeks
shutil.rmtree(earlier, ignore_errors=True)
base = Path(tempfile.mkdtemp(prefix="run-", dir=directory))
commands = list(corpus())
inputs = base / "inputs.txt"
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Respawning in a hardcore world on a dedicated server, against vanilla's, seen by a vanilla client.
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one hardcore
flat world vanilla generated first, with Alice an operator in survival. LocatorBarClient (a player made of
vanilla's protocol code) joins, runs /kill on itself and presses the death screen's button
(ServerboundClientCommandPacket PERFORM_RESPAWN). Vanilla's ServerGamePacketListenerImpl.handleClientCommand
respawns the player, then makes it a spectator because the server is hardcore. The game mode changes and respawns
Alice is sent in the death and respawn steps are compared exactly.
"""
import sys
try:
from . import test_locator_bar_parity as locator
except ImportError:
import test_locator_bar_parity as locator
NAME = 'hardcore-respawn-parity'
# server_dir and generate_world write these server.properties.
locator.PROPERTIES = dict(locator.PROPERTIES, hardcore='true', gamemode='survival')
SCRIPT = [
('death', ['cmd Alice kill @s']),
('respawn', ['respawn Alice']),
]
def shown(lines):
"""Alice's game mode changes and respawns in the death and respawn steps."""
return [line for line in lines if len(parts := line.split(' ', 3)) >= 3
and parts[1] in ('step=death', 'step=respawn') and parts[2] in ('gamemode', 'respawn')]
def check(vanilla, _):
if 'Alice step=respawn gamemode 3' not in vanilla:
return 'vanilla did not make the respawned player a spectator'
return None
def main():
lines = locator.one_player(NAME, SCRIPT, shown, check, 'A player dying and respawning in a hardcore world on a '
'dedicated server: the respawn and the game mode it is sent (spectator).')
print(f'hardcore respawn: {len(lines)} lines identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')
+72 -4
View File
@@ -205,12 +205,13 @@ def run_side(label, server_command, client_command, build, world):
return out.read_text(encoding='utf-8').splitlines()
def main():
def sides(name):
"""The vanilla and Horizon dedicated servers and the LocatorBarClient that joins them, built for harness
`name`: (lock, build directory, vanilla server, Horizon server, client) commands."""
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / NAME
build = lab.LOCAL / name
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
(build / 'report.json').unlink(missing_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java'
classes = build / 'classes'
shutil.rmtree(classes, ignore_errors=True)
@@ -228,7 +229,74 @@ def main():
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']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient']
return lock, build, vanilla_server, horizon_server, client
def one_player(name, script, shown, check, scope, step_seconds=4.0):
"""A harness of one player, Alice: on each server she joins, then runs `script`, a list of (step, client
actions) `step_seconds` apart. The lines `shown(transcript)` keeps must match vanilla's exactly, and
`check(vanilla's shown lines, vanilla's transcript)` returns why vanilla's run is no proof (the script did
not run), or None."""
lock, build, vanilla_server, horizon_server, client = sides(name)
def run(label, server_command, world):
directory = build / label
port = server_dir(directory, world)
out = build / f'{label}.txt'
out.unlink(missing_ok=True)
server = Server(server_command, directory, label)
try:
server.wait_for(r'Done \(')
with (build / f'{label}-client.log').open('w') as log:
process = subprocess.Popen([*map(str, client), '127.0.0.1', str(port), str(out)], cwd=lab.ROOT,
stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, text=True)
def tell(line):
process.stdin.write(line + '\n')
process.stdin.flush()
try:
for line in ['players on', 'state on', 'step joins', 'join Alice']:
tell(line)
server.wait_for(r'Alice joined the game', timeout=120)
time.sleep(step_seconds)
for step, actions in script:
tell(f'step {step}')
for action in actions:
tell(action)
time.sleep(step_seconds)
tell('end')
process.wait(timeout=60)
finally:
if process.poll() is None:
process.kill()
finally:
server.stop()
if not out.exists():
raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)')
return out.read_text(encoding='utf-8').splitlines()
world = generate_world(vanilla_server, build)
vanilla_all = run('vanilla', vanilla_server, world)
horizon_all = run('horizon', horizon_server, world)
errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l]
vanilla, horizon = shown(vanilla_all), shown(horizon_all)
if errors or vanilla != horizon:
import difflib
diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm=''))
raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n'
+ '\n'.join(errors[:10]) + '\n' + diff[:6000])
if (why := check(vanilla, vanilla_all)) is not None:
raise AssertionError(f'{why}: the script did not run (see {build})')
lab.write_json(build / 'report.json', dict(
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), scope=scope))
return vanilla
def main():
lock, build, vanilla_server, horizon_server, client = sides(NAME)
report = build / 'report.json'
world = generate_world(vanilla_server, build)
vanilla = run_side('vanilla', vanilla_server, client, build, world)
horizon = run_side('horizon', horizon_server, client, build, world)
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Compare item lore tooltip styles with the pinned vanilla client.
Vanilla prints what ``ItemLore.addToTooltip`` adds after ``ComponentUtils.mergeStyles``
with dark purple italic (VanillaLoreTooltipOracle). Horizon prints what
``item_tooltip::lore_texts`` gives (examples/probe/lore_tooltip_fixture).
"""
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
# SNBT stacks. A lore line is a text component; italic:0b is an explicit false.
CASES = [
'{id:"minecraft:stick",count:1}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'"Plain"\']}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'{"text":"Gold","color":"gold","italic":0b}\']}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'{"text":"A","extra":[{"text":"B","color":"aqua","italic":0b}]}\']}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'"One"\',\'{"text":"Two","bold":1b}\']}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'"Hidden"\'],"minecraft:tooltip_display":{hidden_components:["minecraft:lore"]}}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'{"text":"Line","underlined":1b,"strikethrough":1b}\']}}',
]
def cases(build):
path = build / 'cases.txt'
path.write_text(''.join(line + '\n' for line in CASES))
return path, len(CASES)
if __name__ == '__main__':
harness.differential(
'lore-tooltip-parity', 'VanillaLoreTooltipOracle', 'lore_tooltip_fixture', cases,
'Item lore tooltip lines: dark purple italic, child colours, explicit non-italic, and tooltip_display',
sources=[
lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs',
lab.ROOT / 'crates/horizon-client/src/item_data.rs',
lab.ROOT / 'crates/horizon-client/src/text.rs',
lab.ROOT / 'crates/horizon-client/src/component.rs',
],
expected_lines=len(CASES))
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""An ender pearl in flight when its thrower dies, on a dedicated server, against vanilla's, seen by a vanilla client.
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world
vanilla generated first, with Alice an operator in survival. LocatorBarClient (a player made of vanilla's protocol
code) throws an ender pearl straight up (ServerboundUseItemPacket), runs /kill on itself while the pearl flies,
presses the death screen's button (PERFORM_RESPAWN) and waits for the pearl to come down, with the rule
ender_pearls_vanish_on_death true: ThrownEnderpearl.tick discards a dead owner's pearl, so the respawned player is
never teleported. The teleports, game mode changes and respawns Alice is sent from the throw on are compared
exactly.
"""
import sys
try:
from . import test_locator_bar_parity as locator
except ImportError:
import test_locator_bar_parity as locator
NAME = 'pearl-death-parity'
# server_dir and generate_world write these server.properties.
locator.PROPERTIES = dict(locator.PROPERTIES, gamemode='survival')
SCRIPT = [
('setup', ['cmd Alice gamerule ender_pearls_vanish_on_death true', 'cmd Alice give @s minecraft:ender_pearl']),
# Straight up: it comes down about four seconds later, near where it was thrown.
('throw', ['use Alice -90', 'cmd Alice kill @s']),
('respawn', ['respawn Alice']),
('landed', []),
]
def shown(lines):
"""Alice's teleports, game mode changes and respawns from the throw on."""
steps = {f'step={step}' for step, _ in SCRIPT if step != 'setup'}
return [line for line in lines if len(parts := line.split(' ', 3)) >= 3 and parts[1] in steps
and parts[2] in ('teleport', 'gamemode', 'respawn')]
def check(vanilla, vanilla_all):
killed = any(l.startswith('Alice step=throw killed') for l in vanilla_all)
if not killed or 'Alice step=respawn respawn minecraft:overworld' not in vanilla:
return 'vanilla did not kill and respawn Alice'
return None
def main():
lines = locator.one_player(NAME, SCRIPT, shown, check, 'An ender pearl in flight when its thrower dies and '
'respawns on a dedicated server, with ender_pearls_vanish_on_death true: the pearl '
'vanishes and never teleports the player.')
print(f'pearl death: {len(lines)} lines identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')
+3
View File
@@ -5,6 +5,7 @@ import json
import os
from pathlib import Path
import platform
import shutil
import subprocess
import tempfile
@@ -35,6 +36,8 @@ def main():
if args.prepare:
lab.prepare()
lock, jars, libraries = test_rust_parity.verify_artifacts()
for earlier in directory.glob("run-*"): # one run per run used to stay behind: 5 GB here after a few weeks
shutil.rmtree(earlier, ignore_errors=True)
base = Path(tempfile.mkdtemp(prefix="run-", dir=directory))
classes = base / "classes"
classes.mkdir()