Merge remote-tracking branch 'origin/t3/achieve-full-parity' into parity/warden-sculk
# Conflicts: # crates/horizon-client/src/game.rs # crates/horizon-client/src/game/creatures.rs
This commit is contained in:
@@ -0,0 +1,929 @@
|
||||
"""Command scripts for tools/test_command_exec_parity.py.
|
||||
|
||||
Each group is a list of operations: `cmd` runs a command as the player and
|
||||
records its messages and results (`record: false` runs setup silently),
|
||||
`tick` advances the game and `settle` loads the terrain around the player.
|
||||
Everything happens high above the terrain (y 200 and up, where both worlds
|
||||
are air) after the world's entities are removed, so the results do not
|
||||
depend on world generation.
|
||||
"""
|
||||
|
||||
|
||||
def cmd(command, record=True):
|
||||
op = {'op': 'cmd', 'cmd': command}
|
||||
if not record:
|
||||
op['record'] = False
|
||||
return op
|
||||
|
||||
|
||||
def setup(*commands):
|
||||
return [cmd(c, False) for c in commands]
|
||||
|
||||
|
||||
BASE = (0, 200, 0)
|
||||
|
||||
|
||||
def group_setup():
|
||||
return [
|
||||
*setup('/gamerule spawn_mobs false', '/gamerule mob_drops false', '/gamerule entity_drops false',
|
||||
'/gamerule advance_time false', '/gamerule advance_weather false', '/gamerule spawn_wandering_traders false',
|
||||
'/gamerule spawn_patrols false', '/gamerule spawn_phantoms false', '/gamerule spawn_wardens false',
|
||||
'/gamerule show_advancement_messages false', '/gamemode creative', '/tp @s 8.5 230 8.5 0 0'),
|
||||
{'op': 'settle'},
|
||||
*setup('/kill @e[type=!player]'),
|
||||
{'op': 'tick', 'n': 25},
|
||||
*setup('/kill @e[type=!player]'),
|
||||
{'op': 'tick', 'n': 25},
|
||||
*setup('/fill 0 200 0 15 228 15 air', '/time set 1000', '/weather clear', '/difficulty normal', '/clear @s'),
|
||||
]
|
||||
|
||||
|
||||
def client_commands():
|
||||
return [
|
||||
cmd('/version'),
|
||||
cmd('/spectate'),
|
||||
cmd('/spectate @s'),
|
||||
cmd('/gamemode spectator'),
|
||||
cmd('/spectate'),
|
||||
cmd('/spectate @s'),
|
||||
cmd('/spectate @s @s'),
|
||||
cmd('/gamemode creative'),
|
||||
cmd('/posteffect list @s'),
|
||||
cmd('/posteffect remove @s minecraft:blur'),
|
||||
cmd('/posteffect clear @s'),
|
||||
cmd('/posteffect add @s minecraft:blur'),
|
||||
cmd('/posteffect add @s minecraft:blur'),
|
||||
cmd('/posteffect add @a minecraft:invert'),
|
||||
cmd('/posteffect list @s'),
|
||||
cmd('/posteffect remove @s minecraft:blur'),
|
||||
cmd('/posteffect remove @p minecraft:blur'),
|
||||
cmd('/posteffect list @p'),
|
||||
cmd('/posteffect clear @s'),
|
||||
cmd('/posteffect clear @s'),
|
||||
cmd('/waypoint list'),
|
||||
cmd('/waypoint modify @s color red'),
|
||||
cmd('/waypoint modify @s color dark_aqua'),
|
||||
cmd('/waypoint modify @s color hex 12ab3f'),
|
||||
cmd('/waypoint modify @s color hex F0A'),
|
||||
cmd('/waypoint list'),
|
||||
cmd('/waypoint modify @s color reset'),
|
||||
cmd('/waypoint modify @s style set minecraft:bowtie'),
|
||||
cmd('/waypoint modify @s style reset'),
|
||||
cmd('/waypoint list'),
|
||||
cmd('/dialog show @s minecraft:server_links'),
|
||||
cmd('/dialog show @a minecraft:quick_actions'),
|
||||
cmd('/dialog show @s {type:"minecraft:notice",title:"Hello"}'),
|
||||
cmd('/dialog clear @s'),
|
||||
cmd('/dialog clear @a'),
|
||||
cmd('/kick @s'),
|
||||
cmd('/kick @s Go away'),
|
||||
cmd('/kick Player'),
|
||||
cmd('/fetchprofile name Notch'),
|
||||
{'op': 'tick', 'n': 5, 'record': True},
|
||||
cmd('/fetchprofile id 069a79f4-44e9-4726-a5be-fca90e38aaf5'),
|
||||
{'op': 'tick', 'n': 5, 'record': True},
|
||||
cmd('/unpublish'),
|
||||
cmd('/debug stop'),
|
||||
cmd('/debug start'),
|
||||
cmd('/debug start'),
|
||||
cmd('/debug stop'),
|
||||
cmd('/debug stop'),
|
||||
cmd('/jfr stop'),
|
||||
]
|
||||
|
||||
|
||||
def game_state():
|
||||
return [
|
||||
cmd('/gamemode survival'),
|
||||
cmd('/gamemode survival'),
|
||||
cmd('/gamemode adventure @s'),
|
||||
cmd('/gamemode creative @a'),
|
||||
cmd('/defaultgamemode survival'),
|
||||
cmd('/defaultgamemode creative'),
|
||||
cmd('/difficulty'),
|
||||
cmd('/difficulty hard'),
|
||||
cmd('/difficulty hard'),
|
||||
cmd('/difficulty normal'),
|
||||
cmd('/seed'),
|
||||
cmd('/time set 1000'),
|
||||
cmd('/time query daytime'),
|
||||
cmd('/time set noon'),
|
||||
cmd('/time set night'),
|
||||
cmd('/time add 100'),
|
||||
cmd('/time set 1000'),
|
||||
cmd('/weather rain'),
|
||||
cmd('/weather thunder 600'),
|
||||
cmd('/weather clear 1d'),
|
||||
cmd('/gamerule keep_inventory'),
|
||||
cmd('/gamerule keep_inventory true'),
|
||||
cmd('/gamerule keep_inventory'),
|
||||
cmd('/gamerule keep_inventory false'),
|
||||
cmd('/gamerule random_tick_speed 5'),
|
||||
cmd('/gamerule random_tick_speed'),
|
||||
cmd('/gamerule random_tick_speed 3'),
|
||||
cmd('/list'),
|
||||
cmd('/say Hello world'),
|
||||
cmd('/me waves'),
|
||||
cmd('/msg @s secret'),
|
||||
cmd('/tellraw @s {"text":"raw","color":"gold","bold":true}'),
|
||||
cmd('/tellraw @s ["a",{"text":"b","italic":true},{"translate":"block.minecraft.stone"}]'),
|
||||
cmd('/title @s title "Hi"'),
|
||||
cmd('/title @s subtitle "Sub"'),
|
||||
cmd('/title @s actionbar "Bar"'),
|
||||
cmd('/title @s times 10 20 30'),
|
||||
cmd('/title @s clear'),
|
||||
cmd('/title @s reset'),
|
||||
cmd('/help gamemode'),
|
||||
cmd('/random value 5..5'),
|
||||
cmd('/random roll 7..7'),
|
||||
cmd('/tick query'),
|
||||
cmd('/stopwatch create harness:a'),
|
||||
cmd('/stopwatch create harness:a'),
|
||||
cmd('/stopwatch query harness:b'),
|
||||
]
|
||||
|
||||
|
||||
def player_state():
|
||||
return [
|
||||
*setup('/gamemode survival'),
|
||||
cmd('/experience add @s 10'),
|
||||
cmd('/experience add @s 3 levels'),
|
||||
cmd('/experience query @s levels'),
|
||||
cmd('/experience query @s points'),
|
||||
cmd('/experience set @s 0 levels'),
|
||||
cmd('/xp set @s 5 points'),
|
||||
cmd('/experience query @s points'),
|
||||
cmd('/effect give @s minecraft:speed 30 1'),
|
||||
cmd('/effect give @s minecraft:speed 10 0'),
|
||||
cmd('/effect give @s minecraft:night_vision infinite 0 true'),
|
||||
cmd('/effect clear @s minecraft:speed'),
|
||||
cmd('/effect clear @s minecraft:speed'),
|
||||
cmd('/effect clear @s'),
|
||||
cmd('/effect clear @s'),
|
||||
cmd('/give @s minecraft:diamond 3'),
|
||||
cmd('/give @s minecraft:diamond_sword[minecraft:custom_name="Blade"]'),
|
||||
cmd('/give @s minecraft:stone 130'),
|
||||
cmd('/clear @s minecraft:diamond 0'),
|
||||
cmd('/clear @s minecraft:stone 0'),
|
||||
cmd('/clear @s minecraft:stone 64'),
|
||||
cmd('/clear @s minecraft:stone 0'),
|
||||
cmd('/item replace entity @s weapon.mainhand with minecraft:iron_pickaxe'),
|
||||
cmd('/enchant @s minecraft:efficiency 3'),
|
||||
cmd('/enchant @s minecraft:sharpness'),
|
||||
cmd('/enchant @s minecraft:efficiency 9'),
|
||||
cmd('/item replace entity @s armor.head with minecraft:golden_helmet'),
|
||||
cmd('/clear @s minecraft:golden_helmet 0'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:1}'),
|
||||
cmd('/clear @s'),
|
||||
cmd('/clear @s'),
|
||||
cmd('/attribute @s minecraft:max_health get'),
|
||||
cmd('/attribute @s minecraft:max_health base get'),
|
||||
cmd('/attribute @s minecraft:max_health base set 30'),
|
||||
cmd('/attribute @s minecraft:max_health modifier add harness:extra 4 add_value'),
|
||||
cmd('/attribute @s minecraft:max_health modifier value get harness:extra'),
|
||||
cmd('/attribute @s minecraft:max_health get'),
|
||||
cmd('/attribute @s minecraft:max_health modifier remove harness:extra'),
|
||||
cmd('/attribute @s minecraft:max_health base reset'),
|
||||
cmd('/spawnpoint @s 8 230 8'),
|
||||
cmd('/setworldspawn 8 230 8'),
|
||||
cmd('/tp @s 8.5 230 8.5'),
|
||||
cmd('/tp @s ~1 ~ ~'),
|
||||
cmd('/teleport @s 8.5 230 8.5 90 0'),
|
||||
cmd('/rotate @s 45 10'),
|
||||
cmd('/damage @s 2'),
|
||||
cmd('/damage @s 1 minecraft:magic'),
|
||||
*setup('/gamemode creative'),
|
||||
]
|
||||
|
||||
|
||||
def world_blocks():
|
||||
return [
|
||||
cmd('/setblock 2 205 2 minecraft:stone'),
|
||||
cmd('/setblock 2 205 2 minecraft:stone'),
|
||||
cmd('/setblock 2 205 2 minecraft:oak_stairs[facing=east]'),
|
||||
cmd('/execute if block 2 205 2 minecraft:oak_stairs[facing=east]'),
|
||||
cmd('/execute if block 2 205 2 minecraft:stone'),
|
||||
cmd('/execute unless block 2 205 2 minecraft:stone'),
|
||||
cmd('/fill 0 201 0 4 203 4 minecraft:glass'),
|
||||
cmd('/fill 0 201 0 4 203 4 minecraft:glass'),
|
||||
cmd('/fill 0 201 0 4 203 4 minecraft:stone hollow'),
|
||||
cmd('/fill 0 201 0 4 203 4 minecraft:dirt replace minecraft:stone'),
|
||||
cmd('/fill 0 201 0 4 203 4 minecraft:air destroy'),
|
||||
cmd('/execute if blocks 0 201 0 4 203 4 0 210 0 all'),
|
||||
cmd('/setblock 3 206 3 minecraft:chest'),
|
||||
cmd('/item replace block 3 206 3 container.0 with minecraft:apple 5'),
|
||||
cmd('/data get block 3 206 3 Items[0].count'),
|
||||
cmd('/data merge block 3 206 3 {CustomName:"Box"}'),
|
||||
cmd('/clone 0 205 0 4 207 4 6 205 6'),
|
||||
cmd('/clone 0 205 0 4 207 4 6 205 6 masked'),
|
||||
cmd('/execute if blocks 0 205 0 4 207 4 6 205 6 all'),
|
||||
cmd('/setblock 3 206 3 minecraft:air'),
|
||||
cmd('/fill 0 200 0 15 228 15 air'),
|
||||
cmd('/execute if block 0 300 0 air'),
|
||||
cmd('/setblock 0 400 0 stone'),
|
||||
cmd('/worldborder get'),
|
||||
cmd('/worldborder set 1000'),
|
||||
cmd('/worldborder set 1000'),
|
||||
cmd('/worldborder center 10 20'),
|
||||
cmd('/worldborder center 10 20'),
|
||||
cmd('/worldborder damage amount 0.5'),
|
||||
cmd('/worldborder damage buffer 3'),
|
||||
cmd('/worldborder warning distance 10'),
|
||||
cmd('/worldborder warning time 20'),
|
||||
cmd('/worldborder add 100'),
|
||||
cmd('/worldborder get'),
|
||||
cmd('/worldborder set 59999968'),
|
||||
cmd('/worldborder center 0 0'),
|
||||
]
|
||||
|
||||
|
||||
def entities():
|
||||
return [
|
||||
cmd('/summon minecraft:pig 4.5 210 4.5 {NoAI:1b,NoGravity:1b,Tags:["a","h"]}'),
|
||||
cmd('/summon minecraft:cow 6.5 210 4.5 {NoAI:1b,NoGravity:1b,CustomName:"Daisy",Tags:["h"]}'),
|
||||
cmd('/summon minecraft:armor_stand 8.5 210 4.5 {NoGravity:1b}'),
|
||||
cmd('/execute if entity @e[tag=h,type=minecraft:pig]'),
|
||||
cmd('/execute if entity @e[tag=h,type=minecraft:sheep]'),
|
||||
cmd('/tag @e[tag=h,type=minecraft:pig] list'),
|
||||
cmd('/tag @e[tag=h,type=minecraft:cow] add b'),
|
||||
cmd('/tag @e[tag=h,type=minecraft:cow] add b'),
|
||||
cmd('/tag @e[tag=b] list'),
|
||||
cmd('/tag @e[tag=b] remove b'),
|
||||
cmd('/data get entity @e[tag=h,type=minecraft:pig,limit=1] Tags'),
|
||||
cmd('/data get entity @e[tag=h,type=minecraft:cow,limit=1] CustomName'),
|
||||
cmd('/data merge entity @e[tag=h,type=minecraft:pig,limit=1] {Tags:["a","c"]}'),
|
||||
cmd('/attribute @e[tag=h,type=minecraft:pig,limit=1] minecraft:movement_speed base get'),
|
||||
cmd('/effect give @e[tag=h] minecraft:glowing 10'),
|
||||
cmd('/damage @e[tag=h,type=minecraft:cow,limit=1] 1'),
|
||||
cmd('/ride @s mount @e[tag=h,type=minecraft:pig,limit=1]'),
|
||||
cmd('/ride @s dismount'),
|
||||
cmd('/ride @s dismount'),
|
||||
cmd('/spectate @e[tag=h,type=minecraft:pig,limit=1]'),
|
||||
cmd('/gamemode spectator'),
|
||||
cmd('/spectate @e[tag=h,type=minecraft:pig,limit=1]'),
|
||||
cmd('/spectate'),
|
||||
cmd('/gamemode creative'),
|
||||
cmd('/waypoint modify @e[tag=h,type=minecraft:pig,limit=1] color red'),
|
||||
cmd('/waypoint modify @e[type=minecraft:armor_stand,limit=1] color red'),
|
||||
cmd('/fetchprofile entity @e[tag=h,type=minecraft:pig,limit=1]'),
|
||||
cmd('/kill @e[tag=h,type=minecraft:pig]'),
|
||||
cmd('/kill @e[tag=h,type=minecraft:pig]'),
|
||||
cmd('/execute as @e[tag=h] run say mob'),
|
||||
cmd('/execute store result score @s harness_score run data get entity @s SelectedItemSlot'),
|
||||
cmd('/kill @e[tag=h]'),
|
||||
*setup('/kill @e[type=minecraft:armor_stand]'),
|
||||
{'op': 'tick', 'n': 25},
|
||||
cmd('/execute if entity @e[tag=h]'),
|
||||
]
|
||||
|
||||
|
||||
def scores():
|
||||
return [
|
||||
cmd('/scoreboard objectives add harness dummy'),
|
||||
cmd('/scoreboard objectives add harness dummy'),
|
||||
cmd('/scoreboard objectives add harness_h health "Health"'),
|
||||
cmd('/scoreboard objectives list'),
|
||||
cmd('/scoreboard players set @s harness 5'),
|
||||
cmd('/scoreboard players add @s harness 3'),
|
||||
cmd('/scoreboard players remove @s harness 1'),
|
||||
cmd('/scoreboard players get @s harness'),
|
||||
cmd('/scoreboard players set fake harness 9'),
|
||||
cmd('/scoreboard players operation @s harness += fake harness'),
|
||||
cmd('/scoreboard players get @s harness'),
|
||||
cmd('/scoreboard players list'),
|
||||
cmd('/scoreboard players list @s'),
|
||||
cmd('/scoreboard players reset fake harness'),
|
||||
cmd('/scoreboard players get fake harness'),
|
||||
cmd('/scoreboard objectives setdisplay list harness'),
|
||||
cmd('/scoreboard objectives setdisplay sidebar harness'),
|
||||
cmd('/scoreboard objectives modify harness displayname "Shown"'),
|
||||
cmd('/scoreboard objectives modify harness rendertype hearts'),
|
||||
cmd('/execute store result score @s harness run scoreboard players get @s harness'),
|
||||
cmd('/execute if score @s harness matches 15'),
|
||||
cmd('/team add red_team'),
|
||||
cmd('/team add red_team'),
|
||||
cmd('/team modify red_team color red'),
|
||||
cmd('/team modify red_team prefix "[R] "'),
|
||||
cmd('/team join red_team @s'),
|
||||
cmd('/team list'),
|
||||
cmd('/team list red_team'),
|
||||
cmd('/waypoint list'),
|
||||
cmd('/team leave @s'),
|
||||
cmd('/team remove red_team'),
|
||||
cmd('/scoreboard objectives remove harness'),
|
||||
cmd('/scoreboard objectives remove harness_h'),
|
||||
cmd('/bossbar add harness:bar "Bar"'),
|
||||
cmd('/bossbar add harness:bar "Bar"'),
|
||||
cmd('/bossbar set harness:bar value 30'),
|
||||
cmd('/bossbar set harness:bar max 60'),
|
||||
cmd('/bossbar set harness:bar color red'),
|
||||
cmd('/bossbar set harness:bar style notched_10'),
|
||||
cmd('/bossbar set harness:bar players @s'),
|
||||
cmd('/bossbar get harness:bar value'),
|
||||
cmd('/bossbar get harness:bar players'),
|
||||
cmd('/bossbar list'),
|
||||
cmd('/bossbar remove harness:bar'),
|
||||
cmd('/bossbar remove harness:bar'),
|
||||
]
|
||||
|
||||
|
||||
def execute():
|
||||
return [
|
||||
*setup('/scoreboard objectives add exec dummy', '/scoreboard players set @s exec 4', '/scoreboard players set fake exec 9'),
|
||||
cmd('/execute as @s run say hi'),
|
||||
cmd('/execute as @s at @s run tp @s ~ ~ ~'),
|
||||
cmd('/execute positioned 4 210 4 run setblock ~ ~ ~ minecraft:stone'),
|
||||
cmd('/execute positioned 4 210 4 if block ~ ~ ~ minecraft:stone'),
|
||||
cmd('/execute positioned as @s run tp @s ~ ~ ~'),
|
||||
cmd('/execute align xyz run summon minecraft:armor_stand ~ ~-20 ~ {NoGravity:1b,Tags:["ex"],UUID:[I;1,2,3,4]}'),
|
||||
cmd('/execute if entity @e[tag=ex]'),
|
||||
cmd('/execute as @e[tag=ex] run data get entity @s Pos'),
|
||||
cmd('/data get entity @e[tag=ex,limit=1]'),
|
||||
cmd('/data get entity @e[tag=ex,limit=1] Pose'),
|
||||
cmd('/execute anchored eyes run tp @s ^ ^ ^'),
|
||||
cmd('/execute rotated 90 0 run tp @s ~ ~ ~ ~ ~'),
|
||||
cmd('/execute rotated as @e[tag=ex,limit=1] run tp @s ~ ~ ~ ~ ~'),
|
||||
cmd('/execute facing 0 230 0 run tp @s ~ ~ ~ ~ ~'),
|
||||
cmd('/execute facing entity @e[tag=ex,limit=1] feet run tp @s ~ ~ ~ ~ ~'),
|
||||
cmd('/execute in minecraft:the_nether run setblock 0 200 0 minecraft:stone'),
|
||||
cmd('/execute in minecraft:the_end if block 0 64 0 minecraft:air'),
|
||||
cmd('/execute in minecraft:the_end run say elsewhere'),
|
||||
cmd('/execute in minecraft:nowhere run say nowhere'),
|
||||
cmd('/execute in minecraft:overworld run setblock 5 210 5 minecraft:dirt'),
|
||||
cmd('/execute if dimension minecraft:overworld'),
|
||||
cmd('/execute if dimension minecraft:the_end'),
|
||||
cmd('/execute if loaded 8 230 8'),
|
||||
cmd('/execute if loaded 100000 230 100000'),
|
||||
cmd('/execute if score @s exec matches 4'),
|
||||
cmd('/execute if score @s exec < fake exec'),
|
||||
cmd('/execute if score @s exec = fake exec'),
|
||||
cmd('/execute unless score @s exec matches 1..3'),
|
||||
cmd('/execute if score nobody exec matches 1'),
|
||||
cmd('/execute if data entity @s Inventory'),
|
||||
cmd('/execute if data entity @e[tag=ex,limit=1] Tags[0]'),
|
||||
cmd('/execute if data block 4 210 4 Items'),
|
||||
cmd('/execute if data storage harness:s value'),
|
||||
cmd('/execute if predicate minecraft:tool/can_shear'),
|
||||
cmd('/execute if predicate {condition:"minecraft:random_chance",chance:1.0}'),
|
||||
cmd('/execute if predicate {condition:"minecraft:entity_properties",entity:"this",predicate:{type:"minecraft:player"}}'),
|
||||
cmd('/execute if items entity @s weapon.mainhand minecraft:air'),
|
||||
cmd('/execute if items entity @s container.* *'),
|
||||
cmd('/execute store result score @s exec run data get entity @s SelectedItemSlot'),
|
||||
cmd('/execute store success score @s exec run setblock 4 210 4 minecraft:stone'),
|
||||
cmd('/scoreboard players get @s exec'),
|
||||
cmd('/execute store result storage harness:s value int 2 run scoreboard players get fake exec'),
|
||||
cmd('/data get storage harness:s value'),
|
||||
cmd('/execute store result entity @e[tag=ex,limit=1] Rotation[0] float 1 run scoreboard players get fake exec'),
|
||||
cmd('/data get entity @e[tag=ex,limit=1] Rotation'),
|
||||
cmd('/execute store result block 4 210 4 x int 1 run scoreboard players get fake exec'),
|
||||
cmd('/execute summon minecraft:armor_stand run tag @s add summoned'),
|
||||
cmd('/execute if entity @e[tag=summoned]'),
|
||||
cmd('/execute as @e[tag=ex] on passengers run say passenger'),
|
||||
cmd('/execute on vehicle run say vehicle'),
|
||||
cmd('/execute as @e[tag=ex] run return 3'),
|
||||
cmd('/execute if entity @s run return fail'),
|
||||
cmd('/return 7'),
|
||||
cmd('/return fail'),
|
||||
cmd('/return run scoreboard players get fake exec'),
|
||||
cmd('/execute if biome 8 230 8 #minecraft:is_overworld'),
|
||||
cmd('/execute if block 8 0 8 #minecraft:base_stone_overworld'),
|
||||
cmd('/execute as @a run tellraw @s "each"'),
|
||||
*setup('/kill @e[type=minecraft:armor_stand]', '/setblock 4 210 4 minecraft:air', '/setblock 5 210 5 minecraft:air',
|
||||
'/scoreboard objectives remove exec', '/tp @s 8.5 230 8.5 0 0'),
|
||||
{'op': 'tick', 'n': 25},
|
||||
]
|
||||
|
||||
|
||||
def items_and_loot():
|
||||
return [
|
||||
*setup('/clear @s', '/gamemode survival'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:3}'),
|
||||
cmd('/item replace entity @s weapon.mainhand with minecraft:stone 10'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:3}'),
|
||||
cmd('/clear @s minecraft:stone 0'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_count",count:5,add:true}'),
|
||||
cmd('/clear @s minecraft:stone 0'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:limit_count",limit:{max:4}}'),
|
||||
cmd('/clear @s minecraft:stone 0'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_name",name:"Rock"}'),
|
||||
cmd('/data get entity @s SelectedItem'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_name",name:{text:"Item",color:"red"},target:"item_name"}'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_lore",lore:["one","two"],mode:"replace_all"}'),
|
||||
cmd('/item modify entity @s weapon.mainhand [{type:"minecraft:set_count",count:2},{type:"minecraft:set_custom_data",tag:{a:1b}}]'),
|
||||
cmd('/data get entity @s SelectedItem'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_components",components:{"minecraft:max_stack_size":16}}'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:filtered",item_filter:{items:"minecraft:dirt"},on_pass:{type:"minecraft:set_count",count:1}}'),
|
||||
cmd('/clear @s minecraft:stone 0'),
|
||||
cmd('/item replace entity @s weapon.mainhand with minecraft:diamond_sword'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_damage",damage:0.5}'),
|
||||
cmd('/data get entity @s SelectedItem.components'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_enchantments",enchantments:{"minecraft:sharpness":3}}'),
|
||||
cmd('/data get entity @s SelectedItem.components."minecraft:enchantments"'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:set_enchantments",enchantments:{"minecraft:sharpness":1},add:true}'),
|
||||
cmd('/data get entity @s SelectedItem.components."minecraft:enchantments"'),
|
||||
cmd('/item modify entity @s weapon.mainhand {type:"minecraft:toggle_tooltips",toggles:{"minecraft:enchantments":false}}'),
|
||||
cmd('/item modify entity @s armor.head {type:"minecraft:set_count",count:1}'),
|
||||
cmd('/item modify entity @s weapon.offhand {type:"minecraft:set_count",count:1}'),
|
||||
cmd('/item modify entity @s hotbar.* {type:"minecraft:set_count",count:1}'),
|
||||
cmd('/item modify entity @s weapon.mainhand minecraft:nonexistent'),
|
||||
cmd('/item replace entity @s hotbar.1 from entity @s weapon.mainhand'),
|
||||
cmd('/item replace entity @s hotbar.2 from entity @s weapon.mainhand {type:"minecraft:set_count",count:1}'),
|
||||
cmd('/clear @s minecraft:diamond_sword 0'),
|
||||
cmd('/setblock 3 206 3 minecraft:barrel'),
|
||||
cmd('/item replace block 3 206 3 container.4 with minecraft:emerald 7'),
|
||||
cmd('/item modify block 3 206 3 container.4 {type:"minecraft:set_count",count:2}'),
|
||||
cmd('/item modify block 3 206 3 container.5 {type:"minecraft:set_count",count:2}'),
|
||||
cmd('/item modify block 3 206 3 container.99 {type:"minecraft:set_count",count:2}'),
|
||||
cmd('/item modify block 3 207 3 container.0 {type:"minecraft:set_count",count:2}'),
|
||||
cmd('/data get block 3 206 3 Items'),
|
||||
cmd('/data get block 3 206 3'),
|
||||
cmd('/item replace entity @s hotbar.3 from block 3 206 3 container.4'),
|
||||
cmd('/item replace block 3 206 3 container.0 from entity @s hotbar.3'),
|
||||
cmd('/data get block 3 206 3 Items'),
|
||||
cmd('/loot give @s loot minecraft:blocks/stone'),
|
||||
cmd('/loot give @s loot minecraft:blocks/dirt'),
|
||||
cmd('/loot insert 3 206 3 loot minecraft:blocks/oak_planks'),
|
||||
cmd('/loot replace block 3 206 3 container.8 loot minecraft:blocks/cobblestone'),
|
||||
cmd('/loot replace entity @s hotbar.5 loot minecraft:blocks/glass'),
|
||||
cmd('/loot spawn 3 210 3 loot minecraft:blocks/stone'),
|
||||
cmd('/loot give @s loot {pools:[{rolls:1,entries:[{type:"minecraft:item",name:"minecraft:apple",functions:[{type:"minecraft:set_count",count:4}]}]}]}'),
|
||||
cmd('/setblock 2 205 2 minecraft:stone'),
|
||||
cmd('/loot give @s mine 2 205 2'),
|
||||
cmd('/loot give @s mine 2 205 2 mainhand'),
|
||||
cmd('/loot give @s mine 2 205 2 minecraft:diamond_pickaxe[minecraft:enchantments={"minecraft:silk_touch":1}]'),
|
||||
cmd('/data get block 3 206 3 Items'),
|
||||
cmd('/clear @s minecraft:cobblestone 0'),
|
||||
cmd('/clear @s minecraft:apple 0'),
|
||||
cmd('/give @s minecraft:written_book[minecraft:written_book_content={title:"T",author:"A",pages:["p"]}]'),
|
||||
cmd('/give @s minecraft:potion[minecraft:potion_contents={potion:"minecraft:swiftness"}] 2'),
|
||||
cmd('/give @s minecraft:air'),
|
||||
cmd('/give @s minecraft:stone 6401'),
|
||||
cmd('/clear @s #minecraft:logs'),
|
||||
cmd('/clear @s *[minecraft:custom_data]'),
|
||||
cmd('/clear @s'),
|
||||
*setup('/setblock 3 206 3 minecraft:air', '/setblock 2 205 2 minecraft:air', '/kill @e[type=minecraft:item]', '/gamemode creative'),
|
||||
]
|
||||
|
||||
|
||||
def world_misc():
|
||||
return [
|
||||
cmd('/setblock 1 210 1 minecraft:stone keep'),
|
||||
cmd('/setblock 1 210 1 minecraft:dirt keep'),
|
||||
cmd('/setblock 1 210 1 minecraft:dirt destroy'),
|
||||
cmd('/setblock 1 210 1 minecraft:sand strict'),
|
||||
cmd('/setblock 1 210 1 minecraft:air replace'),
|
||||
cmd('/fill 0 210 0 2 212 2 minecraft:stone outline'),
|
||||
cmd('/fill 0 210 0 2 212 2 minecraft:glass keep'),
|
||||
cmd('/fill 0 210 0 2 212 2 minecraft:dirt replace #minecraft:base_stone_overworld'),
|
||||
cmd('/fill 0 210 0 2 212 2 minecraft:air strict'),
|
||||
cmd('/fill 0 210 0 100 300 100 minecraft:stone'),
|
||||
cmd('/setblock 0 211 0 minecraft:oak_sign{front_text:{messages:["a","b","c","d"]}}'),
|
||||
cmd('/data get block 0 211 0 front_text.messages'),
|
||||
cmd('/clone 0 211 0 0 211 0 1 211 1 replace move'),
|
||||
cmd('/clone 1 211 1 1 211 1 0 211 0 filtered minecraft:oak_sign'),
|
||||
cmd('/clone 0 211 0 0 211 0 0 211 0'),
|
||||
cmd('/clone 0 211 0 0 211 0 0 212 0 replace force'),
|
||||
cmd('/clone from minecraft:overworld 0 211 0 0 211 0 to minecraft:overworld 2 211 2'),
|
||||
cmd('/fill 0 210 0 2 212 2 minecraft:air'),
|
||||
cmd('/fillbiome 0 200 0 15 215 15 minecraft:desert'),
|
||||
cmd('/execute if biome 4 205 4 minecraft:desert'),
|
||||
cmd('/fillbiome 0 200 0 15 215 15 minecraft:plains replace minecraft:desert'),
|
||||
cmd('/fillbiome 0 200 0 15 215 15 minecraft:plains replace minecraft:desert'),
|
||||
cmd('/fillbiome 0 0 0 1000 300 1000 minecraft:plains'),
|
||||
cmd('/forceload query'),
|
||||
cmd('/forceload add 0 0'),
|
||||
cmd('/forceload add 0 0'),
|
||||
cmd('/forceload query 0 0'),
|
||||
cmd('/forceload query 40 40'),
|
||||
cmd('/forceload add 32 32 47 47'),
|
||||
cmd('/forceload query'),
|
||||
cmd('/forceload remove 32 32'),
|
||||
cmd('/forceload remove all'),
|
||||
cmd('/forceload query'),
|
||||
cmd('/forceload add 0 0 1000 1000'),
|
||||
cmd('/particle minecraft:flame 4 210 4'),
|
||||
cmd('/particle minecraft:flame 4 300 4'),
|
||||
cmd('/particle minecraft:flame 4 300 4 0 0 0 0 1 force'),
|
||||
cmd('/particle minecraft:flame 4 300 4 0 0 0 0 1 force @e[type=minecraft:pig]'),
|
||||
cmd('/particle minecraft:dust{color:[1.0,0.0,0.0],scale:1.0} 4 210 4 0 0 0 0 5 force @s'),
|
||||
cmd('/particle minecraft:block{block_state:"minecraft:stone"} 4 210 4 1 1 1 0.1 10 normal @a'),
|
||||
cmd('/playsound minecraft:block.note_block.harp master @s'),
|
||||
cmd('/playsound minecraft:block.note_block.harp record @s 4 210 4 1 2 0'),
|
||||
cmd('/playsound minecraft:block.note_block.harp master @a 1000 210 1000'),
|
||||
cmd('/stopsound @s'),
|
||||
cmd('/stopsound @s master'),
|
||||
cmd('/stopsound @s * minecraft:block.note_block.harp'),
|
||||
cmd('/stopsound @s music minecraft:music.game'),
|
||||
cmd('/swing @s'),
|
||||
cmd('/swing @s offhand'),
|
||||
cmd('/swing @e[type=minecraft:pig]'),
|
||||
cmd('/summon minecraft:armor_stand 4.5 210 4.5 {NoGravity:1b,Tags:["w"],CustomName:{text:"Stand",color:"blue"}}'),
|
||||
cmd('/swing @e[tag=w]'),
|
||||
cmd('/summon minecraft:lightning_bolt 4.5 300 4.5'),
|
||||
cmd('/summon minecraft:pig 4.5 210 4.5 {NoAI:1b,Invulnerable:1b,Tags:["w"],Passengers:[{id:"minecraft:chicken",NoAI:1b,Tags:["w"]}]}'),
|
||||
cmd('/summon minecraft:pig 4.5 400 4.5'),
|
||||
cmd('/summon minecraft:pig 30000000 210 4.5'),
|
||||
cmd('/summon minecraft:player'),
|
||||
cmd('/summon minecraft:marker 4.5 210 4.5 {Tags:["w","mk"]}'),
|
||||
cmd('/gamemode spectator'),
|
||||
cmd('/spectate @e[tag=mk,limit=1]'),
|
||||
cmd('/spectate @e[type=minecraft:armor_stand,tag=w,limit=1]'),
|
||||
cmd('/spectate @e[type=minecraft:pig,tag=w,limit=1] @s'),
|
||||
cmd('/spectate @e[type=minecraft:chicken,tag=w,limit=1] Player'),
|
||||
cmd('/spectate'),
|
||||
cmd('/spectate @e[tag=nothing,limit=1]'),
|
||||
cmd('/gamemode creative'),
|
||||
# The waypoint manager is a HashSet of entities (identity hash order),
|
||||
# so at most one transmitter at a time. Range changes take effect when
|
||||
# the entity ticks.
|
||||
cmd('/attribute @s minecraft:waypoint_transmit_range base set 0'),
|
||||
cmd('/waypoint list'),
|
||||
{'op': 'tick', 'n': 1},
|
||||
cmd('/waypoint list'),
|
||||
cmd('/attribute @e[type=minecraft:pig,tag=w,limit=1] minecraft:waypoint_transmit_range base set 100'),
|
||||
cmd('/attribute @e[type=minecraft:pig,tag=w,limit=1] minecraft:waypoint_transmit_range get'),
|
||||
cmd('/waypoint list'),
|
||||
{'op': 'tick', 'n': 1},
|
||||
cmd('/waypoint list'),
|
||||
cmd('/waypoint modify @e[type=minecraft:pig,tag=w,limit=1] color gold'),
|
||||
cmd('/waypoint modify @e[tag=mk,limit=1] color gold'),
|
||||
cmd('/waypoint list'),
|
||||
cmd('/waypoint modify @e[tag=w] color gold'),
|
||||
cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:max_health get'),
|
||||
cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier add harness:big 1 add_multiplied_base'),
|
||||
cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale get'),
|
||||
cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier add harness:big 1 add_value'),
|
||||
cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier value get harness:big'),
|
||||
cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier remove harness:big'),
|
||||
cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:scale modifier remove harness:big'),
|
||||
cmd('/attribute @e[type=minecraft:armor_stand,tag=w,limit=1] minecraft:attack_damage get'),
|
||||
cmd('/attribute @e[tag=mk,limit=1] minecraft:scale get'),
|
||||
cmd('/attribute @e[type=minecraft:pig,tag=w,limit=1] minecraft:waypoint_transmit_range base set 0'),
|
||||
{'op': 'tick', 'n': 1},
|
||||
cmd('/waypoint list'),
|
||||
cmd('/waypoint modify @e[type=minecraft:pig,tag=w,limit=1] style set minecraft:bowtie'),
|
||||
cmd('/waypoint list'),
|
||||
{'op': 'tick', 'n': 1},
|
||||
cmd('/waypoint list'),
|
||||
cmd('/kill @e[type=minecraft:pig,tag=w]'),
|
||||
{'op': 'tick', 'n': 1},
|
||||
cmd('/waypoint list'),
|
||||
{'op': 'tick', 'n': 25},
|
||||
cmd('/waypoint list'),
|
||||
cmd('/attribute @s minecraft:waypoint_transmit_range base reset'),
|
||||
{'op': 'tick', 'n': 1},
|
||||
cmd('/waypoint list'),
|
||||
cmd('/dialog show @s minecraft:custom_options'),
|
||||
cmd('/dialog show @s minecraft:nonexistent'),
|
||||
cmd('/dialog show @s {type:"minecraft:confirmation",title:"Sure?",yes:{label:"Yes"},no:{label:"No"}}'),
|
||||
cmd('/dialog show @s {type:"minecraft:notice"}'),
|
||||
cmd('/dialog show @e[tag=w] minecraft:server_links'),
|
||||
cmd('/dialog clear @e[tag=w]'),
|
||||
cmd('/dialog clear @s'),
|
||||
cmd('/spreadplayers 8 8 0 1 false @s'),
|
||||
cmd('/spreadplayers 8 8 5 1 false @s'),
|
||||
cmd('/spreadplayers 8 8 0 1 under 100 false @s'),
|
||||
cmd('/kill @e[tag=w]'),
|
||||
cmd('/tp @s 8.5 230 8.5 0 0'),
|
||||
cmd('/teleport @s 8.5 230 8.5 facing 0 230 0'),
|
||||
cmd('/teleport @s 8.5 230 8.5 facing entity @s'),
|
||||
cmd('/tp @s 30000000 230 0'),
|
||||
cmd('/tp 8.5 230 8.5'),
|
||||
cmd('/rotate @s facing 0 230 0'),
|
||||
cmd('/rotate @s ~10 ~'),
|
||||
cmd('/tp @s 8.5 230 8.5 0 0'),
|
||||
cmd('/locate biome minecraft:plains'),
|
||||
cmd('/locate biome #minecraft:is_ocean'),
|
||||
cmd('/locate structure minecraft:village_plains'),
|
||||
cmd('/locate structure #minecraft:village'),
|
||||
cmd('/locate structure minecraft:end_city'),
|
||||
cmd('/locate poi minecraft:meeting'),
|
||||
cmd('/place template minecraft:nonexistent 4 210 4'),
|
||||
cmd('/place feature minecraft:oak 4 210 4'),
|
||||
cmd('/place jigsaw minecraft:village/plains/town_centers minecraft:bottom 1 4 210 4'),
|
||||
cmd('/place structure minecraft:nonexistent'),
|
||||
*setup('/kill @e[type=!minecraft:player]', '/fill 0 200 0 15 228 15 air', '/forceload remove all', '/tp @s 8.5 230 8.5 0 0'),
|
||||
{'op': 'tick', 'n': 25},
|
||||
]
|
||||
|
||||
|
||||
def progression():
|
||||
return [
|
||||
*setup('/gamemode survival', '/experience set @s 0 levels', '/experience set @s 0 points'),
|
||||
cmd('/advancement grant @s only minecraft:story/mine_stone'),
|
||||
cmd('/advancement grant @s only minecraft:story/mine_stone'),
|
||||
cmd('/advancement revoke @s only minecraft:story/mine_stone'),
|
||||
cmd('/advancement revoke @s only minecraft:story/mine_stone'),
|
||||
cmd('/advancement grant @s only minecraft:story/upgrade_tools minecraft:stone_pickaxe'),
|
||||
cmd('/advancement grant @s only minecraft:story/upgrade_tools minecraft:stone_pickaxe'),
|
||||
cmd('/advancement grant @s only minecraft:story/upgrade_tools minecraft:nonexistent'),
|
||||
cmd('/advancement revoke @s only minecraft:story/upgrade_tools minecraft:stone_pickaxe'),
|
||||
cmd('/advancement grant @s until minecraft:story/smelt_iron'),
|
||||
cmd('/advancement grant @s from minecraft:story/root'),
|
||||
cmd('/advancement revoke @s through minecraft:story/iron_tools'),
|
||||
cmd('/advancement grant @s everything'),
|
||||
cmd('/advancement grant @s everything'),
|
||||
cmd('/experience query @s levels'),
|
||||
cmd('/experience query @s points'),
|
||||
cmd('/advancement revoke @s everything'),
|
||||
cmd('/advancement revoke @s everything'),
|
||||
cmd('/advancement grant @s only minecraft:nonexistent'),
|
||||
cmd('/recipe give @s minecraft:oak_planks'),
|
||||
cmd('/recipe give @s minecraft:oak_planks'),
|
||||
cmd('/recipe take @s minecraft:oak_planks'),
|
||||
cmd('/recipe take @s minecraft:oak_planks'),
|
||||
cmd('/recipe give @s *'),
|
||||
cmd('/recipe give @s *'),
|
||||
cmd('/recipe take @s *'),
|
||||
cmd('/recipe take @s *'),
|
||||
cmd('/experience add @s -5 levels'),
|
||||
cmd('/experience add @s 1000'),
|
||||
cmd('/experience query @s levels'),
|
||||
cmd('/experience set @s 100 points'),
|
||||
cmd('/experience set @s 1000 points'),
|
||||
cmd('/experience add @e[type=!minecraft:player] 1'),
|
||||
*setup('/gamemode creative'),
|
||||
]
|
||||
|
||||
|
||||
def functions_and_packs():
|
||||
return [
|
||||
cmd('/function minecraft:nonexistent'),
|
||||
cmd('/function #minecraft:load'),
|
||||
cmd('/function #minecraft:tick'),
|
||||
cmd('/debug function minecraft:nonexistent'),
|
||||
cmd('/schedule function minecraft:nonexistent 10'),
|
||||
cmd('/schedule clear minecraft:nonexistent'),
|
||||
cmd('/datapack list'),
|
||||
cmd('/datapack list available'),
|
||||
cmd('/datapack list enabled'),
|
||||
cmd('/datapack enable vanilla'),
|
||||
# Disabling vanilla reloads without its data; enable it again before
|
||||
# anything observes the empty registries.
|
||||
cmd('/datapack disable vanilla'),
|
||||
{'op': 'tick', 'n': 20},
|
||||
cmd('/datapack list enabled'),
|
||||
cmd('/datapack enable vanilla'),
|
||||
{'op': 'tick', 'n': 20},
|
||||
cmd('/datapack list'),
|
||||
cmd('/datapack enable "file/missing"'),
|
||||
cmd('/datapack enable trade_rebalance'),
|
||||
cmd('/datapack disable trade_rebalance'),
|
||||
cmd('/reload'),
|
||||
{'op': 'tick', 'n': 5, 'record': True},
|
||||
]
|
||||
|
||||
|
||||
def ticking():
|
||||
return [
|
||||
cmd('/tick query'),
|
||||
cmd('/tick rate 40'),
|
||||
cmd('/tick query'),
|
||||
cmd('/tick rate 20'),
|
||||
cmd('/tick freeze'),
|
||||
cmd('/tick query'),
|
||||
cmd('/tick freeze'),
|
||||
cmd('/tick step'),
|
||||
cmd('/tick step 5'),
|
||||
cmd('/tick step stop'),
|
||||
cmd('/tick step stop'),
|
||||
cmd('/tick unfreeze'),
|
||||
cmd('/tick unfreeze'),
|
||||
cmd('/tick step'),
|
||||
cmd('/tick sprint stop'),
|
||||
cmd('/tick rate 1'),
|
||||
cmd('/tick rate 20'),
|
||||
cmd('/stopwatch create harness:t'),
|
||||
cmd('/stopwatch restart harness:t'),
|
||||
cmd('/stopwatch restart harness:missing'),
|
||||
cmd('/stopwatch remove harness:t'),
|
||||
cmd('/stopwatch remove harness:t'),
|
||||
cmd('/stopwatch remove harness:a'),
|
||||
cmd('/random value 1..100 harness:seq'),
|
||||
cmd('/random value 1..100 harness:seq'),
|
||||
cmd('/random roll 1..6 harness:dice'),
|
||||
cmd('/random reset harness:seq'),
|
||||
cmd('/random value 1..100 harness:seq'),
|
||||
cmd('/random reset harness:seq 42'),
|
||||
cmd('/random value 1..100 harness:seq'),
|
||||
cmd('/random reset harness:seq 42 false false'),
|
||||
cmd('/random value 1..100 harness:seq'),
|
||||
cmd('/random reset *'),
|
||||
cmd('/random value 1..100 harness:seq'),
|
||||
cmd('/random roll 1..2147483647 harness:big'),
|
||||
cmd('/random value -2147483648..2147483647 harness:big'),
|
||||
cmd('/time query day'),
|
||||
cmd('/time set 0'),
|
||||
cmd('/time set day'),
|
||||
cmd('/time set midnight'),
|
||||
cmd('/time set sunset'),
|
||||
cmd('/time add -500'),
|
||||
cmd('/time set 1000'),
|
||||
]
|
||||
|
||||
|
||||
def compute():
|
||||
return [
|
||||
cmd('/compute default integer 5'),
|
||||
cmd('/compute default integer {type:"minecraft:add",left:2,right:3}'),
|
||||
cmd('/compute default integer {type:"minecraft:add",inputs:[2,3,4]}'),
|
||||
cmd('/compute default integer {type:"minecraft:add",inputs:[2147483647,1]}'),
|
||||
cmd('/compute default integer {type:"minecraft:mul",inputs:[6,7]}'),
|
||||
cmd('/compute default integer {type:"minecraft:avg",inputs:[1,2,4]}'),
|
||||
cmd('/compute default integer {type:"minecraft:div",left:7,right:2}'),
|
||||
cmd('/compute default integer {type:"minecraft:div",left:7,right:0}'),
|
||||
cmd('/compute default integer {type:"minecraft:mod",left:-7,right:3}'),
|
||||
cmd('/compute default integer {type:"minecraft:floor_mod",left:-7,right:3}'),
|
||||
cmd('/compute default integer {type:"minecraft:floor_div",left:-7,right:2}'),
|
||||
cmd('/compute default integer {type:"minecraft:sub",left:-2147483648,right:1}'),
|
||||
cmd('/compute default integer {type:"minecraft:pow",left:2,right:10}'),
|
||||
cmd('/compute default integer {type:"minecraft:pow",base:2,exponent:10}'),
|
||||
cmd('/compute default integer {type:"minecraft:pow",base:0,exponent:0}'),
|
||||
cmd('/compute default integer {type:"minecraft:pow",base:2,exponent:40}'),
|
||||
cmd('/compute default integer {type:"minecraft:max",values:[1,9,4]}'),
|
||||
cmd('/compute default integer {type:"minecraft:max",inputs:[1,9,4]}'),
|
||||
cmd('/compute default integer {type:"minecraft:min",inputs:[1,9,4]}'),
|
||||
cmd('/compute default integer {type:"minecraft:abs",input:-4}'),
|
||||
cmd('/compute default integer {type:"minecraft:abs",input:-2147483648}'),
|
||||
cmd('/compute default integer {type:"minecraft:negate",input:4}'),
|
||||
cmd('/compute default integer {type:"minecraft:from_float",input:2.7}'),
|
||||
cmd('/compute default integer {type:"minecraft:from_float",input:-2.7}'),
|
||||
cmd('/compute default integer {type:"minecraft:from_float",input:{type:"minecraft:div",left:1,right:0}}'),
|
||||
cmd('/compute default integer {type:"minecraft:uniform",min:3,max:3}'),
|
||||
cmd('/compute default integer {type:"minecraft:conditional",condition:{type:"minecraft:inverted",term:{type:"minecraft:match_block",blocks:"minecraft:stone"}},on_true:5}'),
|
||||
cmd('/compute default integer {type:"minecraft:nope"}'),
|
||||
cmd('/compute default integer minecraft:brewing/uses_default'),
|
||||
cmd('/compute default integer minecraft:cooking/time_coal'),
|
||||
cmd('/compute default integer minecraft:cooking/fast_burn_time_reduction_factor'),
|
||||
cmd('/compute default integer minecraft:nonexistent'),
|
||||
cmd('/compute default float 2.5'),
|
||||
cmd('/compute default float 2.5 2'),
|
||||
cmd('/compute default float 3'),
|
||||
cmd('/compute default float -0.5'),
|
||||
cmd('/compute default float 1e30'),
|
||||
cmd('/compute default float {type:"minecraft:div",left:1,right:0}'),
|
||||
cmd('/compute default float {type:"minecraft:mod",left:1,right:0}'),
|
||||
cmd('/compute default float {type:"minecraft:sqrt",value:2}'),
|
||||
cmd('/compute default float {type:"minecraft:sqrt",input:2}'),
|
||||
cmd('/compute default float {type:"minecraft:sqrt",input:2} 1000'),
|
||||
cmd('/compute default float {type:"minecraft:sqrt",input:-1}'),
|
||||
cmd('/compute default float {type:"minecraft:mul",left:1.5,right:4}'),
|
||||
cmd('/compute default float {type:"minecraft:mul",inputs:[1.5,4]}'),
|
||||
cmd('/compute default float {type:"minecraft:sub",left:1.5,right:4}'),
|
||||
cmd('/compute default float {type:"minecraft:floor",input:-1.5}'),
|
||||
cmd('/compute default float {type:"minecraft:ceil",input:-1.5}'),
|
||||
cmd('/compute default float {type:"minecraft:round",input:2.5}'),
|
||||
cmd('/compute default float {type:"minecraft:round",input:-2.5}'),
|
||||
cmd('/compute default float {type:"minecraft:truncate",input:-2.7}'),
|
||||
cmd('/compute default float {type:"minecraft:from_int",input:3}'),
|
||||
cmd('/compute default float {type:"minecraft:avg",inputs:[1,2]}'),
|
||||
cmd('/compute default float {type:"minecraft:length",inputs:[3,4]}'),
|
||||
cmd('/compute default float {type:"minecraft:pow",base:2,exponent:0.5} 100'),
|
||||
cmd('/compute default float {type:"minecraft:sin",input:1} 1000'),
|
||||
cmd('/compute default float {type:"minecraft:cos",input:1} 1000'),
|
||||
cmd('/compute default float {type:"minecraft:abs",input:-3.25}'),
|
||||
cmd('/compute default float {type:"minecraft:negate",input:3.25}'),
|
||||
cmd('/compute default float {type:"minecraft:max",inputs:[]}'),
|
||||
cmd('/compute default float minecraft:brewing/speed_default'),
|
||||
cmd('/compute default float minecraft:cooking/speed_default 100'),
|
||||
cmd('/compute block 8 229 8 float minecraft:cooking/speed_default'),
|
||||
*setup('/setblock 8 229 8 minecraft:smoker'),
|
||||
cmd('/compute block 8 229 8 float minecraft:cooking/speed_default'),
|
||||
cmd('/compute block 8 229 8 integer minecraft:cooking/time_coal'),
|
||||
*setup('/setblock 8 229 8 minecraft:composter[level=0]'),
|
||||
cmd('/compute block 8 229 8 integer minecraft:compostable/low'),
|
||||
*setup('/setblock 8 229 8 minecraft:air'),
|
||||
cmd('/compute entity @s integer {type:"minecraft:add",inputs:[1,1]}'),
|
||||
cmd('/compute entity @e[type=minecraft:pig,limit=1] integer 1'),
|
||||
cmd('/compute block 8 400 8 integer 1'),
|
||||
cmd('/compute block 100000 64 100000 integer 1'),
|
||||
cmd('/execute store result score @s cmp run compute default integer 5'),
|
||||
]
|
||||
|
||||
|
||||
def social():
|
||||
return [
|
||||
*setup('/scoreboard objectives add trig trigger', '/scoreboard objectives add plain dummy'),
|
||||
cmd('/trigger trig'),
|
||||
cmd('/scoreboard players enable @s trig'),
|
||||
cmd('/scoreboard players enable @s trig'),
|
||||
cmd('/scoreboard players enable @s plain'),
|
||||
cmd('/trigger trig'),
|
||||
cmd('/trigger trig'),
|
||||
cmd('/scoreboard players enable @s trig'),
|
||||
cmd('/trigger trig add 5'),
|
||||
cmd('/scoreboard players enable @s trig'),
|
||||
cmd('/trigger trig set 3'),
|
||||
cmd('/scoreboard players get @s trig'),
|
||||
cmd('/trigger plain'),
|
||||
cmd('/scoreboard players display name @s trig "Shown"'),
|
||||
cmd('/scoreboard players display numberformat @s trig styled {color:"red"}'),
|
||||
cmd('/scoreboard players display numberformat @s trig fixed "X"'),
|
||||
cmd('/scoreboard players display numberformat @s trig blank'),
|
||||
cmd('/scoreboard players display numberformat @s trig'),
|
||||
cmd('/scoreboard objectives modify trig numberformat fixed "Y"'),
|
||||
cmd('/scoreboard objectives modify trig displayautoupdate true'),
|
||||
cmd('/scoreboard objectives setdisplay sidebar'),
|
||||
cmd('/scoreboard objectives setdisplay sidebar.team.red trig'),
|
||||
cmd('/scoreboard players operation @s trig = @s trig'),
|
||||
cmd('/scoreboard players operation @s trig /= @s plain'),
|
||||
cmd('/scoreboard players operation @s trig >< @s plain'),
|
||||
cmd('/scoreboard players list'),
|
||||
cmd('/scoreboard players reset @s'),
|
||||
cmd('/scoreboard players list @s'),
|
||||
cmd('/teammsg hello'),
|
||||
cmd('/team add blue "Blue Team"'),
|
||||
cmd('/team join blue'),
|
||||
cmd('/teammsg hello team'),
|
||||
cmd('/tm short'),
|
||||
cmd('/team modify blue friendlyFire false'),
|
||||
cmd('/team modify blue friendlyFire false'),
|
||||
cmd('/team modify blue seeFriendlyInvisibles false'),
|
||||
cmd('/team modify blue nametagVisibility hideForOtherTeams'),
|
||||
cmd('/team modify blue deathMessageVisibility never'),
|
||||
cmd('/team modify blue collisionRule pushOwnTeam'),
|
||||
cmd('/team modify blue suffix " [B]"'),
|
||||
cmd('/team modify blue displayName "Blues"'),
|
||||
cmd('/team modify blue color reset'),
|
||||
cmd('/team list blue'),
|
||||
cmd('/team empty blue'),
|
||||
cmd('/team empty blue'),
|
||||
cmd('/team join blue fake1 fake2'),
|
||||
cmd('/team list blue'),
|
||||
cmd('/team leave fake1'),
|
||||
cmd('/team remove blue'),
|
||||
cmd('/team list'),
|
||||
cmd('/msg @s'),
|
||||
cmd('/tell Player hi'),
|
||||
cmd('/w @a hi all'),
|
||||
cmd('/me'),
|
||||
cmd('/say @s says'),
|
||||
cmd('/tellraw @s {"selector":"@s"}'),
|
||||
cmd('/tellraw @s {"score":{"name":"@s","objective":"trig"}}'),
|
||||
cmd('/tellraw @s {"nbt":"SelectedItemSlot","entity":"@s"}'),
|
||||
cmd('/tellraw @s {"nbt":"Inventory","entity":"@s","plain":true}'),
|
||||
cmd('/tellraw @s {"nbt":"value","storage":"harness:s","color":"red"}'),
|
||||
cmd('/tellraw @s {"nbt":"nothing","entity":"@s"}'),
|
||||
cmd('/tellraw @s {"text":"click","click_event":{"action":"run_command","command":"/say x"},"underlined":true}'),
|
||||
cmd('/title @s title {"selector":"@s"}'),
|
||||
cmd('/list uuids'),
|
||||
cmd('/help'),
|
||||
cmd('/help execute'),
|
||||
cmd('/help scoreboard players'),
|
||||
cmd('/help nonexistent'),
|
||||
*setup('/scoreboard objectives remove trig', '/scoreboard objectives remove plain'),
|
||||
]
|
||||
|
||||
|
||||
def test_command():
|
||||
# Horizon has no game test runner: `/test run|runmultiple|verify` of an
|
||||
# existing instance and `/test create` are not compared.
|
||||
return [
|
||||
cmd('/test clearall'),
|
||||
cmd('/test stop'),
|
||||
cmd('/test pos'),
|
||||
cmd('/test locate minecraft:always_pass'),
|
||||
cmd('/test runclosest'),
|
||||
cmd('/test resetclosest'),
|
||||
cmd('/test runfailed'),
|
||||
cmd('/test clearthese'),
|
||||
cmd('/test runthese'),
|
||||
cmd('/test runthat 2 true'),
|
||||
cmd('/test runfailed true'),
|
||||
cmd('/test resetthese'),
|
||||
cmd('/test resetthat'),
|
||||
cmd('/test clearthat'),
|
||||
cmd('/test clearall 10'),
|
||||
cmd('/test pos myPos'),
|
||||
cmd('/test locate *'),
|
||||
cmd('/test run minecraft:nothing*'),
|
||||
cmd('/test locate nothing'),
|
||||
*setup('/summon minecraft:marker 8 230 8 {Tags:["tp"]}'),
|
||||
cmd('/execute as @e[tag=tp] run test pos'),
|
||||
cmd('/execute positioned 0 230 0 run test pos'),
|
||||
cmd('/execute as @e[tag=tp] run kill @e[tag=nothing]'),
|
||||
cmd('/execute as @e[tag=tp] at @s run kill @e[tag=nothing]'),
|
||||
cmd('/execute positioned 1 2 3 run kill @e[tag=nothing]'),
|
||||
*setup('/kill @e[tag=tp]'),
|
||||
]
|
||||
|
||||
|
||||
def groups():
|
||||
return [
|
||||
('setup', group_setup()),
|
||||
('client commands', client_commands()),
|
||||
('game state', game_state()),
|
||||
('player state', player_state()),
|
||||
('blocks and border', world_blocks()),
|
||||
('entities', entities()),
|
||||
('scores, teams and bossbars', scores()),
|
||||
('execute', execute()),
|
||||
('items and loot', items_and_loot()),
|
||||
('world', world_misc()),
|
||||
('progression', progression()),
|
||||
('functions and packs', functions_and_packs()),
|
||||
('ticking and random', ticking()),
|
||||
('compute', compute()),
|
||||
('social and scoreboard', social()),
|
||||
('test', test_command()),
|
||||
]
|
||||
+2
-2
@@ -41,7 +41,7 @@ def steps(args):
|
||||
yield "doc tests", ["cargo", "+stable", "test", "--locked", "--workspace", "--doc"]
|
||||
yield "python tests", [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-q"]
|
||||
if not args.no_parity:
|
||||
yield "vanilla harnesses", [sys.executable, "tools/parity.py", "-j", str(args.jobs)]
|
||||
yield "vanilla harnesses", [sys.executable, "tools/parity.py", *(["-j", str(args.jobs)] if args.jobs is not None else [])]
|
||||
|
||||
|
||||
def head():
|
||||
@@ -53,7 +53,7 @@ def main():
|
||||
parser.add_argument("--no-parity", action="store_true", help="skip the vanilla harnesses")
|
||||
parser.add_argument("--quick", action="store_true", help="only formatting, lints and Python tests")
|
||||
parser.add_argument("--known-failures", default="", help="comma-separated harnesses allowed to keep failing")
|
||||
parser.add_argument("-j", "--jobs", type=int, default=max(1, (os.cpu_count() or 4) // 3), help="parallel harnesses")
|
||||
parser.add_argument("-j", "--jobs", type=int, help="harnesses at once on this machine (default: tools/parity.py's)")
|
||||
args = parser.parse_args()
|
||||
logs = ROOT / ".local" / "gate"
|
||||
logs.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate crates/horizon-client/src/command/vanilla_order.rs: the order of
|
||||
the children of each node of vanilla's command tree where Horizon's tree
|
||||
registers them in a different order. Brigadier keeps children in
|
||||
registration order, and /help (smart usage) lists them that way.
|
||||
|
||||
python3 tools/test_command_parse_parity.py # exports .local/command-parse-parity/tree.json
|
||||
command_parse_fixture tree rust_tree.json # Horizon's tree with child order
|
||||
generate_command_order.py VANILLA_TREE RUST_TREE
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("vanilla", type=Path)
|
||||
parser.add_argument("rust", type=Path)
|
||||
parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/command/vanilla_order.rs")
|
||||
args = parser.parse_args()
|
||||
vanilla = json.loads(args.vanilla.read_text())
|
||||
rust = json.loads(args.rust.read_text())
|
||||
rows = []
|
||||
|
||||
def walk(v, r, path):
|
||||
names = list(v.get("children", {}))
|
||||
# GameRuleCommand registers the rules in a Reference2ObjectOpenHashMap's
|
||||
# (identity hash) order, which changes from run to run.
|
||||
if path == ["gamerule"]:
|
||||
return
|
||||
order = r.get("order", [])
|
||||
shared = [n for n in names if n in order]
|
||||
if shared != [n for n in order if n in names]:
|
||||
rows.append((" ".join(path), shared))
|
||||
for n in names:
|
||||
if n in r.get("children", {}):
|
||||
walk(v["children"][n], r["children"][n], path + [n])
|
||||
|
||||
walk(vanilla, rust, [])
|
||||
if not rows or rows[0][0] != "":
|
||||
raise SystemExit("expected the root's order to differ")
|
||||
lines = [
|
||||
"//! The order of node children in vanilla's command tree, for the nodes",
|
||||
"//! where Horizon's tree registers them differently (path of node names",
|
||||
"//! from the root, children in vanilla's order). Generated by",
|
||||
"//! tools/generate_command_order.py; do not edit by hand.",
|
||||
"",
|
||||
"pub const ORDER: &[(&str, &[&str])] = &[",
|
||||
]
|
||||
for path, names in rows:
|
||||
joined = ", ".join(f'"{n}"' for n in names)
|
||||
lines.append(f' ("{path}", &[{joined}]),')
|
||||
lines += ["];", ""]
|
||||
args.out.write_text("\n".join(lines))
|
||||
print(f"wrote {len(rows)} nodes to {args.out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,243 @@
|
||||
"""Random HUD cases for test_hud_parity.py, one generator per case kind."""
|
||||
|
||||
EFFECTS = ['minecraft:poison', 'minecraft:wither', 'minecraft:regeneration', 'minecraft:hunger', 'minecraft:speed']
|
||||
|
||||
|
||||
def decorations(rng, n):
|
||||
max_health = rng.choice([20.0, 20.0, 6.0, 40.0, 33.0, 100.0])
|
||||
health = rng.choice([max_health, round(rng.uniform(0, max_health), 2), 1.0, 0.5, 3.0])
|
||||
air_max = 300
|
||||
under = rng.random() < 0.3
|
||||
air = rng.choice([air_max, rng.randint(-20, air_max), 0, 1, 29, 30, 31, 299]) if under or rng.random() < 0.2 else air_max
|
||||
case = {
|
||||
'width': rng.choice([427, 320, 480, 640, 961]), 'height': rng.choice([240, 255, 270, 360, 501]),
|
||||
'gameMode': rng.choice(['survival'] * 5 + ['adventure', 'creative', 'spectator']),
|
||||
'crosshair': rng.random() < 0.7,
|
||||
'attackIndicator': rng.choice(['OFF', 'CROSSHAIR', 'HOTBAR']),
|
||||
'attackScale': rng.choice([1.0, round(rng.random(), 3), 0.0, 0.999]),
|
||||
'selected': rng.randint(0, 8), 'rightHanded': rng.random() < 0.7,
|
||||
'slots': [rng.choice([None, 0, 0, 3, 5]) if rng.random() < 0.6 else None for _ in range(9)],
|
||||
'offhand': rng.choice([None, None, 0, 4]), 'partial': round(rng.random(), 3),
|
||||
'health': health, 'maxHealth': max_health,
|
||||
'absorption': rng.choice([0.0, 0.0, 4.0, 3.5, 17.0, 40.0]),
|
||||
'armor': rng.choice([0, 0, 1, 7, 20, 13]), 'food': rng.randint(0, 20),
|
||||
'saturation': rng.choice([0.0, 5.0, 0.0]),
|
||||
'effects': [e for e in EFFECTS if rng.random() < 0.15], 'frozen': rng.random() < 0.08,
|
||||
'hardcore': rng.random() < 0.2, 'damageCooldown': rng.choice([0, 0, 10]),
|
||||
'air': air, 'maxAir': air_max, 'underWater': under,
|
||||
'tick': rng.randint(0, 100000), 'lastHealth': rng.randint(0, 40), 'displayHealth': rng.randint(0, 40),
|
||||
'lastHealthAgo': rng.choice([0, 500, 5000]), 'healthBlinkTime': 0,
|
||||
'xpProgress': rng.choice([0.0, round(rng.random(), 4), 0.999]), 'xpLevel': rng.choice([0, 1, 7, 30, 123, 4000]),
|
||||
'experienceBar': rng.random() < 0.8,
|
||||
}
|
||||
if case['damageCooldown'] and rng.random() < 0.5:
|
||||
case['healthBlinkTime'] = case['tick'] + rng.randint(1, 20)
|
||||
if rng.random() < 0.15:
|
||||
case['vehicleMaxHealth'] = rng.choice([15.0, 30.0, 53.0, 100.0])
|
||||
case['vehicleHealth'] = round(rng.uniform(0, case['vehicleMaxHealth']), 1)
|
||||
return case
|
||||
|
||||
|
||||
ALL_EFFECTS = ['speed', 'slowness', 'haste', 'mining_fatigue', 'strength', 'instant_health', 'instant_damage', 'jump_boost',
|
||||
'nausea', 'regeneration', 'resistance', 'fire_resistance', 'water_breathing', 'invisibility', 'blindness',
|
||||
'night_vision', 'hunger', 'weakness', 'poison', 'wither', 'health_boost', 'absorption', 'saturation', 'glowing',
|
||||
'levitation', 'luck', 'unluck', 'slow_falling', 'conduit_power', 'dolphins_grace', 'bad_omen',
|
||||
'hero_of_the_village', 'darkness', 'trial_omen', 'raid_omen', 'wind_charged', 'weaving', 'oozing', 'infested',
|
||||
'breath_of_the_nautilus']
|
||||
SIZES = dict(width=[427, 320, 480, 640, 961], height=[240, 255, 270, 360, 501])
|
||||
|
||||
|
||||
def screen(rng):
|
||||
return {'width': rng.choice(SIZES['width']), 'height': rng.choice(SIZES['height'])}
|
||||
|
||||
|
||||
def backdrop(rng):
|
||||
"""The text background options behind textWithBackdrop."""
|
||||
return {'chatOnly': rng.random() < 0.5, 'textOpacity': rng.choice([0.0, 0.5, 0.25, 1.0, round(rng.random(), 3)])}
|
||||
|
||||
|
||||
def effects(rng, n):
|
||||
count = rng.choice([1, 2, 3, 5, 8, 12, 20])
|
||||
active = []
|
||||
for e in rng.sample(ALL_EFFECTS, count):
|
||||
duration = rng.choice([-1, 1, 7, 19, 20, 99, 150, 199, 200, 201, 600, 32147, 32148, 40000, rng.randint(0, 220)])
|
||||
active.append({'id': 'minecraft:' + e, 'duration': duration, 'ambient': rng.random() < 0.25, 'icon': rng.random() < 0.9})
|
||||
return {**screen(rng), 'demo': rng.random() < 0.15, 'active': active}
|
||||
|
||||
|
||||
TITLES = [{'text': 'Hello'}, {'text': 'Boss fight!', 'color': 'red', 'bold': True}, {'text': 'Wave 3', 'italic': True},
|
||||
{'text': 'A long title over the whole screen'}, {'text': ''}, ['Mixed ', {'text': 'parts', 'color': 'gold'}],
|
||||
{'text': 'Ünïcödé ★'}]
|
||||
|
||||
|
||||
def title(rng, n):
|
||||
"""Title, subtitle and action bar events between ticks (fades, setTimes mid-title, clears)."""
|
||||
ops = []
|
||||
for _ in range(rng.randint(1, 6)):
|
||||
r = rng.random()
|
||||
if r < 0.3:
|
||||
ops.append(['title', rng.choice(TITLES)])
|
||||
elif r < 0.45:
|
||||
ops.append(['subtitle', rng.choice(TITLES)])
|
||||
elif r < 0.6:
|
||||
ops.append(['times', rng.choice([-1, 0, 1, 5, 10, 20]), rng.choice([-1, 0, 3, 40, 70]), rng.choice([-1, 0, 1, 7, 20])])
|
||||
elif r < 0.65:
|
||||
ops.append(['clear'])
|
||||
elif r < 0.7:
|
||||
ops.append(['reset'])
|
||||
elif r < 0.85:
|
||||
ops.append(['overlay', rng.choice(TITLES), rng.random() < 0.3])
|
||||
ops.append(['tick', rng.choice([0, 0, 1, 2, 5, 9, 10, 11, 30, 50, 59, 60, 79, 80, 81, 99, 100, rng.randint(0, 120)])])
|
||||
return {**screen(rng), **backdrop(rng), 'partial': round(rng.random(), 3), 'ops': ops}
|
||||
|
||||
|
||||
# Items for the selected item name: id, translation key and rarity colour (checked by the oracle's own stacks).
|
||||
HELD = [('stone', 'block.minecraft.stone', 'white'), ('diamond_sword', 'item.minecraft.diamond_sword', 'white'),
|
||||
('totem_of_undying', 'item.minecraft.totem_of_undying', 'yellow'), ('beacon', 'block.minecraft.beacon', 'aqua'),
|
||||
('dragon_egg', 'block.minecraft.dragon_egg', 'light_purple'), ('apple', 'item.minecraft.apple', 'white')]
|
||||
CUSTOM = [None, None, None, {'text': 'Excalibur'}, {'text': 'Red', 'color': 'red'}, {'text': 'Plain', 'italic': False}]
|
||||
|
||||
|
||||
def selected(rng, n):
|
||||
"""Selected-slot changes tick by tick, then the name with its fade."""
|
||||
def stack():
|
||||
item, key, rarity = rng.choice(HELD)
|
||||
return {'item': item, 'key': key, 'rarity': rarity, 'custom': rng.choice(CUSTOM)}
|
||||
steps, held = [], stack()
|
||||
for _ in range(rng.randint(1, 60)):
|
||||
if rng.random() < 0.1:
|
||||
if rng.random() < 0.2:
|
||||
held = None
|
||||
else:
|
||||
held = stack()
|
||||
steps.append(held)
|
||||
return {**screen(rng), **backdrop(rng), 'gameMode': rng.choice(['survival', 'adventure', 'creative']),
|
||||
'displayTime': rng.choice([1.0, 1.0, 0.5, 2.0, 0.123]), 'steps': steps}
|
||||
|
||||
|
||||
|
||||
def boss(rng, n):
|
||||
bars = []
|
||||
for _ in range(rng.choice([1, 1, 2, 3, 5, 9])):
|
||||
progress = rng.choice([0.0, 1.0, 0.5, 0.001, 0.999, 1 / 182, round(rng.random(), 4)])
|
||||
bars.append({'name': rng.choice(TITLES), 'progress': progress, 'color': rng.randrange(7), 'overlay': rng.randrange(5)})
|
||||
return {**screen(rng), 'bars': bars}
|
||||
|
||||
|
||||
def jump(rng, n):
|
||||
return {**screen(rng), 'cooldown': rng.choice([0, 0, 0, 1, 10]),
|
||||
'jumpScale': rng.choice([0.0, 1.0, 0.4, 0.001, round(rng.random(), 4)])}
|
||||
|
||||
|
||||
OWNERS = ['Alex', 'steve', 'Zed', 'bob', 'Bobby', 'ÉLodie', 'élan', '#hidden', 'x', 'LongPlayerName_123', 'Mia', '_under']
|
||||
FORMATS = [None, None, None, {'type': 'blank'}, {'type': 'fixed', 'value': {'text': 'FIX', 'color': 'aqua'}},
|
||||
{'type': 'styled', 'style': {'color': 'gold', 'bold': True}}, {'type': 'styled', 'style': {}}]
|
||||
|
||||
|
||||
def sidebar(rng, n):
|
||||
"""An objective with scores, display names, number formats and teams."""
|
||||
owners = rng.sample(OWNERS, rng.randint(0, len(OWNERS)))
|
||||
if rng.random() < 0.3: # more rows than the 15 shown
|
||||
owners += [f'p{i}' for i in range(rng.randint(5, 20))]
|
||||
scores = [{'owner': o, 'value': rng.choice([0, 1, -1, 7, 7, 100, 2147483647, -2147483648, rng.randint(-50, 50)]),
|
||||
'display': rng.choice([None, None, None, {'text': 'Shown ' + o, 'color': 'green'}]),
|
||||
'format': rng.choice(FORMATS)} for o in owners]
|
||||
teams = []
|
||||
for t in range(rng.choice([0, 0, 1, 2])):
|
||||
teams.append({'name': f'team{t}', 'prefix': rng.choice([{'text': ''}, {'text': '[A] '}, {'text': '<', 'color': 'red'}]),
|
||||
'suffix': rng.choice([{'text': ''}, {'text': ' *'}]),
|
||||
'color': rng.choice([None, 'red', 'blue', 'gold', 'white']),
|
||||
'members': [o for o in owners if rng.random() < 0.3]})
|
||||
return {**screen(rng), **backdrop(rng),
|
||||
'objective': {'display': rng.choice(TITLES + [{'text': 'Kills'}]), 'format': rng.choice(FORMATS)},
|
||||
'scores': scores, 'teams': teams}
|
||||
|
||||
|
||||
|
||||
# Items for the decorations: id and max damage (0 = not damageable), checked by the oracle's own stacks.
|
||||
DECOR_ITEMS = [('diamond_sword', 1561), ('bow', 384), ('shield', 336), ('flint_and_steel', 64), ('elytra', 432),
|
||||
('stone', 0), ('ender_pearl', 0), ('apple', 0)]
|
||||
|
||||
|
||||
def decor(rng, n):
|
||||
"""GuiGraphicsExtractor.itemDecorations: count, durability bar and cooldown shade."""
|
||||
item, max_damage = rng.choice(DECOR_ITEMS)
|
||||
case = {'x': rng.randint(-20, 400), 'y': rng.randint(-20, 300), 'item': item, 'maxDamage': max_damage,
|
||||
'count': rng.choice([1, 1, 2, 16, 64, 99, 0, 10, 127]),
|
||||
'damage': rng.choice([0, 0, 1, max_damage // 2, max_damage - 1, max_damage, rng.randint(0, max(max_damage, 1))]) if max_damage else 0,
|
||||
'unbreakable': rng.random() < 0.1, 'partial': round(rng.random(), 3)}
|
||||
if rng.random() < 0.4:
|
||||
duration = rng.choice([1, 2, 7, 20, 100, 200])
|
||||
case['cooldown'] = {'duration': duration, 'elapsed': rng.choice([0, 1, duration - 1, duration, rng.randint(0, duration)])}
|
||||
if rng.random() < 0.1:
|
||||
case['countText'] = rng.choice(['', '+', '1/2', 'x9'])
|
||||
return case
|
||||
|
||||
|
||||
|
||||
def overlays(rng, n):
|
||||
"""Camera overlays (vignette and border warning, spyglass, pumpkin, powder snow, portal, nausea) and sleep."""
|
||||
case = {**screen(rng), 'vignette': rng.random() < 0.7,
|
||||
'vignetteBrightness': rng.choice([1.0, 0.0, 0.5, round(rng.random(), 4), 1.3, -0.2]),
|
||||
'firstPerson': rng.random() < 0.8, 'scoping': rng.random() < 0.2,
|
||||
'scopeScale': rng.choice([0.5, 1.125, round(rng.uniform(0.5, 1.125), 4)]), 'partial': round(rng.random(), 3),
|
||||
'head': rng.choice([None, None, 'carved_pumpkin', 'diamond_helmet']),
|
||||
'ticksFrozen': rng.choice([0, 0, 0, 1, 70, 139, 140, 300]),
|
||||
'portal': rng.choice([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0125], [0.5, 0.5125], [1.0, 1.0], [0.05, 0.0], [round(rng.random(), 3)] * 2]),
|
||||
'nausea': rng.choice([0.0, 0.0, 1.0, 0.25, round(rng.random(), 3)]),
|
||||
'screenEffectScale': rng.choice([1.0, 0.0, 0.5, round(rng.random(), 3)]),
|
||||
'sleepTimer': rng.choice([0, 0, 0, 1, 50, 100, 101, 105, 110, 111])}
|
||||
if rng.random() < 0.4:
|
||||
size = rng.choice([10.0, 50.0, 200.0, 1000.0])
|
||||
case['border'] = {'centerX': rng.choice([0.0, 100.5]), 'centerZ': rng.choice([0.0, -30.25]), 'size': size,
|
||||
'warningBlocks': rng.choice([0, 5, 20, 100]), 'warningTime': rng.choice([0, 15])}
|
||||
case['camX'] = round(rng.uniform(-150, 250), 2)
|
||||
case['camZ'] = round(rng.uniform(-150, 150), 2)
|
||||
return case
|
||||
|
||||
|
||||
|
||||
WORDS = ['hello', 'world', 'a', 'Minecraft', 'supercalifragilisticexpialidocious', 'x' * 70, 'ok!', 'Ünïcödé', '★', '']
|
||||
|
||||
|
||||
def chat_text(rng):
|
||||
words = [rng.choice(WORDS) for _ in range(rng.choice([1, 2, 5, 12, 30]))]
|
||||
text = rng.choice([' ', ' ', ' ', ' ', '\n']).join(words)
|
||||
if rng.random() < 0.1:
|
||||
text = rng.choice([' ', '\n']) + text + rng.choice(['', ' ', '\n'])
|
||||
if rng.random() < 0.3:
|
||||
cut = rng.randint(0, len(text))
|
||||
return [{'text': text[:cut], 'color': rng.choice(['red', 'gold', 'aqua'])},
|
||||
{'text': text[cut:], 'bold': rng.random() < 0.5, 'italic': rng.random() < 0.3}]
|
||||
return {'text': text}
|
||||
|
||||
|
||||
def chat(rng, n):
|
||||
"""Messages wrapped to the chat width and fading 200 ticks after they arrive."""
|
||||
count = rng.choice([1, 2, 5, 10, 30, 120])
|
||||
now = rng.randint(200, 2000)
|
||||
messages = []
|
||||
for _ in range(count):
|
||||
at = rng.choice([now, now - 1, now - 179, now - 180, now - 190, now - 199, now - 200, now - 500, rng.randint(now - 260, now + 5)])
|
||||
messages.append({'text': chat_text(rng), 'at': at, 'tag': rng.choice([None, None, 'system', 'error'])})
|
||||
messages.sort(key=lambda m: m['at'])
|
||||
return {**screen(rng), 'now': now, 'messages': messages,
|
||||
'chatScale': rng.choice([1.0, 1.0, 0.5, 0.0 + 0.75, 0.25]), 'chatWidth': rng.choice([1.0, 1.0, 0.5, 0.0, 0.3]),
|
||||
'chatOpacity': rng.choice([1.0, 0.5, 0.0, 0.25]), 'textOpacity': rng.choice([0.5, 0.0, 1.0, 0.25]),
|
||||
'chatLineSpacing': rng.choice([0.0, 0.0, 0.5, 1.0, 0.25]), 'chatHeightUnfocused': rng.choice([70 / 160, 1.0, 0.0, 0.5]),
|
||||
'chatHeightFocused': 1.0}
|
||||
|
||||
|
||||
# Generators by kind: (rng, index) -> case. Cases are drawn round-robin.
|
||||
KINDS = {
|
||||
'decorations': decorations,
|
||||
'effects': effects,
|
||||
'title': title,
|
||||
'selected': selected,
|
||||
'boss': boss,
|
||||
'jump': jump,
|
||||
'sidebar': sidebar,
|
||||
'decor': decor,
|
||||
'overlays': overlays,
|
||||
'chat': chat,
|
||||
}
|
||||
+705
-86
@@ -59,11 +59,44 @@ SHIM = STATE_DIR / "shim"
|
||||
# so a harness whose inputs match one that passed elsewhere doesn't run again.
|
||||
SHARED = Path(os.environ.get("PARITY_SHARED") or (LOCAL / "minecraft").resolve().parent / "parity-shared")
|
||||
MACHINE_JOBS = int(os.environ.get("PARITY_MACHINE_JOBS") or max(1, (os.cpu_count() or 4) // 2))
|
||||
HOST = os.uname().nodename.split(".")[0]
|
||||
DEFAULT_MEMORY = 3 << 30 # assumed peak for a harness that never ran here
|
||||
|
||||
|
||||
def harness_settings(path):
|
||||
"""PARITY_SHARDS and PARITY_RUST_SCOPE, read from a harness's source without running it."""
|
||||
import ast
|
||||
text = Path(path).read_text()
|
||||
settings = {}
|
||||
if "PARITY_" in text:
|
||||
for node in ast.parse(text).body:
|
||||
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) \
|
||||
and node.targets[0].id in ("PARITY_SHARDS", "PARITY_RUST_SCOPE"):
|
||||
settings[node.targets[0].id] = ast.literal_eval(node.value)
|
||||
return settings
|
||||
|
||||
|
||||
SHARDS = {} # "datafix#2" -> "2/8": the share of a sharded harness each entry runs (PARITY_SHARD)
|
||||
|
||||
|
||||
def harnesses():
|
||||
return {path.name[len("test_"):-len("_parity.py")]: path for path in sorted((ROOT / "tools").glob("test_*_parity.py"))}
|
||||
"""Harness names and scripts. A harness declaring PARITY_SHARDS = N runs as N entries, NAME#1 to NAME#N."""
|
||||
found = {}
|
||||
for path in sorted((ROOT / "tools").glob("test_*_parity.py")):
|
||||
name = path.name[len("test_"):-len("_parity.py")]
|
||||
count = harness_settings(path).get("PARITY_SHARDS", 1)
|
||||
if count > 1:
|
||||
for index in range(1, count + 1):
|
||||
found[f"{name}#{index}"] = path
|
||||
SHARDS[f"{name}#{index}"] = f"{index}/{count}"
|
||||
else:
|
||||
found[name] = path
|
||||
return found
|
||||
|
||||
|
||||
def base_name(name):
|
||||
"""The harness a shard belongs to: datafix#2 -> datafix."""
|
||||
return name.split("#")[0]
|
||||
|
||||
|
||||
def load_state():
|
||||
@@ -84,20 +117,47 @@ class Hasher:
|
||||
self.cache = cache
|
||||
|
||||
def __call__(self, path):
|
||||
real, _, keep = str(path).partition(KEEP)
|
||||
try:
|
||||
stat = os.stat(path)
|
||||
stat = os.stat(real)
|
||||
except FileNotFoundError:
|
||||
return "missing"
|
||||
stamp = [stat.st_size, stat.st_mtime_ns]
|
||||
cached = self.cache.get(str(path))
|
||||
if cached and cached[0] == stamp:
|
||||
return cached[1]
|
||||
with open(path, "rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if keep:
|
||||
digest = hashlib.sha256(crate_root_without_modules(Path(real).read_text(), set(keep.split(","))).encode()).hexdigest()
|
||||
else:
|
||||
with open(real, "rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
self.cache[str(path)] = [stamp, digest]
|
||||
return digest
|
||||
|
||||
|
||||
# A narrowed crate root: "crates/c/src/lib.rs#keep:a,b" stands for lib.rs without its
|
||||
# declarations of modules other than a and b (see narrow_rust_sources).
|
||||
KEEP = "#keep:"
|
||||
MODULE_DECLARATION = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;\s*$")
|
||||
|
||||
|
||||
def crate_root_without_modules(text, keep):
|
||||
"""A crate root's text without the `mod x;` lines (and their attributes and doc comments) for modules not in keep."""
|
||||
lines, pending = [], []
|
||||
for line in text.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith(("#[", "///", "//!")) and not stripped.startswith("#!["):
|
||||
pending.append(line)
|
||||
continue
|
||||
declared = MODULE_DECLARATION.match(line)
|
||||
if declared and declared.group(1) not in keep:
|
||||
pending = []
|
||||
continue
|
||||
lines += pending + [line]
|
||||
pending = []
|
||||
return "\n".join(lines + pending)
|
||||
|
||||
|
||||
def environment_key(hasher):
|
||||
"""Everything outside the recorded dependencies that can change a result."""
|
||||
def version(command):
|
||||
@@ -161,8 +221,225 @@ def artifacts_of(arguments):
|
||||
return found
|
||||
|
||||
|
||||
def dependencies(trace):
|
||||
"""Repository files a traced harness depended on, relative to ROOT."""
|
||||
RUST_PATH = re.compile(r"(?<![\w:])((?:crate|self|super)(?:::super)*|[a-z_][a-z0-9_]*)::((?:[A-Za-z_]\w*::)*[A-Za-z_]\w*)")
|
||||
RUST_TYPE = re.compile(r"\b(?:struct|enum|trait|union|type)\s+([A-Za-z_]\w*)")
|
||||
RUST_MACRO_USE = re.compile(r"\b([A-Za-z_]\w*)!\s*[(\[{]")
|
||||
RUST_MACRO_DEFINITION = re.compile(r"macro_rules!\s+([A-Za-z_]\w*)")
|
||||
|
||||
|
||||
RUST_LITERAL_START = re.compile(r"//|/\*|(?<![\w])b?r#*\"|\"|'")
|
||||
RUST_CODE_CACHE = {}
|
||||
|
||||
|
||||
def rust_code(text):
|
||||
"""Rust source with comments, string and character literals blanked out (newlines kept)."""
|
||||
cached = RUST_CODE_CACHE.get(text)
|
||||
if cached is not None:
|
||||
return cached
|
||||
out, i, n = [], 0, len(text)
|
||||
def blank(chunk):
|
||||
return re.sub(r"[^\n]", " ", chunk)
|
||||
while i < n:
|
||||
match = RUST_LITERAL_START.search(text, i)
|
||||
if not match:
|
||||
out.append(text[i:])
|
||||
break
|
||||
out.append(text[i:match.start()])
|
||||
i, token = match.start(), match.group()
|
||||
if token == "//":
|
||||
end = text.find("\n", i)
|
||||
end = n if end < 0 else end
|
||||
elif token == "/*":
|
||||
depth, end = 1, i + 2
|
||||
while end < n and depth:
|
||||
nested = re.compile(r"/\*|\*/").search(text, end)
|
||||
if not nested:
|
||||
end = n
|
||||
break
|
||||
depth += 1 if nested.group() == "/*" else -1
|
||||
end = nested.end()
|
||||
elif token.endswith('"') and "r" in token:
|
||||
closing = '"' + "#" * token.count("#")
|
||||
end = text.find(closing, match.end())
|
||||
end = n if end < 0 else end + len(closing)
|
||||
elif token == '"':
|
||||
literal = re.compile(r'"(?:\\.|[^"\\])*"', re.DOTALL).match(text, i)
|
||||
end = literal.end() if literal else n
|
||||
else: # ' starts a character literal or a lifetime
|
||||
literal = re.compile(r"'(?:\\(?:u\{[0-9a-fA-F]*\}|x..|.)|[^\\'\n])'").match(text, i)
|
||||
if not literal:
|
||||
out.append("'")
|
||||
i += 1
|
||||
continue
|
||||
end = literal.end()
|
||||
out.append(blank(text[i:end]))
|
||||
i = end
|
||||
result = "".join(out)
|
||||
RUST_CODE_CACHE[text] = result
|
||||
return result
|
||||
|
||||
|
||||
def inline_modules(code):
|
||||
"""For blanked Rust code: a function giving the inline modules (`mod x { }`) open at an offset."""
|
||||
import bisect
|
||||
marks, stack, depth = [0], [], 0
|
||||
states = [()]
|
||||
opening = {match.end() - 1: match.group(1) for match in re.finditer(r"\bmod\s+(\w+)\s*\{", code)}
|
||||
for index, c in enumerate(code):
|
||||
if c == "{":
|
||||
depth += 1
|
||||
if index in opening:
|
||||
stack.append((opening[index], depth))
|
||||
marks.append(index); states.append(tuple(name for name, _ in stack))
|
||||
elif c == "}":
|
||||
if stack and stack[-1][1] == depth:
|
||||
stack.pop()
|
||||
marks.append(index); states.append(tuple(name for name, _ in stack))
|
||||
depth -= 1
|
||||
return lambda offset: list(states[bisect.bisect_right(marks, offset) - 1])
|
||||
|
||||
|
||||
def impl_targets(header, text, workspace):
|
||||
"""Names an impl header (after `impl`) may implement for or with that could be the scope's own types.
|
||||
|
||||
Only the trait and the self type count, by their last path segment; a path
|
||||
starting with an external crate (std::error::Error) can't name a scope type,
|
||||
nor can a bare name the file imports from an external crate or defines itself."""
|
||||
header = re.split(r"\bwhere\b", header)[0].strip().replace("->", " ")
|
||||
parameters = set()
|
||||
if header.startswith("<"): # generic parameters
|
||||
depth, start = 0, 1
|
||||
for index, c in enumerate(header):
|
||||
if depth == 1 and c in ",>":
|
||||
parameter = re.match(r"\s*(?:const\s+)?([A-Za-z_]\w*)", header[start:index])
|
||||
if parameter:
|
||||
parameters.add(parameter.group(1))
|
||||
start = index + 1
|
||||
depth += c == "<"
|
||||
depth -= c == ">"
|
||||
if depth == 0:
|
||||
header = header[index + 1:]
|
||||
break
|
||||
names = set()
|
||||
for part in re.split(r"\bfor\b", header, maxsplit=1):
|
||||
path = re.sub(r"<.*", "", part.strip().lstrip("!&").replace("dyn ", "").strip(), flags=re.DOTALL).strip()
|
||||
segments = [segment for segment in path.split("::") if segment]
|
||||
if not segments:
|
||||
continue
|
||||
head, last = segments[0], segments[-1]
|
||||
if not re.fullmatch(r"[A-Za-z_]\w*", last):
|
||||
names.update(set(re.findall(r"[A-Za-z_]\w*", part)) - {"mut", "const"}) # a tuple, slice or pointer type
|
||||
continue
|
||||
if len(segments) > 1 and head not in ("crate", "self", "super") and head not in workspace:
|
||||
continue # qualified by an external crate
|
||||
if len(segments) == 1:
|
||||
if re.search(rf"\b(?:struct|enum|trait|union)\s+{last}\b", text):
|
||||
continue # defined in this file (an import of the same name would not compile)
|
||||
imported = re.search(rf"\buse\s+(\w+)[^;]*\b{last}\b[^;]*;", text)
|
||||
if imported and imported.group(1) not in ("crate", "self", "super", *workspace):
|
||||
continue # imported from an external crate
|
||||
names.add(last)
|
||||
return names - parameters
|
||||
|
||||
|
||||
def narrow_rust_sources(sources, scope):
|
||||
"""Drop the workspace Rust sources a harness's declared PARITY_RUST_SCOPE proves it can't reach.
|
||||
|
||||
The scope lists source prefixes (crates/horizon-world/src/nbt.rs,
|
||||
crates/horizon-world/src/datafix/). It applies only if it is closed: no
|
||||
file in it names a module, crate item or macro outside it (crate::,
|
||||
super::, other workspace crates), declares a module it doesn't cover, or
|
||||
includes source; and no file outside it implements anything for a type
|
||||
it defines. Crate roots stay as dependencies without their declarations
|
||||
of unreachable modules, so adding a module elsewhere doesn't count.
|
||||
Probe entry points (examples, bins) are always kept. Returns the kept
|
||||
sources and None, or all of them and the reason the scope isn't closed."""
|
||||
crates = {path.parent.name.replace("-", "_"): path.parent for path in (ROOT / "crates").glob("*/Cargo.toml")}
|
||||
def scoped(path):
|
||||
return any(path == prefix or (prefix.endswith("/") and path.startswith(prefix)) for prefix in scope)
|
||||
rust = [path for path in sources if path.startswith("crates/") and path.endswith(".rs")]
|
||||
entry = [path for path in rust if "/examples/" in path or "/src/bin/" in path or path.endswith("/src/main.rs")]
|
||||
inner = [path for path in rust if scoped(path)]
|
||||
outside = [path for path in rust if path not in inner and path not in entry
|
||||
and not path.endswith("/src/lib.rs")]
|
||||
|
||||
def module_file(crate_dir, parts):
|
||||
"""The file of the deepest module named by parts, and how many parts it covers."""
|
||||
for count in range(len(parts), 0, -1):
|
||||
for candidate in (crate_dir / "src" / Path(*parts[:count - 1]) / f"{parts[count - 1]}.rs",
|
||||
crate_dir / "src" / Path(*parts[:count]) / "mod.rs"):
|
||||
if candidate.is_file():
|
||||
return str(candidate.relative_to(ROOT)), count
|
||||
return None, 0
|
||||
|
||||
def module_path(path):
|
||||
parts = list(Path(*Path(path).parts[3:]).with_suffix("").parts) # crates/<crate>/src/...
|
||||
return parts[:-1] if parts[-1] in ("mod", "lib") else parts
|
||||
|
||||
defined_types, used_macros, kept_modules = set(), set(), {}
|
||||
for path in inner + entry:
|
||||
text = rust_code((ROOT / path).read_text(errors="replace"))
|
||||
crate_name = Path(path).parts[1].replace("-", "_")
|
||||
nesting = inline_modules(text)
|
||||
if re.search(r"\binclude!\s*\(", text):
|
||||
return sources, f"{path} includes source"
|
||||
used_macros.update(RUST_MACRO_USE.findall(text))
|
||||
if path in inner:
|
||||
defined_types.update(RUST_TYPE.findall(text))
|
||||
kept_modules.setdefault(crate_name, set()).add(module_path(path)[0] if module_path(path) else "")
|
||||
for line in text.splitlines():
|
||||
declared = MODULE_DECLARATION.match(line)
|
||||
if declared:
|
||||
child, _ = module_file(crates[crate_name], module_path(path) + [declared.group(1)])
|
||||
if child and not scoped(child):
|
||||
return sources, f"{path} declares module {declared.group(1)} outside the scope"
|
||||
for match in RUST_PATH.finditer(text):
|
||||
head, rest = match.groups()
|
||||
parts = rest.split("::")
|
||||
if head in crates: # a workspace crate
|
||||
base, crate_name = [], head
|
||||
elif head.startswith(("crate", "self", "super")) and path in inner:
|
||||
own, crate_name = module_path(path) + nesting(match.start()), Path(path).parts[1].replace("-", "_")
|
||||
ups = head.count("super")
|
||||
if head != "crate" and ups <= len(nesting(match.start())):
|
||||
continue # within this file
|
||||
base = [] if head == "crate" else own[:len(own) - ups]
|
||||
else:
|
||||
continue # an external crate, a local name or a probe's own module
|
||||
target, covered = module_file(crates[crate_name], base + parts)
|
||||
if target is None:
|
||||
# An item of the crate root: fine if defined there (the narrowed root keeps it), not if re-exported.
|
||||
root = crates[crate_name] / "src" / "lib.rs"
|
||||
item = (base + parts)[0]
|
||||
defined_in_root = root.is_file() and re.search(
|
||||
rf"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const|static|fn|struct|enum|type|trait|union)\s+{item}\b",
|
||||
root.read_text(), re.MULTILINE)
|
||||
if not defined_in_root:
|
||||
return sources, f"{path} names {head}::{rest}, which the crate root doesn't define itself"
|
||||
continue
|
||||
if not scoped(target):
|
||||
return sources, f"{path} names {head}::{rest} ({target})"
|
||||
for path in outside:
|
||||
text = rust_code((ROOT / path).read_text(errors="replace"))
|
||||
defined = set(RUST_MACRO_DEFINITION.findall(text)) & used_macros
|
||||
if defined:
|
||||
return sources, f"the scope uses macro {sorted(defined)[0]}! defined in {path}"
|
||||
for header in re.findall(r"^\s*(?:unsafe\s+)?impl\b([^;{]*)", text, re.MULTILINE):
|
||||
touched = impl_targets(header, text, set(crates)) & defined_types
|
||||
if touched:
|
||||
return sources, f"{path} implements something for {sorted(touched)[0]}, defined in the scope"
|
||||
kept = [path for path in sources if path not in outside and not path.endswith("/src/lib.rs")]
|
||||
for path in sources:
|
||||
if path.endswith("/src/lib.rs"):
|
||||
modules = kept_modules.get(Path(path).parts[1].replace("-", "_")) or {"-"} # "-": no module of it is reachable
|
||||
kept.append(f"{path}{KEEP}{','.join(sorted(modules))}")
|
||||
return sorted(kept), None
|
||||
|
||||
|
||||
def dependencies(trace, scope=None):
|
||||
"""Repository files a traced harness depended on, relative to ROOT, and the probes it built.
|
||||
|
||||
With a PARITY_RUST_SCOPE, Rust sources it can't reach are left out (see narrow_rust_sources)."""
|
||||
found = set(trace["modules"])
|
||||
found.update(trace["read"])
|
||||
artifacts = []
|
||||
@@ -182,13 +459,17 @@ def dependencies(trace):
|
||||
kept = set()
|
||||
for path in found:
|
||||
path = Path(path) if os.path.isabs(path) else ROOT / path
|
||||
if inside(path, ROOT) and not inside(path, LOCAL) and not inside(path, ROOT / "target") and path.is_file():
|
||||
if inside(path, ROOT) and not inside(path, LOCAL) and not inside(path, ROOT / "target") and path.is_file() \
|
||||
and "__pycache__" not in path.parts: # bytecode caches vary; their sources are dependencies already
|
||||
kept.add(str(path.resolve().relative_to(ROOT)))
|
||||
unique = []
|
||||
for artifact in artifacts:
|
||||
if artifact not in unique:
|
||||
unique.append(artifact)
|
||||
return sorted(kept), unique
|
||||
kept, note = narrow_rust_sources(sorted(kept), scope) if scope else (sorted(kept), None)
|
||||
if note:
|
||||
print(f"note: PARITY_RUST_SCOPE not applied: {note}", flush=True)
|
||||
return kept, unique
|
||||
|
||||
|
||||
def java_sources(arguments):
|
||||
@@ -221,6 +502,16 @@ def run_environment(reuse_oracles=False):
|
||||
return environment
|
||||
|
||||
|
||||
def default_build_jobs():
|
||||
"""Cargo jobs for the probe build: PARITY_BUILD_JOBS, else every thread, within $FLEET_LOAD_JOBS when set."""
|
||||
if os.environ.get("PARITY_BUILD_JOBS"):
|
||||
return int(os.environ["PARITY_BUILD_JOBS"])
|
||||
jobs = os.cpu_count() or 8
|
||||
if os.environ.get("FLEET_LOAD_JOBS", "").isdigit():
|
||||
jobs = min(jobs, max(1, int(os.environ["FLEET_LOAD_JOBS"])))
|
||||
return jobs
|
||||
|
||||
|
||||
def prebuild(artifacts, jobs):
|
||||
"""Build every recorded probe in one Cargo run so harnesses don't serialise on its lock."""
|
||||
environment = run_environment()
|
||||
@@ -304,92 +595,389 @@ def machine_slot():
|
||||
|
||||
|
||||
def memory_available():
|
||||
for line in Path("/proc/meminfo").read_text().splitlines():
|
||||
if line.startswith("MemAvailable:"):
|
||||
return int(line.split()[1]) * 1024
|
||||
return 16 << 30
|
||||
"""Bytes the system can give harnesses now: MemAvailable on Linux, free and reclaimable pages on macOS."""
|
||||
meminfo = Path("/proc/meminfo")
|
||||
if meminfo.exists():
|
||||
for line in meminfo.read_text().splitlines():
|
||||
if line.startswith("MemAvailable:"):
|
||||
return int(line.split()[1]) * 1024
|
||||
try:
|
||||
text = subprocess.run(["vm_stat"], capture_output=True, text=True).stdout
|
||||
page = int(re.search(r"page size of (\d+) bytes", text).group(1))
|
||||
pages = sum(int(re.search(rf"^{label}:\s+(\d+)", text, re.MULTILINE).group(1))
|
||||
for label in ("Pages free", "Pages inactive", "Pages speculative", "Pages purgeable"))
|
||||
return pages * page
|
||||
except (OSError, AttributeError, ValueError):
|
||||
return 16 << 30
|
||||
|
||||
|
||||
def run(selected, state, hasher, environment_digest, jobs, timeout, memory_budget, reuse_oracles):
|
||||
logs = STATE_DIR / "logs"
|
||||
traces = STATE_DIR / "traces"
|
||||
logs.mkdir(parents=True, exist_ok=True)
|
||||
traces.mkdir(parents=True, exist_ok=True)
|
||||
records = state["harnesses"]
|
||||
# Longest first, so the slow harnesses don't start last.
|
||||
queue = sorted(selected, key=lambda name: -records.get(name, {}).get("seconds", 1e9))
|
||||
running = {}
|
||||
results = {}
|
||||
retried = set()
|
||||
started_all = time.monotonic()
|
||||
while queue or running:
|
||||
in_use = sum(item[3] for item in running.values())
|
||||
for name in list(queue):
|
||||
if len(running) >= jobs:
|
||||
break
|
||||
expected = records.get(name, {}).get("peak_bytes", DEFAULT_MEMORY)
|
||||
if running and in_use + expected > memory_budget:
|
||||
continue
|
||||
slot = machine_slot()
|
||||
if slot is None:
|
||||
break # other runners on this machine hold every slot
|
||||
queue.remove(name)
|
||||
reuse = reuse_oracles and records.get(name, {}).get("oracle_reuse", True) and name not in retried
|
||||
trace = traces / f"{name}.json"
|
||||
trace.unlink(missing_ok=True)
|
||||
log = (logs / f"{name}.log").open("w")
|
||||
environment = run_environment(reuse)
|
||||
environment["PARITY_SHIM_OUTPUTS"] = str(outputs_listing(name, fresh=True))
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, str(Path(__file__)), "--trace", str(trace), str(selected[name])],
|
||||
cwd=ROOT, env=environment, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
running[name] = (process, time.monotonic(), log, expected, reuse, slot)
|
||||
in_use += expected
|
||||
time.sleep(0.2)
|
||||
for name, (process, started, log, _, reused, slot) in list(running.items()):
|
||||
elapsed = time.monotonic() - started
|
||||
if process.poll() is None and elapsed < timeout:
|
||||
REMOTE_LOCAL_JOBS = 3 # harnesses at once here while other machines take the rest
|
||||
REMOTE_LOCAL_PEAK = 800 << 20 # heavier harnesses are left to them
|
||||
MEMORY_RESERVE = 2 << 30 # what admission leaves free here, for the person at the screen
|
||||
|
||||
|
||||
def default_local_jobs(remote=False):
|
||||
"""Harnesses at once on this machine: PARITY_LOCAL_JOBS, else a third of its threads (3 when other machines
|
||||
help), within the fleet's budget ($FLEET_LOAD_JOBS)."""
|
||||
if os.environ.get("PARITY_LOCAL_JOBS"):
|
||||
return int(os.environ["PARITY_LOCAL_JOBS"])
|
||||
jobs = REMOTE_LOCAL_JOBS if remote else max(1, (os.cpu_count() or 4) // 3)
|
||||
if os.environ.get("FLEET_LOAD_JOBS", "").isdigit():
|
||||
jobs = min(jobs, max(1, int(os.environ["FLEET_LOAD_JOBS"])))
|
||||
return jobs
|
||||
|
||||
|
||||
def outcome(name, script, passed, elapsed, trace_path, hasher=None):
|
||||
"""The record of a finished harness, from its trace. With a hasher, also the content hash of each dependency."""
|
||||
record = {"status": "pass" if passed else "fail", "seconds": round(elapsed, 1),
|
||||
"finished": time.strftime("%Y-%m-%dT%H:%M:%S"), "host": HOST}
|
||||
try:
|
||||
trace = json.loads(Path(trace_path).read_text())
|
||||
except (OSError, ValueError):
|
||||
trace = None # killed before writing it, or the disk was full: the pass can't be keyed
|
||||
if trace:
|
||||
record["dependencies"], record["artifacts"] = dependencies(trace, harness_settings(script).get("PARITY_RUST_SCOPE"))
|
||||
record["peak_bytes"] = trace["peak_bytes"]
|
||||
if passed:
|
||||
clear_large_outputs(name, trace)
|
||||
if hasher is not None:
|
||||
record["hashes"] = {path: hasher(ROOT / path) for path in record["dependencies"]}
|
||||
else:
|
||||
record["dependencies"], record["artifacts"] = [], []
|
||||
return record
|
||||
|
||||
|
||||
class LocalExecutor:
|
||||
"""Runs harnesses on this machine, within its job count, memory budget and the machine-wide slots."""
|
||||
|
||||
def __init__(self, jobs, memory_budget, timeout, max_peak=None):
|
||||
self.name, self.jobs, self.memory_budget, self.timeout = HOST, jobs, memory_budget, timeout
|
||||
self.max_peak = max_peak # set while other machines can take heavier harnesses
|
||||
self.running = {}
|
||||
self.available, self.measured = 0, 0.0
|
||||
(STATE_DIR / "logs").mkdir(parents=True, exist_ok=True)
|
||||
(STATE_DIR / "traces").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def free(self):
|
||||
return self.jobs - len(self.running)
|
||||
|
||||
def accepts(self, name):
|
||||
return True
|
||||
|
||||
def fits(self, expected, only_here=True):
|
||||
"""Admission by recorded peak, within the budget and leaving MEMORY_RESERVE of what is free now.
|
||||
only_here: no other machine can take this harness."""
|
||||
if self.max_peak is not None and expected > self.max_peak and not only_here:
|
||||
return False
|
||||
if time.monotonic() - self.measured > 1:
|
||||
self.available, self.measured = memory_available(), time.monotonic()
|
||||
if not self.running and (self.max_peak is None or only_here):
|
||||
return True # alone, it must run anyway
|
||||
return sum(item["expected"] for item in self.running.values()) + expected <= self.memory_budget \
|
||||
and self.available - expected >= MEMORY_RESERVE
|
||||
|
||||
def start(self, name, script, reuse, expected, shard=None):
|
||||
self.measured = 0.0 # measure again before the next start
|
||||
slot = machine_slot()
|
||||
if slot is None:
|
||||
return False # other runners on this machine hold every slot
|
||||
trace = STATE_DIR / "traces" / f"{name}.json"
|
||||
trace.unlink(missing_ok=True)
|
||||
log = (STATE_DIR / "logs" / f"{name}.log").open("w")
|
||||
environment = run_environment(reuse)
|
||||
environment["PARITY_SHIM_OUTPUTS"] = str(outputs_listing(name, fresh=True))
|
||||
environment.pop("PARITY_SHARD", None)
|
||||
if shard:
|
||||
environment["PARITY_SHARD"] = shard
|
||||
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)
|
||||
self.running[name] = {"process": process, "started": time.monotonic(), "log": log, "expected": expected,
|
||||
"slot": slot, "script": script}
|
||||
return True
|
||||
|
||||
def poll(self):
|
||||
"""(name, script, passed, seconds, trace path) of each harness that finished or timed out."""
|
||||
finished = []
|
||||
for name, item in list(self.running.items()):
|
||||
process, elapsed = item["process"], time.monotonic() - item["started"]
|
||||
if process.poll() is None and elapsed < self.timeout:
|
||||
continue
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, 9)
|
||||
process.wait()
|
||||
print(f"--- {name}: timed out after {timeout}s", file=log)
|
||||
log.close()
|
||||
slot.close()
|
||||
del running[name]
|
||||
passed = process.returncode == 0
|
||||
print(f"--- {name}: timed out after {self.timeout}s", file=item["log"])
|
||||
item["log"].close()
|
||||
item["slot"].close()
|
||||
del self.running[name]
|
||||
finished.append((name, item["script"], process.returncode == 0, elapsed, STATE_DIR / "traces" / f"{name}.json"))
|
||||
return finished
|
||||
|
||||
def stop(self):
|
||||
for item in self.running.values():
|
||||
try:
|
||||
os.killpg(item["process"].pid, 9)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
|
||||
def host_config():
|
||||
"""tools/parity_hosts.json: the machines harnesses can run on, and the harnesses that must stay local."""
|
||||
path = ROOT / "tools" / "parity_hosts.json"
|
||||
return json.loads(path.read_text()) if path.exists() else {"default": [], "hosts": {}, "local_only": {}}
|
||||
|
||||
|
||||
class RemoteExecutor:
|
||||
"""Runs harnesses on another machine through `parity.py --worker` over ssh.
|
||||
|
||||
The worktree (minus .git, .local, target and ignored files) is mirrored to
|
||||
<root>/remote/<this host><this path> there; its .local links to the vanilla
|
||||
data in <root>/shared-local. The worker builds the probes and runs each
|
||||
harness it is sent under the same tracer; results come back with the
|
||||
content hash of every dependency, so the pass is keyed on exactly what ran."""
|
||||
|
||||
def __init__(self, name, config, artifacts, local_only, timeout):
|
||||
import threading
|
||||
self.name, self.config, self.local_only, self.timeout = name, config, set(local_only), timeout
|
||||
self.jobs, self.memory_budget, self.ready, self.dead = 0, 0, False, False
|
||||
self.running, self.events, self.backoff = {}, [], 0.0
|
||||
self.lock = threading.Lock()
|
||||
self.process = None
|
||||
self.mirror = f"{config['root']}/remote/{HOST}{str(ROOT).replace('/', '-')}"
|
||||
threading.Thread(target=self._connect, args=(artifacts,), daemon=True).start()
|
||||
|
||||
def _log(self, text):
|
||||
print(f"[{self.name}] {text}", flush=True)
|
||||
|
||||
def _connect(self, artifacts):
|
||||
import shlex
|
||||
ssh = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=30", self.config["ssh"]]
|
||||
started = time.monotonic()
|
||||
shared = f"{self.config['root']}/shared-local"
|
||||
mkdir = subprocess.run([*ssh, f"mkdir -p {shlex.quote(self.mirror)}"], capture_output=True, text=True)
|
||||
if mkdir.returncode:
|
||||
self._log(f"unreachable, running everything here: {mkdir.stderr.strip()[-300:]}")
|
||||
self.dead = True
|
||||
return
|
||||
sync = subprocess.run(
|
||||
["rsync", "-a", "--delete", "--filter=:- .gitignore", "--exclude=/.git", "--exclude=/.local", "--exclude=/target",
|
||||
"--exclude=__pycache__", "-e", " ".join(ssh[:-1]), f"--rsync-path={self.config.get('rsync', 'rsync')}",
|
||||
f"{ROOT}/", f"{self.config['ssh']}:{self.mirror}/"], capture_output=True, text=True)
|
||||
if sync.returncode:
|
||||
self._log(f"sync failed, running everything here: {sync.stderr.strip()[-300:]}")
|
||||
self.dead = True
|
||||
return
|
||||
environment = " ".join(f"{key}={shlex.quote(str(value))}" for key, value in self.config.get("environment", {}).items())
|
||||
command = (f"{self.config.get('setup', 'true')} && cd {shlex.quote(self.mirror)} && "
|
||||
f"exec nice -n {int(self.config.get('nice', 0))} env PARITY_MACHINE_JOBS={self.config.get('jobs', 8)} "
|
||||
f"{environment} {self.config.get('python', 'python3')} tools/parity.py --worker {shlex.quote(shared)}")
|
||||
self.process = subprocess.Popen([*ssh, f"{self.config.get('shell', 'sh -c')} {shlex.quote(command)}"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1)
|
||||
self._send({"prebuild": artifacts, "timeout": self.timeout})
|
||||
self._log(f"synced in {time.monotonic() - started:.0f}s, building probes...")
|
||||
for line in self.process.stdout:
|
||||
try:
|
||||
message = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
with self.lock:
|
||||
if "hello" in message:
|
||||
hello = message["hello"]
|
||||
self.jobs = min(self.config.get("jobs", hello["jobs"]), hello["jobs"])
|
||||
self.memory_budget = hello["memory"]
|
||||
self.ready = True
|
||||
if not hello["built"]:
|
||||
self._log("probe build failed; harnesses will report their own build errors:\n" + hello["errors"][-2000:])
|
||||
self._log(f"ready after {time.monotonic() - started:.0f}s: {self.jobs} harnesses at once, "
|
||||
f"{self.memory_budget / (1 << 30):.0f} GB")
|
||||
else:
|
||||
self.events.append(message)
|
||||
with self.lock:
|
||||
self.dead = True
|
||||
|
||||
def _send(self, message):
|
||||
try:
|
||||
self.process.stdin.write(json.dumps(message) + "\n")
|
||||
self.process.stdin.flush()
|
||||
except (OSError, ValueError, AttributeError):
|
||||
self.dead = True
|
||||
|
||||
def free(self):
|
||||
if not self.ready or self.dead or time.monotonic() < self.backoff:
|
||||
return 0
|
||||
return self.jobs - len(self.running)
|
||||
|
||||
def accepts(self, name):
|
||||
return base_name(name) not in self.local_only and base_name(name) not in self.config.get("exclude", {})
|
||||
|
||||
def fits(self, expected, only_here=False):
|
||||
return not self.running or sum(self.running.values()) + expected <= self.memory_budget
|
||||
|
||||
def start(self, name, script, reuse, expected, shard=None):
|
||||
self.running[name] = expected
|
||||
self._send({"run": name, "script": str(Path(script).relative_to(ROOT)), "reuse": reuse, "expected": expected,
|
||||
"shard": shard})
|
||||
return True
|
||||
|
||||
def poll(self):
|
||||
"""Finished harnesses, as (name, record or None): None means it must run elsewhere."""
|
||||
with self.lock:
|
||||
events, self.events = self.events, []
|
||||
dead = self.dead
|
||||
finished = []
|
||||
for message in events:
|
||||
name = message.get("done") or message.get("rejected")
|
||||
if name not in self.running:
|
||||
continue
|
||||
del self.running[name]
|
||||
if "rejected" in message:
|
||||
self.backoff = time.monotonic() + 5 # other runners hold the remote machine's slots
|
||||
finished.append((name, None))
|
||||
else:
|
||||
(STATE_DIR / "logs").mkdir(parents=True, exist_ok=True)
|
||||
(STATE_DIR / "logs" / f"{name}.log").write_text(message.get("log", ""))
|
||||
finished.append((name, message["record"]))
|
||||
if dead and self.running:
|
||||
self._log("connection lost; its harnesses run elsewhere")
|
||||
finished += [(name, None) for name in self.running]
|
||||
self.running = {}
|
||||
return finished
|
||||
|
||||
def stop(self):
|
||||
if self.process and self.process.poll() is None:
|
||||
try:
|
||||
self.process.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
self.process.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.process.kill()
|
||||
|
||||
|
||||
def key_from(record, hashes, environment):
|
||||
"""key() over the content hashes a remote machine recorded for each dependency."""
|
||||
return key(record, lambda path: hashes.get(str(Path(path).relative_to(ROOT)), "missing"), environment)
|
||||
|
||||
|
||||
def run(selected, state, hasher, environment_digest, executors, reuse_oracles):
|
||||
records = state["harnesses"]
|
||||
# Longest first, so the slow harnesses don't start last.
|
||||
queue = sorted(selected, key=lambda name: -records.get(name, {}).get("seconds", 1e9))
|
||||
results, retried, busy = {}, set(), {}
|
||||
started_all = time.monotonic()
|
||||
local = executors[-1]
|
||||
while queue or busy:
|
||||
# Remote machines first: they take the longest harnesses and leave this one lighter.
|
||||
for executor in executors:
|
||||
while queue and executor.free() > 0:
|
||||
pick = next((name for name in queue if executor.accepts(name) and executor.fits(
|
||||
records.get(name, {}).get("peak_bytes", DEFAULT_MEMORY),
|
||||
not any(other.accepts(name) and not other.dead for other in executors[:-1]))), None)
|
||||
if pick is None:
|
||||
break
|
||||
reuse = reuse_oracles and records.get(pick, {}).get("oracle_reuse", True) and pick not in retried
|
||||
if not executor.start(pick, selected[pick], reuse, records.get(pick, {}).get("peak_bytes", DEFAULT_MEMORY),
|
||||
SHARDS.get(pick)):
|
||||
break
|
||||
queue.remove(pick)
|
||||
busy[pick] = (executor, reuse)
|
||||
if executors[:-1] and all(executor.dead for executor in executors[:-1]) and local.max_peak is not None:
|
||||
# Every other machine is gone: this one runs everything.
|
||||
local.max_peak, local.jobs = None, max(local.jobs, default_local_jobs())
|
||||
time.sleep(0.2)
|
||||
finished = []
|
||||
for executor in executors:
|
||||
if isinstance(executor, LocalExecutor):
|
||||
for name, script, passed, elapsed, trace in executor.poll():
|
||||
finished.append((name, outcome(name, script, passed, elapsed, trace)))
|
||||
else:
|
||||
finished += executor.poll()
|
||||
for name, record in finished:
|
||||
executor, reused = busy.pop(name)
|
||||
if record is None:
|
||||
queue.insert(0, name)
|
||||
continue
|
||||
passed = record["status"] == "pass"
|
||||
if not passed and reused and records.get(name, {}).get("status") != "fail":
|
||||
# A new failure might come from a reused oracle result: run it again from scratch.
|
||||
retried.add(name)
|
||||
queue.insert(0, name)
|
||||
print(f"retry {name} without reused oracle results", flush=True)
|
||||
continue
|
||||
trace_path = traces / f"{name}.json"
|
||||
record = {"status": "pass" if passed else "fail", "seconds": round(elapsed, 1),
|
||||
"finished": time.strftime("%Y-%m-%dT%H:%M:%S")}
|
||||
# A harness that only passes fresh no longer reuses oracle results.
|
||||
record["oracle_reuse"] = records.get(name, {}).get("oracle_reuse", True) and not (passed and name in retried)
|
||||
try:
|
||||
trace = json.loads(trace_path.read_text())
|
||||
except (OSError, ValueError):
|
||||
trace = None # killed before writing it, or the disk was full: the pass can't be keyed
|
||||
if trace:
|
||||
record["dependencies"], record["artifacts"] = dependencies(trace)
|
||||
record["peak_bytes"] = trace["peak_bytes"]
|
||||
record["key"] = key(record, hasher, environment_digest)
|
||||
if passed:
|
||||
clear_large_outputs(name, trace)
|
||||
else:
|
||||
record["dependencies"], record["artifacts"] = [], []
|
||||
hashes = record.pop("hashes", None)
|
||||
if record["dependencies"]:
|
||||
record["key"] = key_from(record, hashes, environment_digest) if hashes is not None else \
|
||||
key(record, hasher, environment_digest)
|
||||
records[name] = record
|
||||
results[name] = record
|
||||
save_state(state)
|
||||
publish(name, record)
|
||||
tail = "" if passed else f" ({logs / (name + '.log')})"
|
||||
print(f"{'PASS' if passed else 'FAIL'} {name} {elapsed:.0f}s{tail}", flush=True)
|
||||
where = "" if executor is local else f" on {executor.name}"
|
||||
tail = "" if passed else f" ({STATE_DIR / 'logs' / (name + '.log')})"
|
||||
print(f"{'PASS' if passed else 'FAIL'} {name} {record['seconds']:.0f}s{where}{tail}", flush=True)
|
||||
return results, time.monotonic() - started_all
|
||||
|
||||
|
||||
def worker_main(shared_local):
|
||||
"""`parity.py --worker SHARED_LOCAL`: run harnesses sent as JSON lines on stdin, answer on stdout."""
|
||||
import queue as queues
|
||||
import threading
|
||||
global SHARED
|
||||
LOCAL.mkdir(exist_ok=True)
|
||||
shared_local = Path.home() / Path(shared_local).expanduser() # relative paths are from the home directory
|
||||
for entry in sorted(shared_local.iterdir()) if shared_local.is_dir() else []:
|
||||
if entry.is_dir() and entry.name not in {"parity-shared", "datafix"} and not (LOCAL / entry.name).exists():
|
||||
(LOCAL / entry.name).symlink_to(entry)
|
||||
if not os.environ.get("PARITY_SHARED"):
|
||||
SHARED = (LOCAL / "minecraft").resolve().parent / "parity-shared"
|
||||
inbox = queues.Queue()
|
||||
|
||||
def read():
|
||||
for line in sys.stdin:
|
||||
inbox.put(json.loads(line))
|
||||
inbox.put(None)
|
||||
|
||||
threading.Thread(target=read, daemon=True).start()
|
||||
channel = sys.stdout
|
||||
sys.stdout = sys.stderr # nothing else may write to the protocol channel
|
||||
|
||||
def send(message):
|
||||
channel.write(json.dumps(message) + "\n")
|
||||
channel.flush()
|
||||
|
||||
first = inbox.get()
|
||||
if first is None:
|
||||
return 0
|
||||
state = load_state()
|
||||
hasher = Hasher(state["hashes"])
|
||||
built, errors = prebuild(first["prebuild"], default_build_jobs()) if first["prebuild"] else (True, "")
|
||||
executor = LocalExecutor(MACHINE_JOBS, int(memory_available() * 0.75), first["timeout"])
|
||||
send({"hello": {"jobs": MACHINE_JOBS, "memory": executor.memory_budget, "built": built, "errors": errors[-4000:]}})
|
||||
while True:
|
||||
try:
|
||||
message = inbox.get(timeout=0.2)
|
||||
except queues.Empty:
|
||||
message = False
|
||||
if message is None:
|
||||
executor.stop()
|
||||
save_state(state)
|
||||
return 0
|
||||
if message:
|
||||
# Other runners may share this machine: take a slot only while memory allows.
|
||||
reserve = message["expected"] + (4 << 30)
|
||||
if (executor.running and memory_available() < reserve) or \
|
||||
not executor.start(message["run"], ROOT / message["script"], message["reuse"], message["expected"],
|
||||
message.get("shard")):
|
||||
send({"rejected": message["run"]})
|
||||
for name, script, passed, elapsed, trace in executor.poll():
|
||||
record = outcome(name, script, passed, elapsed, trace, hasher)
|
||||
log = (STATE_DIR / "logs" / f"{name}.log").read_bytes()[-(8 << 20):].decode(errors="replace")
|
||||
send({"done": name, "record": record, "log": log})
|
||||
save_state(state)
|
||||
|
||||
|
||||
def stale(name, state, hasher, environment):
|
||||
record = state["harnesses"].get(name)
|
||||
if record and record.get("status") == "pass" and "key" in record and key(record, hasher, environment) == record["key"]:
|
||||
@@ -427,6 +1015,7 @@ def trace_main(output, script, arguments):
|
||||
def write():
|
||||
modules = [getattr(module, "__file__", None) for module in list(sys.modules.values())]
|
||||
peak = max(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss)
|
||||
peak //= 1024 if sys.platform == "darwin" else 1 # bytes on macOS, KiB elsewhere
|
||||
Path(output).write_text(json.dumps({
|
||||
"modules": sorted({m for m in modules if m and inside(m, ROOT)}),
|
||||
"read": sorted(path for path in read if os.path.isabs(path) or not path.startswith("<")),
|
||||
@@ -450,6 +1039,8 @@ def finished_run(failed):
|
||||
def main():
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "--trace":
|
||||
return trace_main(sys.argv[2], sys.argv[3], sys.argv[4:])
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "--worker":
|
||||
return worker_main(sys.argv[2])
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("names", nargs="*", help="harness names, e.g. food or block_update")
|
||||
parser.add_argument("--all", action="store_true", help="run every harness from scratch, ignoring earlier passes")
|
||||
@@ -457,8 +1048,12 @@ def main():
|
||||
parser.add_argument("--failed", action="store_true", help="rerun the harnesses that failed last time")
|
||||
parser.add_argument("--list", action="store_true", help="print what would run, then stop")
|
||||
parser.add_argument("--status", action="store_true", help="print each harness's last result")
|
||||
parser.add_argument("-j", "--jobs", type=int, default=max(1, (os.cpu_count() or 4) // 3),
|
||||
help="harnesses at once in this run; every runner on the machine shares PARITY_MACHINE_JOBS slots")
|
||||
parser.add_argument("-j", "--jobs", type=int,
|
||||
help="harnesses at once on this machine (default: PARITY_LOCAL_JOBS, else 3 with other hosts or a "
|
||||
"third of its threads, within $FLEET_LOAD_JOBS); runners here share PARITY_MACHINE_JOBS slots")
|
||||
parser.add_argument("--hosts", default=os.environ.get("PARITY_HOSTS"),
|
||||
help="comma-separated machines from tools/parity_hosts.json to run harnesses on as well "
|
||||
"(default: PARITY_HOSTS, else the file's default; '' for this machine only)")
|
||||
parser.add_argument("--timeout", type=int, default=3600, help="seconds per harness")
|
||||
args = parser.parse_args()
|
||||
|
||||
@@ -467,6 +1062,9 @@ def main():
|
||||
hasher = Hasher(state["hashes"])
|
||||
environment = environment_key(hasher)
|
||||
records = state["harnesses"]
|
||||
# A sharded harness's name stands for all its shards.
|
||||
args.names = [entry for name in args.names for entry in ([name] if name in found else
|
||||
[shard for shard in found if base_name(shard) == name] or [name])]
|
||||
unknown = [name for name in args.names if name not in found]
|
||||
if unknown:
|
||||
parser.error("unknown harnesses: " + ", ".join(unknown))
|
||||
@@ -496,23 +1094,44 @@ def main():
|
||||
finished_run([])
|
||||
return 0
|
||||
|
||||
jobs = max(1, args.jobs)
|
||||
# Harnesses that never ran here have no recorded probes: build them all.
|
||||
artifacts = [["all", "", "release"]] if any("artifacts" not in records.get(name, {}) for name in selected) else []
|
||||
for name in selected:
|
||||
for artifact in records.get(name, {}).get("artifacts", []):
|
||||
if artifact not in artifacts:
|
||||
artifacts.append(artifact)
|
||||
print("Building probes...", flush=True)
|
||||
started = time.monotonic()
|
||||
built, errors = prebuild(artifacts, os.cpu_count() or 8)
|
||||
if not built:
|
||||
print(errors[-4000:])
|
||||
print("Probe build failed; harnesses will report their own build errors.", flush=True)
|
||||
print(f"Probes built in {time.monotonic() - started:.0f}s. Running {len(selected)} harnesses, {jobs} at a time...", flush=True)
|
||||
reuse_oracles = not (args.fresh or args.all)
|
||||
results, elapsed = run(selected, state, hasher, environment_key(hasher), jobs, args.timeout, int(memory_available() * 0.75),
|
||||
reuse_oracles)
|
||||
config = host_config()
|
||||
hosts = [host for host in (config.get("default", []) if args.hosts is None else args.hosts.split(","))
|
||||
if host and host != HOST]
|
||||
unknown = [host for host in hosts if host not in config["hosts"]]
|
||||
if unknown:
|
||||
parser.error("unknown hosts (see tools/parity_hosts.json): " + ", ".join(unknown))
|
||||
jobs = default_local_jobs(remote=bool(hosts)) if args.jobs is None else max(0, args.jobs)
|
||||
def elsewhere(name):
|
||||
return base_name(name) not in config.get("local_only", {}) and \
|
||||
any(base_name(name) not in config["hosts"][host].get("exclude", {}) for host in hosts)
|
||||
if jobs == 0 and not all(elsewhere(name) for name in selected):
|
||||
jobs = 1 # harnesses that can only run here still need a slot
|
||||
remotes = [RemoteExecutor(host, config["hosts"][host], artifacts, config.get("local_only", {}), args.timeout)
|
||||
for host in hosts]
|
||||
try:
|
||||
if jobs:
|
||||
print("Building probes...", flush=True)
|
||||
started = time.monotonic()
|
||||
built, errors = prebuild(artifacts, default_build_jobs())
|
||||
if not built:
|
||||
print(errors[-4000:])
|
||||
print("Probe build failed; harnesses will report their own build errors.", flush=True)
|
||||
print(f"Probes built in {time.monotonic() - started:.0f}s.", flush=True)
|
||||
where = "".join(f", plus {host}" for host in hosts)
|
||||
print(f"Running {len(selected)} harnesses, {jobs} at a time here{where}...", flush=True)
|
||||
reuse_oracles = not (args.fresh or args.all)
|
||||
executors = [*remotes, LocalExecutor(jobs, int(memory_available() * 0.75), args.timeout,
|
||||
REMOTE_LOCAL_PEAK if remotes and args.jobs is None else None)]
|
||||
results, elapsed = run(selected, state, hasher, environment_key(hasher), executors, reuse_oracles)
|
||||
finally:
|
||||
for executor in remotes:
|
||||
executor.stop()
|
||||
save_state(state)
|
||||
failed = sorted(name for name, record in results.items() if record["status"] != "pass")
|
||||
finished_run(failed)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"default": ["macmini"],
|
||||
"hosts": {
|
||||
"macmini": {
|
||||
"ssh": "macmini",
|
||||
"root": "code/horizon-parity",
|
||||
"shell": "zsh -lc",
|
||||
"setup": "source ~/.cargo/env && export JAVA_HOME=$(/usr/libexec/java_home -v 25) && export PATH=$JAVA_HOME/bin:$PATH",
|
||||
"python": "/opt/homebrew/bin/python3.13",
|
||||
"rsync": "/opt/homebrew/bin/rsync",
|
||||
"jobs": 14,
|
||||
"exclude": {
|
||||
"options": "Rust's f64::powf uses the platform libm, which rounds differently on macOS",
|
||||
"chunk_generation": "one ocean ruined portal differs on macOS (platform float math)"
|
||||
}
|
||||
},
|
||||
"thinkpad": {
|
||||
"ssh": "thinkpad",
|
||||
"root": "code/horizon-parity",
|
||||
"shell": "sh -c",
|
||||
"jobs": 2,
|
||||
"nice": 19,
|
||||
"environment": {"PARITY_BUILD_JOBS": "2"},
|
||||
"note": "hosts the Claude account pool: two harnesses at most, at the lowest priority"
|
||||
}
|
||||
},
|
||||
"local_only": {
|
||||
"save_roundtrip": "runs the game on a virtual screen (vscreen) with a null ALSA device"
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,12 @@ def stdin_identity(hashes):
|
||||
return "null"
|
||||
import stat as modes
|
||||
if modes.S_ISREG(stat.st_mode):
|
||||
return "f:" + hashes.file(os.readlink("/proc/self/fd/0"))
|
||||
# Hash the content without moving the shared offset (no /proc on macOS).
|
||||
digest, offset = hashlib.sha256(), 0
|
||||
while chunk := os.pread(0, 1 << 20, offset):
|
||||
digest.update(chunk)
|
||||
offset += len(chunk)
|
||||
return "f:" + digest.hexdigest()
|
||||
if modes.S_ISCHR(stat.st_mode):
|
||||
return "tty"
|
||||
return None # a pipe or socket: its content is unknown, so never cache
|
||||
|
||||
@@ -394,6 +394,23 @@ def main():
|
||||
subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaMobDataExporter', str(mob_data), str(jars['client'])],
|
||||
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
|
||||
# Vanilla's built-in registries for in-game command parsing (mob effects,
|
||||
# data component types, dialogs, block entity and tag members).
|
||||
command_registries = root / 'command-registries.json'
|
||||
command_oracle = oracle.with_name('VanillaCommandParseOracle.java')
|
||||
command_sources = base.source_hashes([command_oracle])
|
||||
if not (previous.get('command_registries_exporters_sha256') == command_sources and command_registries.exists()
|
||||
and previous.get('server_sha256') == origin['server_sha256']):
|
||||
export = lab.LOCAL / 'command-registries'; classes = export / 'classes'; classes.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
with (root / 'command-registries-export.log').open('w') as log:
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none',
|
||||
'-cp', dependencies, '-d', str(classes), str(command_oracle)],
|
||||
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
|
||||
subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaCommandParseOracle', 'registries', str(export)],
|
||||
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
|
||||
command_registries.write_bytes((export / 'registries.json').read_bytes())
|
||||
creative = root / 'creative-tabs.json'
|
||||
creative_oracle = oracle.with_name('VanillaCreativeTabsExporter.java')
|
||||
creative_sources = base.source_hashes([creative_oracle])
|
||||
@@ -425,6 +442,7 @@ def main():
|
||||
'mob_data_exporters_sha256': mob_sources,
|
||||
'entity_types_exporters_sha256': entity_types_sources,
|
||||
'behaviour_exporters_sha256': behaviour_sources,
|
||||
'command_registries_exporters_sha256': command_sources,
|
||||
'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'],
|
||||
'facts_sha256': lab.digest(facts, 'sha256'),
|
||||
'block_tags_sha256': lab.digest(root / 'block-tags.json', 'sha256'), 'resource_files': count})
|
||||
|
||||
+3
-2
@@ -133,7 +133,8 @@ def integrate(args):
|
||||
if git("rev-parse", "HEAD", cwd=base_tree) == before:
|
||||
print(f"{names}: nothing new for {args.base}.")
|
||||
return 0
|
||||
gate = [sys.executable, "tools/gate.py", "-j", str(args.jobs), "--known-failures", ",".join(known)]
|
||||
gate = [sys.executable, "tools/gate.py", "--known-failures", ",".join(known)]
|
||||
gate += ["-j", str(args.jobs)] if args.jobs is not None else []
|
||||
gate += ["--no-parity"] if args.no_parity else []
|
||||
if subprocess.run(gate, cwd=base_tree).returncode:
|
||||
git("reset", "--hard", before, cwd=base_tree)
|
||||
@@ -158,7 +159,7 @@ def main():
|
||||
command.set_defaults(run=save)
|
||||
command = commands.add_parser("integrate")
|
||||
command.add_argument("branches", nargs="+", help="merged in order, then gated together")
|
||||
command.add_argument("-j", "--jobs", type=int, default=8)
|
||||
command.add_argument("-j", "--jobs", type=int, help="harnesses at once on this machine (default: tools/parity.py's)")
|
||||
command.add_argument("--no-parity", action="store_true", help="skip the vanilla harnesses in the gate")
|
||||
command.set_defaults(run=integrate)
|
||||
args = parser.parse_args()
|
||||
|
||||
Executable
+316
@@ -0,0 +1,316 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare client-ticked block-entity animation with the vanilla 26.3 block entities.
|
||||
|
||||
The Java oracle (VanillaBlockEntityAnimOracle) builds each case's real vanilla
|
||||
block entity (chest, trapped/copper chest and the other half of a double chest,
|
||||
ender chest, enchanting table, shulker box, bell, conduit, dragon/piglin head,
|
||||
decorated pot)
|
||||
on a stand-in client level, then per scripted step applies the block event
|
||||
(triggerEvent), runs the entity's own client ticker and the renderer's
|
||||
extractRenderState, printing the fields, the level calls the tick made
|
||||
(neighbour updates, entity pushes/queries, sounds, particles) and the render
|
||||
state. `examples/block_entity_anim_fixture` replays the steps through
|
||||
`horizon_client::block_entity_anim` and derives the render state from the
|
||||
`BlockAnim` Horizon's renderer reads. Lines must match exactly (floats as bits).
|
||||
|
||||
test_block_entity_anim_parity.py [--filter SUBSTRING] [--detail N]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
|
||||
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
|
||||
HORIZONTAL = ['north', 'south', 'west', 'east']
|
||||
ALL = ['down', 'up'] + HORIZONTAL
|
||||
FRAME = ['minecraft:prismarine', 'minecraft:prismarine_bricks', 'minecraft:sea_lantern', 'minecraft:dark_prismarine']
|
||||
WATERY = ['minecraft:water', 'minecraft:water[level=3]', 'minecraft:bubble_column', 'minecraft:seagrass',
|
||||
'minecraft:kelp_plant', 'minecraft:oak_slab[waterlogged=true]', 'minecraft:oak_stairs[waterlogged=true]']
|
||||
CHESTS = ['chest', 'trapped_chest', 'copper_chest', 'exposed_copper_chest', 'waxed_oxidized_copper_chest']
|
||||
CLOCKWISE = {'north': 'east', 'east': 'south', 'south': 'west', 'west': 'north'}
|
||||
STEP = {'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)}
|
||||
DRY = ['minecraft:air', 'minecraft:stone', 'minecraft:lava', 'minecraft:oak_slab', 'minecraft:ice']
|
||||
|
||||
|
||||
def frame_offsets():
|
||||
out = []
|
||||
for ox in range(-2, 3):
|
||||
for oy in range(-2, 3):
|
||||
for oz in range(-2, 3):
|
||||
ax, ay, az = abs(ox), abs(oy), abs(oz)
|
||||
if (ax > 1 or ay > 1 or az > 1) and (ox == 0 and (ay == 2 or az == 2) or oy == 0 and (ax == 2 or az == 2)
|
||||
or oz == 0 and (ax == 2 or ay == 2)):
|
||||
out.append((ox, oy, oz))
|
||||
return out
|
||||
|
||||
|
||||
def cases():
|
||||
rng = random.Random(0x414e494d)
|
||||
out = []
|
||||
|
||||
def pos():
|
||||
return [rng.randint(-3000, 3000), rng.randint(-60, 300), rng.randint(-3000, 3000)]
|
||||
|
||||
def add(kind, block, steps, **extra):
|
||||
case = {'name': f'{kind}-{len(out)}', 'block': block, 'pos': pos(), 'steps': steps}
|
||||
case.update(extra)
|
||||
out.append(case)
|
||||
|
||||
def times(n, start=None, gaps=(1,)):
|
||||
t = rng.randint(-100, 10 ** 7) if start is None else start
|
||||
result = []
|
||||
for _ in range(n):
|
||||
result.append(t)
|
||||
t += rng.choice(gaps)
|
||||
return result
|
||||
|
||||
# Shulker boxes: players open and close (open counts from startOpen/stopOpen), other events ignored.
|
||||
for i in range(48):
|
||||
color = rng.choice(['', 'white_', 'purple_', 'black_'])
|
||||
block = f'minecraft:{color}shulker_box[facing={rng.choice(ALL)}]'
|
||||
steps, count = [], 0
|
||||
for t in times(rng.randint(20, 70)):
|
||||
step = {'time': t, 'partial': round(rng.random(), 4)}
|
||||
r = rng.random()
|
||||
if r < 0.12:
|
||||
count = max(count, 0) + 1
|
||||
step['event'] = [1, count]
|
||||
elif r < 0.22:
|
||||
count -= 1
|
||||
step['event'] = [1, count]
|
||||
elif r < 0.25:
|
||||
step['event'] = [rng.choice([0, 2, 1]), rng.randint(-2, 3)]
|
||||
steps.append(step)
|
||||
add('shulker', block, steps)
|
||||
|
||||
# Bells: rings from any side (and odd data values), raiders and other mobs nearby.
|
||||
for i in range(40):
|
||||
attach = rng.choice(['floor', 'ceiling', 'single_wall', 'double_wall'])
|
||||
block = f'minecraft:bell[attachment={attach},facing={rng.choice(HORIZONTAL)}]'
|
||||
p = pos()
|
||||
entities = []
|
||||
for _ in range(rng.choice([0, 1, 2, 5, 12, 25])):
|
||||
# Multiples of 1/1024: serde_json parses other decimals approximately (1 ulp off).
|
||||
spread = rng.choice([10, 33, 50, 70])
|
||||
entities.append({'pos': [p[k] + 0.5 + round(rng.uniform(-spread, spread) * 1024) / 1024 for k in range(3)],
|
||||
'raider': rng.random() < 0.5, 'alive': rng.random() < 0.85, 'removed': rng.random() < 0.08})
|
||||
steps = []
|
||||
start = rng.randint(-50, 10 ** 6)
|
||||
for k, t in enumerate(times(rng.randint(60, 180), start)):
|
||||
step = {'time': t, 'partial': round(rng.random(), 4)}
|
||||
if (k == 2 or rng.random() < 0.05) and k < 150:
|
||||
step['event'] = [1 if rng.random() < 0.93 else 2, rng.choice([0, 1, 2, 3, 4, 5, 2, 3, 4, 5, 7, -3, 11])]
|
||||
steps.append(step)
|
||||
case = {'name': f'bell-{len(out)}', 'block': block, 'pos': p, 'steps': steps, 'entities': entities}
|
||||
out.append(case)
|
||||
|
||||
# Conduits: water around, prismarine frames of various sizes, frames changing over time.
|
||||
rings = frame_offsets()
|
||||
for i in range(36):
|
||||
world = {}
|
||||
water = rng.random()
|
||||
for ox in range(-1, 2):
|
||||
for oy in range(-1, 2):
|
||||
for oz in range(-1, 2):
|
||||
if (ox, oy, oz) != (0, 0, 0):
|
||||
world[f'{ox},{oy},{oz}'] = rng.choice(WATERY) if rng.random() < 0.97 or water < 0.5 else rng.choice(DRY)
|
||||
size = rng.choice([0, 10, 15, 16, 20, 30, 41, 42, 42])
|
||||
for o in rng.sample(rings, size):
|
||||
world['%d,%d,%d' % o] = rng.choice(FRAME)
|
||||
steps = []
|
||||
for t in times(rng.randint(60, 140), gaps=(1, 1, 1, 2, 7)):
|
||||
step = {'time': t, 'partial': round(rng.random(), 4)}
|
||||
if rng.random() < 0.04:
|
||||
o = rng.choice(rings)
|
||||
step['set'] = {'%d,%d,%d' % o: rng.choice(FRAME + DRY)}
|
||||
steps.append(step)
|
||||
waterlogged = 'true' if rng.random() < 0.9 else 'false'
|
||||
extra = {'world': world, 'seed': rng.randint(0, 2 ** 40)}
|
||||
if rng.random() < 0.3:
|
||||
extra['target'] = {'pos': [round(rng.uniform(-8, 8) * 1024) / 1024 for _ in range(3)], 'width': round(rng.uniform(0.3, 2), 3),
|
||||
'height': round(rng.uniform(0.5, 3), 3), 'eye': round(rng.uniform(0.2, 2.5), 3)}
|
||||
add('conduit', f'minecraft:conduit[waterlogged={waterlogged}]', steps, **extra)
|
||||
|
||||
# Dragon and piglin heads powered on and off.
|
||||
for i in range(24):
|
||||
head = rng.choice(['dragon', 'piglin'])
|
||||
wall = rng.random() < 0.5
|
||||
prop = f'facing={rng.choice(HORIZONTAL)}' if wall else f'rotation={rng.randint(0, 15)}'
|
||||
name = f'minecraft:{head}_wall_head' if wall else f'minecraft:{head}_head'
|
||||
powered = rng.random() < 0.5
|
||||
steps = []
|
||||
for t in times(rng.randint(20, 90)):
|
||||
if rng.random() < 0.1:
|
||||
powered = not powered
|
||||
steps.append({'time': t, 'partial': round(rng.random(), 4),
|
||||
'state': f'{name}[{prop},powered={str(powered).lower()}]'})
|
||||
add('skull', f'{name}[{prop},powered=false]', steps)
|
||||
|
||||
# Decorated pots wobbling (insert: POSITIVE, fail: NEGATIVE) and invalid events.
|
||||
for i in range(24):
|
||||
steps = []
|
||||
for t in times(rng.randint(20, 60), gaps=(0, 1, 1, 1, 3)):
|
||||
step = {'time': t, 'partial': round(rng.random(), 4)}
|
||||
if rng.random() < 0.15:
|
||||
step['event'] = [rng.choice([1, 1, 1, 2]), rng.choice([0, 1, 0, 1, 2, -1])]
|
||||
steps.append(step)
|
||||
add('pot', f'minecraft:decorated_pot[facing={rng.choice(HORIZONTAL)}]', steps)
|
||||
# Chests and ender chests: open counts from block event 1 (both halves of
|
||||
# a double chest), other events ignored; the neighbour a double half
|
||||
# connects to may be its other half or not (wrong block, type, facing).
|
||||
for i in range(48):
|
||||
facing = rng.choice(HORIZONTAL)
|
||||
partner = None
|
||||
world = {}
|
||||
if rng.random() < 0.2:
|
||||
block = f'minecraft:ender_chest[facing={facing}]'
|
||||
else:
|
||||
name = rng.choice(CHESTS)
|
||||
kind = rng.choice(['single', 'left', 'right', 'left', 'right'])
|
||||
block = f'minecraft:{name}[facing={facing},type={kind}]'
|
||||
if kind != 'single':
|
||||
connected = CLOCKWISE[facing] if kind == 'left' else [d for d, c in CLOCKWISE.items() if c == facing][0]
|
||||
other_kind = 'right' if kind == 'left' else 'left'
|
||||
other_name, other_facing, r = name, facing, rng.random()
|
||||
if r < 0.1:
|
||||
other_kind = kind
|
||||
elif r < 0.2:
|
||||
other_facing = rng.choice([d for d in HORIZONTAL if d != facing])
|
||||
elif r < 0.3:
|
||||
other_name = rng.choice([c for c in CHESTS if c != name])
|
||||
elif r < 0.35:
|
||||
other_kind = 'single'
|
||||
if r < 0.95:
|
||||
partner = '%d,%d,%d' % STEP[connected]
|
||||
world[partner] = f'minecraft:{other_name}[facing={other_facing},type={other_kind}]'
|
||||
steps, count, other = [], 0, 0
|
||||
for t in times(rng.randint(20, 70)):
|
||||
step = {'time': t, 'partial': round(rng.random(), 4)}
|
||||
r = rng.random()
|
||||
if r < 0.12:
|
||||
count = max(count, 0) + 1
|
||||
step['event'] = [1, count]
|
||||
elif r < 0.22:
|
||||
count -= 1
|
||||
step['event'] = [1, count]
|
||||
elif r < 0.25:
|
||||
step['event'] = [rng.choice([0, 2, 1]), rng.randint(-2, 3)]
|
||||
if partner and rng.random() < 0.15:
|
||||
other = other + 1 if rng.random() < 0.55 else other - 1
|
||||
step['partnerEvent'] = [1, other]
|
||||
steps.append(step)
|
||||
extra = {'world': world}
|
||||
if partner:
|
||||
extra['partner'] = partner
|
||||
add('chest', block, steps, **extra)
|
||||
|
||||
# Enchanting tables: players (and spectators) walking in and out of the
|
||||
# 3-block reach; the class's shared RANDOM seeded per case.
|
||||
for i in range(36):
|
||||
p = pos()
|
||||
centre = [p[0] + 0.5, p[1] + 0.5, p[2] + 0.5]
|
||||
|
||||
def players():
|
||||
out = []
|
||||
for _ in range(rng.choice([0, 1, 1, 1, 2, 3])):
|
||||
spread = rng.choice([1.5, 3, 5])
|
||||
out.append({'pos': [centre[k] + round(rng.uniform(-spread, spread) * 1024) / 1024 for k in range(3)],
|
||||
'spectator': rng.random() < 0.15})
|
||||
return out
|
||||
steps = []
|
||||
for t in times(rng.randint(40, 160)):
|
||||
step = {'time': t, 'partial': round(rng.random(), 4)}
|
||||
if rng.random() < 0.08:
|
||||
step['players'] = players()
|
||||
steps.append(step)
|
||||
case = {'name': f'book-{len(out)}', 'block': 'minecraft:enchanting_table', 'pos': p, 'steps': steps,
|
||||
'players': players(), 'seed': rng.randint(0, 2 ** 40)}
|
||||
out.append(case)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--filter', default='')
|
||||
parser.add_argument('--detail', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
libraries = baking.client_libraries()
|
||||
build = lab.LOCAL / 'rust-block-entity-anim-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
resources = lab.LOCAL / 'horizon-client' / '26.3'
|
||||
chosen = [c for c in cases() if args.filter in c['name']]
|
||||
inputs = build / 'inputs.jsonl'
|
||||
inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
|
||||
if result.returncode:
|
||||
print((build / (name + '.log')).read_text()[-4000:])
|
||||
sys.exit(f'{name} failed')
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
|
||||
*(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityAnimOracle'))], 'compile-java')
|
||||
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityAnimOracle',
|
||||
inputs, build / 'vanilla.txt'], 'vanilla')
|
||||
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_anim_fixture', '--',
|
||||
resources, inputs, build / 'rust.txt'], 'rust')
|
||||
|
||||
def split(path):
|
||||
result, current = {}, None
|
||||
for line in path.read_text().splitlines():
|
||||
if line.startswith('case '):
|
||||
current = line[5:]
|
||||
result[current] = []
|
||||
else:
|
||||
result[current].append(line)
|
||||
return result
|
||||
vanilla, rust = split(build / 'vanilla.txt'), split(build / 'rust.txt')
|
||||
kinds, failures, errors, steps = {}, {}, {}, 0
|
||||
for case in chosen:
|
||||
name = case['name']
|
||||
kind = name.split('-')[0]
|
||||
v, r = vanilla.get(name, []), rust.get(name, [])
|
||||
total = kinds.setdefault(kind, [0, 0])
|
||||
total[1] += 1
|
||||
if v and v[0].startswith('error'):
|
||||
errors.setdefault(kind, v[0])
|
||||
continue
|
||||
steps += len(v)
|
||||
bad = next((i for i, (a, b) in enumerate(zip(v, r)) if a != b), None)
|
||||
if bad is None and len(v) != len(r):
|
||||
bad = min(len(v), len(r))
|
||||
if bad is None:
|
||||
total[0] += 1
|
||||
else:
|
||||
failures.setdefault(kind, []).append((case, bad, v[bad] if bad < len(v) else None, r[bad] if bad < len(r) else None))
|
||||
for kind, error in sorted(errors.items()):
|
||||
print(f'ORACLE ERROR {kind}: {error[:600]}')
|
||||
for kind, items in sorted(failures.items()):
|
||||
print(f'MISMATCH {kind}: {len(items)} cases')
|
||||
for case, step, a, b in items[:args.detail]:
|
||||
print(f' {case["name"]} {case["block"]} step {step}: {json.dumps(case["steps"][step] if step < len(case["steps"]) else None)}')
|
||||
print(f' vanilla: {(a or "")[:500]}')
|
||||
print(f' horizon: {(b or "")[:500]}')
|
||||
for kind, (ok, n) in sorted(kinds.items()):
|
||||
print(f'{kind}: {ok}/{n} cases match')
|
||||
passed = sum(ok for ok, _ in kinds.values())
|
||||
print(f'{passed}/{len(chosen)} cases match ({steps} ticked steps)')
|
||||
if failures or errors:
|
||||
sys.exit(1)
|
||||
print('block entity animation parity ok')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -122,6 +122,16 @@ def cases():
|
||||
for block in ['end_portal', 'end_gateway', 'campfire[facing=north]', 'spawner',
|
||||
'trial_spawner', 'vault', 'suspicious_sand', 'oak_shelf[facing=east]']:
|
||||
add('minecraft:' + block)
|
||||
# End gateways: the beam while spawning (age < 200) or cooling down, in End and
|
||||
# Overworld build heights, and the faces Block.shouldRenderFace leaves against neighbours.
|
||||
neighbours = [{}, {'up': 'minecraft:bedrock', 'down': 'minecraft:bedrock'},
|
||||
{'north': 'minecraft:end_gateway', 'east': 'minecraft:glass', 'west': 'minecraft:oak_slab[type=top]',
|
||||
'south': 'minecraft:end_stone', 'down': 'minecraft:oak_stairs[facing=east,half=top]'}]
|
||||
for age, cooldown in [(0, 0), (37, 0), (150, 0), (199, 0), (120, 25), (5000, 1), (5000, 17), (5000, 40), (5000, 0)]:
|
||||
add('minecraft:end_gateway', gateway={'age': age, 'cooldown': cooldown}, gameTime=rng.randint(0, 10 ** 6),
|
||||
level=rng.choice([[0, 256], [-64, 384]]), neighbours=rng.choice(neighbours))
|
||||
for n in neighbours:
|
||||
add('minecraft:end_portal', neighbours=n)
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare Horizon's command execution with vanilla's real command implementations.
|
||||
|
||||
Java (VanillaCommandExecOracle) starts a stand-in integrated server: a real
|
||||
MinecraftServer with a generated world, Commands.CommandSelection.INTEGRATED
|
||||
and one single-player owner named Player. Rust runs the same script through
|
||||
the Horizon client headless (HORIZON_COMMAND_SCRIPT). Both run each command as
|
||||
the player through Commands.performPrefixedCommand and record every system or
|
||||
chat message the player receives (text and resolved style: colour, bold,
|
||||
italic, underlined, strikethrough, obfuscated) together with the results the
|
||||
command reported to the player's CommandResultCallback. World, entity and item
|
||||
changes are observed through probe commands whose feedback reports them
|
||||
(execute if, clear with a zero count, data get, scoreboard queries...).
|
||||
Messages that depend on time or a random UUID are compared after masking.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
from . import command_exec_corpus as corpus_module
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
import command_exec_corpus as corpus_module
|
||||
|
||||
SEED = 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--prepare', action='store_true')
|
||||
parser.add_argument('--limit', type=int, default=40, help='print at most this many mismatches')
|
||||
parser.add_argument('--allow-gaps', action='store_true', help='report mismatches without failing')
|
||||
parser.add_argument('--only', help='run only corpus groups whose name contains this')
|
||||
args = parser.parse_args()
|
||||
build = lab.LOCAL / 'command-exec-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report_path = build / 'report.json'
|
||||
report_path.unlink(missing_ok=True)
|
||||
if args.prepare:
|
||||
lab.prepare()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java'
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependency_path = os.pathsep.join(map(str, libraries))
|
||||
|
||||
def run(command, name, **kw):
|
||||
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
|
||||
result = subprocess.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT, **kw)
|
||||
if result.returncode:
|
||||
tail = (build / (name + '.log')).read_text(errors='replace')[-3000:]
|
||||
sys.exit(f'{name} failed ({result.returncode}):\n{tail}')
|
||||
|
||||
groups = corpus_module.groups()
|
||||
if args.only:
|
||||
groups = [g for g in groups if args.only in g[0] or g[0] == 'setup']
|
||||
script = []
|
||||
for _, lines in groups:
|
||||
script.extend(lines)
|
||||
script_path = build / 'script.jsonl'
|
||||
script_path.write_text(''.join(json.dumps(op, ensure_ascii=False) + '\n' for op in script), encoding='utf-8')
|
||||
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + dependency_path, '-d', classes, oracle], 'compile-java')
|
||||
vanilla_dir = build / 'vanilla'
|
||||
shutil.rmtree(vanilla_dir, ignore_errors=True)
|
||||
vanilla_dir.mkdir()
|
||||
run(['java', '-Xmx3G', '-Duser.timezone=UTC', '-cp', os.pathsep.join([str(classes), str(jars['server']), dependency_path]),
|
||||
'dev.horizonlab.parity.VanillaCommandExecOracle', vanilla_dir / 'universe', script_path, build / 'vanilla.jsonl', SEED], 'java', cwd=vanilla_dir)
|
||||
|
||||
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], 'compile-rust', cwd=lab.ROOT)
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
|
||||
binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
rust_dir = build / 'rust'
|
||||
shutil.rmtree(rust_dir, ignore_errors=True)
|
||||
rust_dir.mkdir()
|
||||
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_COMMAND_SCRIPT=str(script_path), HORIZON_COMMAND_OUTPUT=str(build / 'rust.jsonl'))
|
||||
run([binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--world', 'harness', '--seed', SEED, '--radius', 4], 'rust', cwd=rust_dir, env=env)
|
||||
|
||||
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').open(encoding='utf-8')]
|
||||
rust = [json.loads(l) for l in (build / 'rust.jsonl').open(encoding='utf-8')]
|
||||
if len(vanilla) != len(rust):
|
||||
sys.exit(f'record count differs: vanilla {len(vanilla)} rust {len(rust)}')
|
||||
commands_by_group = []
|
||||
index = 0
|
||||
for name, lines in groups:
|
||||
n = sum(1 for op in lines if (op['op'] == 'cmd' and op.get('record', True)) or (op['op'] == 'tick' and op.get('record')))
|
||||
commands_by_group.append((name, index, index + n))
|
||||
index += n
|
||||
mismatches = []
|
||||
for v, r in zip(vanilla, rust):
|
||||
assert v['cmd'] == r['cmd'], (v['cmd'], r['cmd'])
|
||||
kind = compare(v, r)
|
||||
if kind:
|
||||
mismatches.append({'kind': kind, 'cmd': v['cmd'], 'vanilla': v, 'rust': r})
|
||||
(build / 'mismatches.jsonl').write_text(''.join(json.dumps(m, ensure_ascii=False) + '\n' for m in mismatches), encoding='utf-8')
|
||||
summary = []
|
||||
bad = {m['cmd'] for m in mismatches}
|
||||
for name, lo, hi in commands_by_group:
|
||||
failed = sum(1 for rec in vanilla[lo:hi] if rec['cmd'] in bad)
|
||||
summary.append({'group': name, 'commands': hi - lo, 'mismatches': failed})
|
||||
print(f'{name}: {hi - lo - failed}/{hi - lo} commands match', flush=True)
|
||||
for m in mismatches[:args.limit]:
|
||||
print(m['kind'], repr(m['cmd']))
|
||||
print(' vanilla', render(m['vanilla'])[:400])
|
||||
print(' rust ', render(m['rust'])[:400])
|
||||
total = len(vanilla)
|
||||
print(f'total: {total - len(mismatches)}/{total} commands match', flush=True)
|
||||
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'seed': SEED,
|
||||
'commands': total, 'mismatches': len(mismatches), 'groups': summary,
|
||||
'scope': 'Feedback and failure messages (text and resolved style), chat lines, and CommandResultCallback results of commands run by the single-player owner of an integrated server; world, entity and item effects through probe commands.'}
|
||||
lab.write_json(report_path, report)
|
||||
if mismatches and not args.allow_gaps:
|
||||
sys.exit(f'{len(mismatches)} command execution mismatches; see {build}')
|
||||
print(f'Command execution parity report: {report_path}')
|
||||
|
||||
|
||||
MASKS = [
|
||||
(re.compile(r'debug-trace-\d{4}-\d\d-\d\d_\d\d\.\d\d\.\d\d\.txt'), 'debug-trace-<time>.txt'),
|
||||
(re.compile(r'after [0-9.]+ second\(s\) and \d+ tick\(s\) \([0-9.,NaInfity]+ tick\(s\) per second\)'), 'after <time>'),
|
||||
(re.compile(r'Average time per tick: [0-9.]+ms'), 'Average time per tick: <ms>'),
|
||||
(re.compile(r'P50: [0-9.]+ms P95: [0-9.]+ms P99: [0-9.]+ms'), 'P50: <ms> P95: <ms> P99: <ms>'),
|
||||
(re.compile(r'debug/client-[0-9_.-]+\.(jfr|json)'), 'debug/client-<time>'),
|
||||
]
|
||||
|
||||
|
||||
GAMERULES = re.compile(r'/gamerule \(([^)]*)\)')
|
||||
|
||||
|
||||
def masked(record):
|
||||
text = json.dumps(record['messages'], ensure_ascii=False)
|
||||
# GameRuleCommand registers the rules in identity-hash order, different
|
||||
# in every JVM: compare /help's gamerule alternatives as a set.
|
||||
text = GAMERULES.sub(lambda m: '/gamerule (' + '|'.join(sorted(m.group(1).split('|'))) + ')', text)
|
||||
for pattern, replacement in MASKS:
|
||||
text = pattern.sub(replacement, text)
|
||||
return text
|
||||
|
||||
|
||||
def compare(v, r):
|
||||
if masked(v) != masked(r):
|
||||
return 'messages'
|
||||
if v['results'] != r['results']:
|
||||
if v['cmd'].startswith('/debug stop'):
|
||||
return None
|
||||
return 'results'
|
||||
return None
|
||||
|
||||
|
||||
def render(record):
|
||||
lines = [''.join(span[0] for span in m) for m in record['messages']]
|
||||
return json.dumps({'messages': lines, 'styles': [[span[1] for span in m] for m in record['messages']], 'results': record['results']}, ensure_ascii=False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -16,6 +16,10 @@ Then every file is compared: region files chunk by chunk, NBT files and JSON
|
||||
files value by value (compound and object key order does not matter). The only
|
||||
tolerated differences are listed in IGNORED (wall-clock time).
|
||||
|
||||
tools/parity.py runs it in PARITY_SHARDS parts, each upgrading its share of
|
||||
the worlds (PARITY_SHARD=i/n). The vanilla outputs stay in .local/datafix/run
|
||||
so that the oracle's results are reused while its inputs are unchanged.
|
||||
|
||||
test_datafix_parity.py [--keep] [--skip-build] [VERSION...]
|
||||
"""
|
||||
import argparse
|
||||
@@ -35,6 +39,15 @@ LOCAL = ROOT / '.local' / 'datafix'
|
||||
WORLDS = (ROOT / '.local' / 'minecraft').resolve().parent / 'datafix' / 'worlds'
|
||||
RUN = LOCAL / 'run'
|
||||
|
||||
PARITY_SHARDS = 6
|
||||
# What the datafix_world probe can reach, checked by tools/parity.py: it reruns
|
||||
# this harness only when these sources (or the harness, oracle and data) change.
|
||||
PARITY_RUST_SCOPE = [
|
||||
'crates/horizon-world/src/datafix/', 'crates/horizon-world/src/nbt.rs', 'crates/horizon-world/src/region.rs',
|
||||
'crates/horizon-world/src/compression.rs', 'crates/horizon-core/src/position.rs', 'crates/horizon-core/src/position/',
|
||||
'crates/horizon-core/src/geometry/',
|
||||
]
|
||||
|
||||
IGNORED = {
|
||||
r'^level\.dat\.Data\.LastPlayed$': 'wall-clock time of the upgrade',
|
||||
}
|
||||
@@ -46,7 +59,7 @@ def java_classpath():
|
||||
import test_model_baking_parity as baking
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
libraries = baking.client_libraries()
|
||||
build = LOCAL / 'build'
|
||||
build = LOCAL / 'build' / os.environ.get('PARITY_SHARD', 'all').replace('/', '-') # shards compile apart
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
classes, dependencies, _ = harness.compile_oracle(build, 'VanillaDataFixOracle', jars, libraries,
|
||||
lock['minecraft']['java_major'])
|
||||
@@ -61,8 +74,17 @@ def build_rust():
|
||||
return Path(meta['target_directory']) / 'release' / 'examples' / 'datafix_world'
|
||||
|
||||
|
||||
def shard(items):
|
||||
"""This run's share of items when tools/parity.py runs the harness in parts (PARITY_SHARD=i/n)."""
|
||||
spec = os.environ.get('PARITY_SHARD')
|
||||
if not spec:
|
||||
return items
|
||||
index, count = map(int, spec.split('/'))
|
||||
return items[index - 1::count]
|
||||
|
||||
|
||||
def run_vanilla(classpath, world, out):
|
||||
shutil.rmtree(out, ignore_errors=True)
|
||||
# The oracle replaces OUT itself: left in place, an unchanged run's outputs can be reused.
|
||||
log = out.parent / (out.name + '.log')
|
||||
with log.open('w') as f:
|
||||
subprocess.run(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', classpath,
|
||||
@@ -195,7 +217,7 @@ def main():
|
||||
print('generating sample worlds:', ' '.join(missing), flush=True)
|
||||
subprocess.run([sys.executable, str(ROOT / 'tools' / 'datafix_worlds.py'), *missing], cwd=ROOT, check=True)
|
||||
worlds = sorted(p.name for p in WORLDS.iterdir() if p.is_dir())
|
||||
versions = args.versions or worlds
|
||||
versions = shard(args.versions or worlds)
|
||||
classpath = java_classpath()
|
||||
binary = None if args.vanilla_only else Path(args.binary) if args.binary else build_rust()
|
||||
total = 0
|
||||
@@ -214,7 +236,8 @@ def main():
|
||||
if binary is not None:
|
||||
print('datafix parity', 'FAILED' if total else 'ok', f'({total} differences over {len(versions)} worlds)')
|
||||
if not total and not args.keep:
|
||||
shutil.rmtree(RUN, ignore_errors=True)
|
||||
for version in versions: # vanilla outputs stay, for reuse
|
||||
shutil.rmtree(RUN / f'{version}-horizon', ignore_errors=True)
|
||||
sys.exit(1 if total else 0)
|
||||
|
||||
|
||||
|
||||
+81
-54
@@ -1,15 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the in-game HUD decorations with the vanilla 26.3 client's Hud.
|
||||
"""Compare the in-game HUD with the vanilla 26.3 client's Hud.
|
||||
|
||||
The Java oracle (VanillaHudOracle) runs vanilla's own Hud.extractCrosshair,
|
||||
extractItemHotbar, extractPlayerHealth, extractVehicleHealth, ExperienceBar
|
||||
and ContextualBar.extractExperienceLevel on a stand-in client whose player
|
||||
answers from the case, and records every blit (sprite, position, size,
|
||||
partial region), text call (string, position, colour, shadow) and hotbar
|
||||
item (slot, position, seed, pose). `examples/hud_fixture` lays out the same
|
||||
state with `horizon_client::hud_layout`; the ordered call lists must agree.
|
||||
The Java oracle (VanillaHudOracle) runs vanilla's own code on a stand-in
|
||||
client whose player answers from the case, and records every
|
||||
GuiGraphicsExtractor blit (sprite, texture, position, size, region, colour,
|
||||
pose), fill, text call (string, style runs, position, colour, shadow, pose)
|
||||
and hotbar item (slot, position, seed, pose). `examples/hud_fixture` lays
|
||||
out the same state with `horizon_client::hud_layout`, `hud_overlays` and
|
||||
`chat`; the ordered call lists (and any state read back) must agree.
|
||||
|
||||
test_hud_parity.py [--count N] [--detail N]
|
||||
Case kinds (`tools/hud_parity_cases.py`), drawn round-robin:
|
||||
decorations extractCrosshair, extractItemHotbar, extractPlayerHealth,
|
||||
extractVehicleHealth, ExperienceBar and the level
|
||||
effects extractEffects (MobEffectInstance order, blinking icons)
|
||||
title setTitle/setTimes/setOverlayMessage and Hud.tick, then
|
||||
extractOverlayMessage and extractTitle (fades, backdrops)
|
||||
selected Hud.tick's tool highlight, then extractSelectedItemName
|
||||
boss BossHealthOverlay
|
||||
jump JumpableVehicleBar
|
||||
sidebar displayScoreboardSidebar (teams, number formats)
|
||||
decor GuiGraphicsExtractor.itemDecorations (count, bar, cooldown)
|
||||
overlays extractCameraOverlays (vignette, spyglass and scopeScale,
|
||||
pumpkin, powder snow, portal, nausea) and extractSleepOverlay
|
||||
chat ChatComponent: wrapping (StringSplitter, indents), fades,
|
||||
tags, scale, width, height and spacing options
|
||||
|
||||
test_hud_parity.py [--count N] [--detail N] [--kind K]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
@@ -20,62 +36,69 @@ import sys
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
from .hud_parity_cases import KINDS
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
from hud_parity_cases import KINDS
|
||||
|
||||
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
|
||||
EFFECTS = ['minecraft:poison', 'minecraft:wither', 'minecraft:regeneration', 'minecraft:hunger', 'minecraft:speed']
|
||||
|
||||
|
||||
def cases(count):
|
||||
def cases(count, kinds):
|
||||
rng = random.Random(0x485544)
|
||||
out = []
|
||||
for n in range(count):
|
||||
max_health = rng.choice([20.0, 20.0, 6.0, 40.0, 33.0, 100.0])
|
||||
health = rng.choice([max_health, round(rng.uniform(0, max_health), 2), 1.0, 0.5, 3.0])
|
||||
air_max = 300
|
||||
under = rng.random() < 0.3
|
||||
air = rng.choice([air_max, rng.randint(-20, air_max), 0, 1, 29, 30, 31, 299]) if under or rng.random() < 0.2 else air_max
|
||||
case = {
|
||||
'width': rng.choice([427, 320, 480, 640, 961]), 'height': rng.choice([240, 255, 270, 360, 501]),
|
||||
'gameMode': rng.choice(['survival'] * 5 + ['adventure', 'creative', 'spectator']),
|
||||
'crosshair': rng.random() < 0.7,
|
||||
'attackIndicator': rng.choice(['OFF', 'CROSSHAIR', 'HOTBAR']),
|
||||
'attackScale': rng.choice([1.0, round(rng.random(), 3), 0.0, 0.999]),
|
||||
'selected': rng.randint(0, 8), 'rightHanded': rng.random() < 0.7,
|
||||
'slots': [rng.choice([None, 0, 0, 3, 5]) if rng.random() < 0.6 else None for _ in range(9)],
|
||||
'offhand': rng.choice([None, None, 0, 4]), 'partial': round(rng.random(), 3),
|
||||
'health': health, 'maxHealth': max_health,
|
||||
'absorption': rng.choice([0.0, 0.0, 4.0, 3.5, 17.0, 40.0]),
|
||||
'armor': rng.choice([0, 0, 1, 7, 20, 13]), 'food': rng.randint(0, 20),
|
||||
'saturation': rng.choice([0.0, 5.0, 0.0]),
|
||||
'effects': [e for e in EFFECTS if rng.random() < 0.15], 'frozen': rng.random() < 0.08,
|
||||
'hardcore': rng.random() < 0.2, 'damageCooldown': rng.choice([0, 0, 10]),
|
||||
'air': air, 'maxAir': air_max, 'underWater': under,
|
||||
'tick': rng.randint(0, 100000), 'lastHealth': rng.randint(0, 40), 'displayHealth': rng.randint(0, 40),
|
||||
'lastHealthAgo': rng.choice([0, 500, 5000]), 'healthBlinkTime': 0,
|
||||
'xpProgress': rng.choice([0.0, round(rng.random(), 4), 0.999]), 'xpLevel': rng.choice([0, 1, 7, 30, 123, 4000]),
|
||||
'experienceBar': rng.random() < 0.8,
|
||||
}
|
||||
if case['damageCooldown'] and rng.random() < 0.5:
|
||||
case['healthBlinkTime'] = case['tick'] + rng.randint(1, 20)
|
||||
if rng.random() < 0.15:
|
||||
case['vehicleMaxHealth'] = rng.choice([15.0, 30.0, 53.0, 100.0])
|
||||
case['vehicleHealth'] = round(rng.uniform(0, case['vehicleMaxHealth']), 1)
|
||||
kind = kinds[n % len(kinds)]
|
||||
case = KINDS[kind](rng, n)
|
||||
case['kind'] = kind
|
||||
out.append(case)
|
||||
return out
|
||||
|
||||
|
||||
def close(p, q):
|
||||
if (isinstance(p, float) or isinstance(q, float)) and not isinstance(p, bool) and not isinstance(q, bool):
|
||||
return abs(p - q) <= 1e-4 * (1 + abs(p))
|
||||
return p == q
|
||||
|
||||
|
||||
IDENTITY = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
|
||||
|
||||
|
||||
def normal(d):
|
||||
d = dict(d)
|
||||
d.setdefault('matrix', IDENTITY)
|
||||
if d['type'] == 'sprite':
|
||||
d.setdefault('region', None)
|
||||
if d['type'] == 'text':
|
||||
d.setdefault('runs', None)
|
||||
return d
|
||||
|
||||
|
||||
def same(x, y):
|
||||
if x.keys() != y.keys():
|
||||
return False
|
||||
for k in x:
|
||||
p, q = x[k], y[k]
|
||||
if isinstance(p, list) and isinstance(q, list):
|
||||
if len(p) != len(q) or not all(close(a, b) for a, b in zip(p, q)):
|
||||
return False
|
||||
elif not close(p, q):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--count', type=int, default=600)
|
||||
parser.add_argument('--count', type=int, default=2200)
|
||||
parser.add_argument('--detail', type=int, default=3)
|
||||
parser.add_argument('--kind', action='append', choices=sorted(KINDS), help='only these kinds (repeatable)')
|
||||
args = parser.parse_args()
|
||||
kinds = args.kind or list(KINDS)
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
libraries = baking.client_libraries()
|
||||
build = lab.LOCAL / 'rust-hud-parity'; build.mkdir(parents=True, exist_ok=True)
|
||||
resources = lab.LOCAL / 'horizon-client' / '26.3'
|
||||
chosen = cases(args.count)
|
||||
chosen = cases(args.count, kinds)
|
||||
inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
|
||||
classes = build / 'classes'; classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
|
||||
@@ -95,27 +118,31 @@ def main():
|
||||
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
|
||||
assert len(vanilla) == len(rust)
|
||||
errors, bad = [], []
|
||||
totals = {}
|
||||
for v, r in zip(vanilla, rust):
|
||||
kind = v['case']['kind']
|
||||
totals.setdefault(kind, [0, 0])[1] += 1
|
||||
if 'error' in v:
|
||||
errors.append(v['error']); continue
|
||||
a = [{k: x for k, x in d.items() if k != 'color' or d['type'] == 'text'} for d in v['draws']]
|
||||
for d in a:
|
||||
if d['type'] == 'sprite':
|
||||
d.setdefault('region', None)
|
||||
b = r['draws']
|
||||
def same(x, y):
|
||||
if x.keys() != y.keys():
|
||||
return False
|
||||
return all(
|
||||
(all(abs(p - q) <= 1e-4 * (1 + abs(p)) for p, q in zip(x[k], y[k])) if k == 'matrix' else x[k] == y[k]) for k in x)
|
||||
a = [normal(d) for d in v['draws']]
|
||||
b = [normal(d) for d in r['draws']]
|
||||
# State the case reads back besides the draws.
|
||||
for key in v.keys() - {'case', 'draws'}:
|
||||
if key not in r or not close(v[key], r[key]):
|
||||
a = a + [{'type': 'state', key: v[key]}]
|
||||
b = b + [{'type': 'state', key: r.get(key)}]
|
||||
if len(a) != len(b) or not all(same(x, y) for x, y in zip(a, b)):
|
||||
first = next((i for i, (x, y) in enumerate(zip(a, b)) if not same(x, y)), min(len(a), len(b)))
|
||||
bad.append((v['case'], first, a[first:first + 2], b[first:first + 2], len(a), len(b)))
|
||||
else:
|
||||
totals[kind][0] += 1
|
||||
for e in sorted(set(errors))[:5]:
|
||||
print('ORACLE ERROR', e)
|
||||
for case, i, a, b, la, lb in bad[:args.detail]:
|
||||
print('MISMATCH', json.dumps(case))
|
||||
print(f' at call {i} ({la} vanilla, {lb} Horizon calls)\n vanilla {a}\n horizon {b}')
|
||||
for kind, (ok, n) in sorted(totals.items()):
|
||||
print(f' {kind:12} {ok}/{n}')
|
||||
print(f'{len(vanilla) - len(bad) - len(errors)}/{len(vanilla)} HUD states match; {len(errors)} oracle errors')
|
||||
if bad or errors:
|
||||
sys.exit(1)
|
||||
|
||||
@@ -9,10 +9,14 @@ motion, rotations, running goals and target goals, attack target, navigation pat
|
||||
controls, movement input, brain activities and memories) and the sounds played; this harness
|
||||
reports, per scenario and mob, how many ticks match before the first divergence and what differs.
|
||||
|
||||
python3 tools/test_mob_ai_parity.py [--only NAME ...] [--rust-only] [--java-only] [--report-only]
|
||||
python3 tools/test_mob_ai_parity.py [--only NAME ...] [--rust-only] [--java-only] [--report-only] [--trace]
|
||||
|
||||
The oracle traces every mob random draw with its call stack; --trace builds the probe with
|
||||
the rng-trace feature and line tables so the report shows Horizon's draws next to vanilla's.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -200,6 +204,9 @@ def compare(vanilla, rust, fields=None):
|
||||
f'horizon {draws(prev_r, (b or {}).get("rng"))})')
|
||||
for line in [x for x in v.get('trace', {}).get(t, []) if x.split(' ', 1)[0] == str(mob)][:40]:
|
||||
report.append(' vanilla ' + line)
|
||||
# Present when the probe is built with the rng-trace feature (see --trace).
|
||||
for line in [x for x in r.get('trace', {}).get(t, []) if x.split(' ', 1)[0] == str(mob)][:40]:
|
||||
report.append(' horizon ' + line)
|
||||
report.extend(' ' + d for d in diffs[:12])
|
||||
if first is not None:
|
||||
clean = False
|
||||
@@ -221,6 +228,8 @@ def main():
|
||||
parser.add_argument('--java-only', action='store_true')
|
||||
parser.add_argument('--rust-only', action='store_true', help='reuse the last vanilla output')
|
||||
parser.add_argument('--report-only', action='store_true', help='print divergences without failing')
|
||||
parser.add_argument('--trace', action='store_true',
|
||||
help="also trace Horizon's mob random draws (rng-trace probe with line tables)")
|
||||
args = parser.parse_args()
|
||||
build = lab.LOCAL / 'mob-ai-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
@@ -231,13 +240,22 @@ def main():
|
||||
if not args.rust_only:
|
||||
classes, dependencies, _ = oracle_harness.compile_oracle(build, 'VanillaMobAiOracle', jars, baking.client_libraries(),
|
||||
lock['minecraft']['java_major'])
|
||||
# The oracle's server world: cleared before each run, never left in /tmp.
|
||||
world = build / 'world'
|
||||
shutil.rmtree(world, ignore_errors=True)
|
||||
oracle_harness.run_logged(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt'],
|
||||
'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world],
|
||||
build, 'vanilla', timeout=3600)
|
||||
if not args.java_only:
|
||||
oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'],
|
||||
build, 'compile-rust')
|
||||
binary = lab.cargo_target() / 'release/examples/mob_ai_probe'
|
||||
command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe']
|
||||
target, env = lab.cargo_target(), None
|
||||
if args.trace:
|
||||
target = lab.LOCAL / 'mob-ai-trace-target'
|
||||
command += ['--features', 'rng-trace']
|
||||
env = dict(os.environ, CARGO_TARGET_DIR=str(target), CARGO_PROFILE_RELEASE_DEBUG='line-tables-only',
|
||||
CARGO_PROFILE_RELEASE_LTO='false', CARGO_PROFILE_RELEASE_CODEGEN_UNITS='16')
|
||||
oracle_harness.run_logged(command, build, 'compile-rust', env=env)
|
||||
binary = target / 'release/examples/mob_ai_probe'
|
||||
oracle_harness.run_logged([binary, lab.ROOT / '.local/horizon-client/26.3', inputs, build / 'horizon.txt'], build, 'horizon')
|
||||
if args.java_only:
|
||||
return
|
||||
|
||||
@@ -127,7 +127,8 @@ def compare(reference, candidate):
|
||||
raise AssertionError('Parity outputs changed during comparison')
|
||||
|
||||
def run(command, **kwargs):
|
||||
subprocess.run(command, cwd=lab.ROOT, check=True, timeout=300, **kwargs)
|
||||
# A hang guard only: a loaded machine (14 harnesses at once on the Mac mini) can take minutes for one oracle.
|
||||
subprocess.run(command, cwd=lab.ROOT, check=True, timeout=900, **kwargs)
|
||||
|
||||
|
||||
def source_hashes(sources):
|
||||
|
||||
Reference in New Issue
Block a user