Add a knockback harness: a dedicated server against vanilla's

tools/test_server_knockback_parity.py runs vanilla's dedicated server and
Horizon's (`--dedicated --nogui`) on one flat world and joins both with two
vanilla-codec players (KnockbackClient):

- Alice hits a cow and a zombie (plain, sprinting, Knockback II, critical,
  in the air); the game is frozen around the hit and stepped a tick at a
  time, and the mob's Motion and Pos over 20 ticks are compared exactly;
- Alice hits Bob (the same, a shield, netherite, two hits, two sprinting
  hits, a mace smash, a stronger hit inside the hurt cooldown): Bob's own
  motion packets, Alice's and her sprint flag are compared;
- a zombie hits Bob twice: his motion packets.

7 of 21 cases match on main. KNOWN lists the other 14 with their causes:
the guest's server-side velocity never travels (knockback adds up from hit
to hit), the server never sends a guest its own sprint flag, the extra
knockback's direction uses f32 sin/cos instead of Mth's table, a hit in
the hurt cooldown still knocks back, and a mace smash on a player runs
none of MaceItem.hurtEnemy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-24 11:11:43 +02:00
parent c18f3dbfde
commit 50aee22996
2 changed files with 781 additions and 0 deletions
@@ -0,0 +1,444 @@
package dev.horizonlab.parity;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import net.minecraft.SharedConstants;
import net.minecraft.core.UUIDUtil;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.ProtocolInfo;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.common.ClientboundDisconnectPacket;
import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket;
import net.minecraft.network.protocol.common.ClientboundPingPacket;
import net.minecraft.network.protocol.common.ServerboundClientInformationPacket;
import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket;
import net.minecraft.network.protocol.common.ServerboundKeepAlivePacket;
import net.minecraft.network.protocol.common.ServerboundPongPacket;
import net.minecraft.network.protocol.common.custom.BrandPayload;
import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket;
import net.minecraft.network.protocol.configuration.ClientboundSelectKnownPacks;
import net.minecraft.network.protocol.configuration.ConfigurationProtocols;
import net.minecraft.network.protocol.configuration.ServerboundFinishConfigurationPacket;
import net.minecraft.network.protocol.configuration.ServerboundSelectKnownPacks;
import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket;
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
import net.minecraft.network.protocol.game.ClientboundSystemChatPacket;
import net.minecraft.network.protocol.game.GameProtocols;
import net.minecraft.network.protocol.game.ClientboundSetEntityMotionPacket;
import net.minecraft.network.protocol.game.ServerboundAttackPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket;
import net.minecraft.network.protocol.game.ServerboundPunchPacket;
import net.minecraft.network.protocol.game.ServerboundUseItemPacket;
import net.minecraft.world.InteractionHand;
import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket;
import net.minecraft.network.protocol.game.ServerboundChatCommandPacket;
import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket;
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket;
import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket;
import net.minecraft.network.protocol.handshake.ClientIntent;
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
import net.minecraft.network.protocol.handshake.HandshakeProtocols;
import net.minecraft.network.protocol.login.ClientboundLoginCompressionPacket;
import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket;
import net.minecraft.network.protocol.login.ClientboundLoginFinishedPacket;
import net.minecraft.network.protocol.login.LoginProtocols;
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
import net.minecraft.network.protocol.login.ServerboundLoginAcknowledgedPacket;
import net.minecraft.server.level.ClientInformation;
import net.minecraft.world.entity.PositionMoveRotation;
import net.minecraft.world.entity.player.Input;
import net.minecraft.world.phys.Vec3;
/**
* Players made of vanilla's own protocol code that hit and get hit, for
* knockback (tools/test_server_knockback_parity.py). Script on stdin:
* {@code step LABEL}, {@code join NAME}, {@code cmd NAME COMMAND...} (waits
* for its feedback), {@code pos NAME X Y Z YAW PITCH GROUND} (one client tick
* at that place, on the ground or not), {@code sprint NAME on|off}, {@code
* attack NAME TARGET} (ServerboundAttackPacket then the swing; TARGET is a
* player's name or an entity type's path, the last one added), {@code use
* NAME} (ServerboundUseItemPacket, main hand) and {@code end}. Each player
* records the ClientboundSetEntityMotionPacket it receives, its own sprint
* flag as the server sets it, teleports, and the system chat (command
* feedback).
*/
public final class KnockbackClient {
private static volatile String step = "start";
private static final Map<UUID, String> NAMES = new LinkedHashMap<>();
public static void main(String[] args) throws Exception {
ParityData.init();
String host = args[0];
int port = Integer.parseInt(args[1]);
Path output = Path.of(args[2]);
Map<String, Player> players = new LinkedHashMap<>();
BufferedReader script = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
String line;
while ((line = script.readLine()) != null) {
String[] w = line.trim().split(" ", 3);
try {
switch (w[0]) {
case "step" -> step = w[1];
case "join" -> {
Player p = new Player(w[1]);
players.put(w[1], p);
NAMES.put(UUIDUtil.createOfflinePlayerUUID(w[1]), w[1]);
p.join(host, port);
}
case "cmd" -> players.get(w[1]).command(w[2]);
case "pos" -> {
String[] a = w[2].split(" ");
players.get(w[1]).at(new Vec3(Double.parseDouble(a[0]), Double.parseDouble(a[1]), Double.parseDouble(a[2])),
Float.parseFloat(a[3]), Float.parseFloat(a[4]), a[5].equals("1"));
}
case "sprint" -> players.get(w[1]).sprint(w[2].equals("on"));
case "attack" -> players.get(w[1]).attack(w[2]);
case "use" -> players.get(w[1]).send(new ServerboundUseItemPacket(InteractionHand.MAIN_HAND, 0, 0, 0));
case "punch" -> players.get(w[1]).send(net.minecraft.network.protocol.game.ServerboundPunchPacket.INSTANCE);
case "mark" -> players.get(w[1]).mark();
case "await" -> players.get(w[1]).await();
case "end" -> {
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) {
for (Player p : players.values()) {
synchronized (p.lines) {
for (String l : p.lines) out.println(p.name + " " + l);
}
}
}
for (Player p : players.values()) p.close();
System.exit(0);
}
default -> throw new IllegalArgumentException("unknown script line " + line);
}
} catch (Exception e) {
Player p = w.length > 1 ? players.get(w[1]) : null;
if (p != null) p.record("error " + w[0] + " " + e);
else System.err.println("error " + line + ": " + e);
}
}
System.exit(1);
}
private static final class Player {
final String name;
final List<String> lines = new ArrayList<>();
private Socket socket;
private DataInputStream in;
private OutputStream out;
private int threshold = -1;
private ProtocolInfo<?> inbound;
private ProtocolInfo<?> outbound;
private volatile PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0);
private boolean loaded;
private volatile int id = -1;
/** Every entity this player was sent: its id to a name (players) or type path. */
private final Map<Integer, String> seen = new java.util.concurrent.ConcurrentHashMap<>();
private final Map<String, Integer> last = new java.util.concurrent.ConcurrentHashMap<>();
private final Object replyLock = new Object();
private int replies;
/** The motion packets about this player it was sent, and how many there were at the last `mark`. */
private int pushes;
private int marked;
Player(String name) {
this.name = name;
}
void command(String command) throws Exception {
synchronized (replyLock) {
int before = replies;
send(new ServerboundChatCommandPacket(command));
long until = System.nanoTime() + 30_000_000_000L;
while (replies == before) {
long left = (until - System.nanoTime()) / 1_000_000L;
if (left <= 0) {
record("error no reply to /" + command);
return;
}
replyLock.wait(left);
}
}
}
void mark() {
synchronized (replyLock) {
marked = pushes;
}
}
/** Waits for a motion packet about this player since the last `mark` (a mob's hit, which comes when its AI
* strikes). */
void await() throws Exception {
synchronized (replyLock) {
long until = System.nanoTime() + 20_000_000_000L;
while (pushes == marked) {
long left = (until - System.nanoTime()) / 1_000_000L;
if (left <= 0) {
record("error no motion packet since the mark");
return;
}
replyLock.wait(left);
}
}
}
void record(String line) {
synchronized (lines) {
lines.add("step=" + step + " " + line);
}
}
void at(Vec3 to, float yaw, float pitch, boolean ground) throws Exception {
position = new PositionMoveRotation(to, Vec3.ZERO, yaw, pitch);
// A tick of its own: the server takes one position per client tick (receivedPositionThisTick).
send(net.minecraft.network.protocol.game.ServerboundClientTickEndPacket.INSTANCE);
send(new ServerboundMovePlayerPacket.PosRot(to, yaw, pitch, ground, false));
send(net.minecraft.network.protocol.game.ServerboundClientTickEndPacket.INSTANCE);
}
void sprint(boolean on) throws Exception {
// ServerboundPlayerCommandPacket's only public constructors take an Entity: read it from its bytes.
FriendlyByteBuf b = new FriendlyByteBuf(Unpooled.buffer());
b.writeVarInt(id);
b.writeVarInt((on ? ServerboundPlayerCommandPacket.Action.START_SPRINTING : ServerboundPlayerCommandPacket.Action.STOP_SPRINTING).ordinal());
b.writeVarInt(0);
send(ServerboundPlayerCommandPacket.STREAM_CODEC.decode(b));
}
void attack(String target) throws Exception {
Integer entity = last.get(target);
if (entity == null) {
record("error no " + target + " to attack");
return;
}
send(new ServerboundAttackPacket(entity));
send(ServerboundPunchPacket.INSTANCE);
}
void close() throws Exception {
if (socket != null) socket.close();
}
void join(String host, int port) throws Exception {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 10_000);
socket.setTcpNoDelay(true);
in = new DataInputStream(socket.getInputStream());
out = socket.getOutputStream();
outbound = HandshakeProtocols.SERVERBOUND;
send(new ClientIntentionPacket(SharedConstants.getProtocolVersion(), host, port, ClientIntent.LOGIN));
outbound = LoginProtocols.SERVERBOUND;
inbound = LoginProtocols.CLIENTBOUND;
send(new ServerboundHelloPacket(name, UUIDUtil.createOfflinePlayerUUID(name)));
while (true) {
Packet<?> p = read().packet;
if (p instanceof ClientboundLoginCompressionPacket c) {
threshold = c.getCompressionThreshold();
} else if (p instanceof ClientboundLoginFinishedPacket) {
send(ServerboundLoginAcknowledgedPacket.INSTANCE);
break;
} else if (p instanceof ClientboundLoginDisconnectPacket d) {
throw new IllegalStateException("login refused: " + d.reason().getString());
}
}
outbound = ConfigurationProtocols.SERVERBOUND;
inbound = ConfigurationProtocols.CLIENTBOUND;
send(new ServerboundCustomPayloadPacket(new BrandPayload("vanilla")));
send(new ServerboundClientInformationPacket(ClientInformation.createDefault()));
while (true) {
Packet<?> p = read().packet;
if (p instanceof ClientboundSelectKnownPacks k) {
send(new ServerboundSelectKnownPacks(k.knownPacks()));
} else if (p instanceof ClientboundKeepAlivePacket k) {
send(new ServerboundKeepAlivePacket(k.getId()));
} else if (p instanceof ClientboundPingPacket k) {
send(new ServerboundPongPacket(k.getId()));
} else if (p instanceof ClientboundFinishConfigurationPacket) {
send(ServerboundFinishConfigurationPacket.INSTANCE);
break;
} else if (p instanceof ClientboundDisconnectPacket d) {
throw new IllegalStateException("disconnected: " + d.reason().getString());
}
}
GameProtocols.Context context = new GameProtocols.Context() {
@Override
public boolean hasInfiniteMaterials() {
return true;
}
@Override
public boolean canUseCommandBlocks() {
return true;
}
};
outbound = GameProtocols.SERVERBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access), context);
inbound = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(ParityData.access));
Thread reader = new Thread(this::play, name);
reader.setDaemon(true);
reader.start();
}
private void play() {
try {
while (true) {
Received r = read();
Packet<?> p = r.packet;
if (p instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket l) {
id = l.playerId();
seen.put(id, "self");
} else if (p instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket a) {
String who = a.getType() == net.minecraft.world.entity.EntityTypes.PLAYER
? NAMES.getOrDefault(a.getUUID(), "uuid?")
: net.minecraft.core.registries.BuiltInRegistries.ENTITY_TYPE.getKey(a.getType()).getPath();
seen.put(a.getId(), who);
last.put(who, a.getId());
} else if (p instanceof ClientboundSetEntityMotionPacket m) {
Vec3 v = m.movement();
record(String.format(java.util.Locale.ROOT, "motion %s %.5f %.5f %.5f",
seen.getOrDefault(m.id(), "id" + m.id()), v.x, v.y, v.z));
if (m.id() == id) {
synchronized (replyLock) {
pushes++;
replyLock.notifyAll();
}
}
} else if (p instanceof net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket d && d.id() == id) {
for (var value : d.packedItems()) {
if (value.id() == 0) record("sprinting " + ((((Byte) value.value()) & 8) != 0));
}
} else if (p instanceof ClientboundSystemChatPacket c) {
record("chat " + c.content().getString());
synchronized (replyLock) {
replies++;
replyLock.notifyAll();
}
} else if (p instanceof ClientboundKeepAlivePacket k) {
send(new ServerboundKeepAlivePacket(k.getId()));
} else if (p instanceof ClientboundPingPacket k) {
send(new ServerboundPongPacket(k.getId()));
} else if (p instanceof ClientboundPlayerPositionPacket t) {
position = PositionMoveRotation.calculateAbsolute(position, t.change(), t.relatives());
Vec3 at = position.position();
if (loaded) {
record(String.format(java.util.Locale.ROOT, "teleport %.3f %.3f %.3f", at.x, at.y, at.z));
}
send(new ServerboundAcceptTeleportationPacket(t.id(), at.x, at.y, at.z, position.yRot(), position.xRot()));
if (!loaded) {
send(new ServerboundMovePlayerPacket.PosRot(at, position.yRot(), position.xRot(), false, false));
send(new ServerboundPlayerLoadedPacket());
loaded = true;
}
} else if (p instanceof ClientboundChunkBatchFinishedPacket) {
send(new ServerboundChunkBatchReceivedPacket(64.0F));
} else if (p instanceof ClientboundDisconnectPacket d) {
record("disconnected " + d.reason().getString());
return;
}
}
} catch (Exception e) {
if (!socket.isClosed()) record("error play " + e);
}
}
private record Received(Packet<?> packet, byte[] payload) {}
private Received read() throws Exception {
byte[] payload = readFrame();
ByteBuf buf = Unpooled.wrappedBuffer(payload);
Packet<?> packet = inbound.codec().decode(buf);
if (buf.readableBytes() > 0) {
throw new IllegalStateException(packet.type().id() + " was larger than expected: " + buf.readableBytes() + " bytes left");
}
return new Received(packet, payload);
}
synchronized void send(Packet<?> packet) throws Exception {
ByteBuf body = Unpooled.buffer();
((ProtocolInfo) outbound).codec().encode(body, packet);
byte[] raw = new byte[body.readableBytes()];
body.readBytes(raw);
ByteBuf frame = Unpooled.buffer();
if (threshold >= 0) {
ByteBuf inner = Unpooled.buffer();
if (raw.length >= threshold) {
writeVarInt(inner, raw.length);
Deflater d = new Deflater();
d.setInput(raw);
d.finish();
byte[] tmp = new byte[raw.length + 64];
while (!d.finished()) inner.writeBytes(tmp, 0, d.deflate(tmp));
d.end();
} else {
writeVarInt(inner, 0);
inner.writeBytes(raw);
}
writeVarInt(frame, inner.readableBytes());
frame.writeBytes(inner);
} else {
writeVarInt(frame, raw.length);
frame.writeBytes(raw);
}
byte[] bytes = new byte[frame.readableBytes()];
frame.readBytes(bytes);
out.write(bytes);
out.flush();
}
private byte[] readFrame() throws Exception {
byte[] frame = new byte[readVarInt(in)];
in.readFully(frame);
if (threshold < 0) return frame;
ByteArrayInputStream header = new ByteArrayInputStream(frame);
int dataLength = readVarInt(header);
int skip = frame.length - header.available();
if (dataLength == 0) return java.util.Arrays.copyOfRange(frame, skip, frame.length);
Inflater inflater = new Inflater();
inflater.setInput(frame, skip, frame.length - skip);
byte[] raw = new byte[dataLength];
int n = inflater.inflate(raw);
inflater.end();
if (n != dataLength) throw new IllegalStateException("decompressed " + n + " of " + dataLength + " bytes");
return raw;
}
}
private static int readVarInt(InputStream in) throws Exception {
int value = 0;
for (int shift = 0; shift < 35; shift += 7) {
int b = in.read();
if (b < 0) throw new java.io.EOFException();
value |= (b & 0x7F) << shift;
if ((b & 0x80) == 0) return value;
}
throw new IllegalStateException("VarInt too big");
}
private static void writeVarInt(ByteBuf buf, int value) {
while ((value & ~0x7F) != 0) {
buf.writeByte((value & 0x7F) | 0x80);
value >>>= 7;
}
buf.writeByte(value);
}
}
+337
View File
@@ -0,0 +1,337 @@
#!/usr/bin/env python3
"""Knockback on a dedicated server, against vanilla's, seen by vanilla clients.
A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat
world vanilla generated first, in survival on Normal, with Alice and Bob as operators. KnockbackClient, two
players made of vanilla's protocol code, joins them both and runs one script on each:
- Alice hits a cow and a zombie: a plain hit, a sprinting hit, Knockback II, a critical hit, and a plain hit on
a mob in the air. The game is frozen around the hit (`/tick freeze`) and stepped a tick at a time: the mob's
Motion just after the hit and its Pos and Motion over the next 20 ticks are compared exactly. The mobs are
slowed to a stop (Slowness 128) so that their walking adds nothing;
- Alice hits Bob: a plain hit, sprinting, Knockback II, a critical hit, Bob behind a raised shield, Bob in
netherite (knockback resistance), two plain hits a second apart, two sprinting hits a second apart (the
first stops Alice's sprint), a mace smash, and a weak hit then a stronger one inside Bob's hurt cooldown.
Bob's own ClientboundSetEntityMotionPacket (the knockback his client applies, Player.causeExtraKnockback),
Alice's motion packets and her sprint flag as the server sets it are compared exactly;
- a zombie hits Bob, twice: the knockback reaches Bob's client once his server-side copy has
travelled a tick (the mob's hit, then ServerPlayer's travel, then ServerEntity.sendChanges). It is night, so
that no zombie burns (a burning mob is in its hurt cooldown).
Each case is compared on its own. KNOWN lists the cases Horizon still gets wrong and why; one that matches
again is reported, and should leave the list.
"""
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
import time
try:
from . import lab, test_rust_parity as base
from .test_dedicated_server_parity import Server, free_port
from .test_locator_bar_parity import generate_world, ops_json
except ImportError:
import lab
import test_rust_parity as base
from test_dedicated_server_parity import Server, free_port
from test_locator_bar_parity import generate_world, ops_json
NAME = 'server-knockback-parity'
PROPERTIES = {
'online-mode': 'false',
'white-list': 'false',
'level-seed': '12345',
'level-type': 'minecraft\\:flat',
'generate-structures': 'false',
'gamemode': 'survival',
'difficulty': 'normal',
'view-distance': '4',
'simulation-distance': '4',
'spawn-protection': '0',
'max-players': '5',
'pause-when-empty-seconds': '-1',
}
# Cases Horizon still gets wrong, and why.
VELOCITY = ("a guest's server-side velocity never travels and a hit is sent before it would: each knockback starts "
"from the last one's (ServerPlayer's travel, ServerEntity.sendChanges, Player.causeExtraKnockback)")
SPRINT = "the server never sends a guest its own sprint flag, so a sprint hit doesn't stop the attacker's sprint"
YAW = "the extra knockback's direction comes from f32 sin/cos, not Mth's sine table (z is -2e-8 a block, not 0)"
KNOWN = {
'cow-sprint': f'{SPRINT}; {YAW}',
'cow-knockback-2': YAW,
'zombie-sprint': f'{SPRINT}; {YAW}',
'zombie-knockback-2': YAW,
'pvp-plain': VELOCITY,
'pvp-sprint': f'{VELOCITY}; {SPRINT}',
'pvp-knockback-2': VELOCITY,
'pvp-crit': VELOCITY,
'pvp-netherite': VELOCITY,
'pvp-twice': VELOCITY,
'pvp-sprint-twice': f'{VELOCITY}; {SPRINT}',
'pvp-mace': f'{VELOCITY}; a smash on a player runs none of MaceItem.hurtEnemy (the attacker\'s fall goes on)',
'pvp-cooldown': f'{VELOCITY}; a hit inside the hurt cooldown still knocks back (LivingEntity.hurtServer)',
'zombie-hits-bob': VELOCITY,
}
A = (0.5, -60.0, 0.5) # Alice, facing east (yaw -90)
V = (2.5, -60.0, 0.5) # the mob or Bob, two blocks east
SWORD = 'minecraft:wooden_sword'
KNOCKBACK_SWORD = 'minecraft:wooden_sword[enchantments={"minecraft:knockback":2}]'
def stand(name, at, yaw, ticks=3):
"""Client ticks on the ground at `at` (one position a tick, as vanilla's client sends)."""
return [f'pos {name} {at[0]} {at[1]} {at[2]} {yaw} 0 1'] * ticks
def falling(height):
"""Alice off the ground and going down, so that her next hit is critical (or a mace smash)."""
return [f'pos Alice {A[0]} {A[1] + h} {A[2]} -90 0 0' for h in (height, height - 0.3)]
def mob_case(kind, weapon=SWORD, sprint=False, crit=False, air=False):
mob = f'@e[type=minecraft:{kind},limit=1]'
summon = [f'cmd Alice summon minecraft:{kind} {V[0]} {V[1] + (1.5 if air else 0)} {V[2]} {{Rotation:[0f,0f]}}',
f'cmd Alice effect give {mob} minecraft:slowness 100000 127 true']
lines = ['cmd Alice kill @e[type=!player]', 'cmd Alice gamemode creative', 'cmd Bob gamemode creative',
f'cmd Alice item replace entity @s weapon.mainhand with {weapon}', 'cmd Alice tp Bob 2.5 -60 12.5',
*stand('Alice', A, -90), 'sleep 1.2']
# In the air: frozen before its first tick, so it has not landed.
lines += ['cmd Alice tick freeze', *summon] if air else [*summon, 'sleep 1.5', 'cmd Alice tick freeze']
lines += ['sleep 0.3', f'cmd Alice data get entity {mob} Pos']
if sprint:
lines.append('sprint Alice on')
if crit:
lines += falling(0.8)
lines += ['sleep 0.2', f'attack Alice {kind}', 'sleep 0.2', f'cmd Alice data get entity {mob} Motion']
for _ in range(20):
lines += ['cmd Alice tick step 1', 'sleep 0.25', f'cmd Alice data get entity {mob} Pos',
f'cmd Alice data get entity {mob} Motion']
lines += ['cmd Alice tick unfreeze', 'cmd Alice kill @e[type=!player]']
if sprint:
lines.append('sprint Alice off')
lines += [*stand('Alice', A, -90), 'cmd Alice gamemode survival', 'cmd Bob gamemode survival',
f'cmd Alice tp Bob {V[0]} {V[1]} {V[2]} 90 0']
return lines
def pvp_case(weapon=SWORD, sprint=False, crit=False, shield=False, armour=False, twice=False, mace=False,
cooldown=False):
lines = [f'cmd Alice item replace entity @s weapon.mainhand with {weapon}', 'cmd Bob clear @s',
'cmd Bob effect give @s minecraft:resistance 1000 4 true',
'cmd Bob effect give @s minecraft:instant_health 1 5 true', *stand('Alice', A, -90), *stand('Bob', V, 90)]
if armour:
lines += [f'cmd Bob item replace entity @s armor.{slot} with minecraft:netherite_{piece}'
for slot, piece in (('head', 'helmet'), ('chest', 'chestplate'), ('legs', 'leggings'),
('feet', 'boots'))]
if shield:
# A shield blocks from five ticks after it is raised.
lines += ['cmd Bob item replace entity @s weapon.mainhand with minecraft:shield', 'use Bob']
lines += ['sleep 1.5', *stand('Bob', V, 90, ticks=1)]
if sprint:
lines.append('sprint Alice on')
if crit:
lines += falling(0.8)
if mace:
lines += falling(3.0) + falling(1.5)
if cooldown:
# A swing at the air first: the hit is weak, and the stronger one four ticks later lands inside Bob's hurt
# cooldown (LivingEntity.hurtServer: it hurts by the difference, with no knockback and no motion packet).
lines += ['sleep 0.2', 'punch Alice', 'attack Alice Bob']
lines += ['sleep 0.2', 'attack Alice Bob', 'sleep 0.3']
if twice:
lines += [*stand('Bob', V, 90, ticks=20), 'sleep 1.5', 'attack Alice Bob', 'sleep 0.3']
if sprint:
lines.append('sprint Alice off')
lines += stand('Alice', A, -90)
if shield or armour:
lines.append('cmd Bob clear @s')
return lines
def mob_hits_case(kind):
"""A mob's own attack on Bob, twice: his motion packet. Alice is in creative, so the mob goes for Bob; each mob
is killed once its hit has come (`await`), and Bob stands back where he was before the next. (A mob with no
attack_knockback of its own: one with some, like a ravager, adds it along its own yaw, which its AI turns.)"""
mob = f'@e[type=minecraft:{kind},limit=1]'
hit = ['mark Bob', f'cmd Alice summon minecraft:{kind} {V[0] + 1} {V[1]} {V[2]} {{Rotation:[90f,0f]}}',
f'cmd Alice effect give {mob} minecraft:slowness 100000 127 true', 'await Bob', f'cmd Alice kill {mob}']
return ['cmd Bob clear @s', 'cmd Bob effect give @s minecraft:resistance 1000 4 true', 'cmd Alice gamemode creative',
*stand('Bob', V, 90), *hit, 'sleep 2', *stand('Bob', V, 90), *hit, 'sleep 1',
'cmd Alice kill @e[type=!player]', 'cmd Alice gamemode survival']
CASES = {
'cow-plain': mob_case('cow'),
'cow-sprint': mob_case('cow', sprint=True),
'cow-knockback-2': mob_case('cow', weapon=KNOCKBACK_SWORD),
'cow-crit': mob_case('cow', crit=True),
'cow-air': mob_case('cow', air=True),
'zombie-plain': mob_case('zombie'),
'zombie-sprint': mob_case('zombie', sprint=True),
'zombie-knockback-2': mob_case('zombie', weapon=KNOCKBACK_SWORD),
'zombie-crit': mob_case('zombie', crit=True),
'zombie-air': mob_case('zombie', air=True),
'pvp-plain': pvp_case(),
'pvp-sprint': pvp_case(sprint=True),
'pvp-knockback-2': pvp_case(weapon=KNOCKBACK_SWORD),
'pvp-crit': pvp_case(crit=True),
'pvp-shield': pvp_case(shield=True),
'pvp-netherite': pvp_case(armour=True),
'pvp-twice': pvp_case(twice=True),
'pvp-sprint-twice': pvp_case(sprint=True, twice=True),
'pvp-mace': pvp_case(weapon='minecraft:mace', mace=True),
'pvp-cooldown': pvp_case(cooldown=True),
'zombie-hits-bob': mob_hits_case('zombie'),
}
SETUP = ['cmd Alice gamerule spawn_mobs false', 'cmd Alice gamerule spawn_monsters false',
'cmd Alice kill @e[type=!player]', 'cmd Alice gamerule advance_time false', 'cmd Alice time set midnight',
f'cmd Alice tp Alice {A[0]} {A[1]} {A[2]} -90 0', f'cmd Alice tp Bob {V[0]} {V[1]} {V[2]} 90 0', 'sleep 2']
def server_dir(directory, world):
if directory.exists():
shutil.rmtree(directory)
directory.mkdir(parents=True)
port = free_port()
props = dict(PROPERTIES, **{'server-port': str(port)})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()),
encoding='iso-8859-1')
(directory / 'eula.txt').write_text('eula=true\n')
(directory / 'ops.json').write_text(ops_json())
shutil.copytree(world, directory / 'world')
(directory / 'world' / 'session.lock').unlink(missing_ok=True)
return port
def run_side(label, server_command, client_command, build, world):
directory = build / label
port = server_dir(directory, world)
out = build / f'{label}.txt'
out.unlink(missing_ok=True)
server = Server(server_command, directory, label)
try:
server.wait_for(r'Done \(')
with (build / f'{label}-client.log').open('w') as log:
client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)],
cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
text=True)
def send(line):
if line.startswith('sleep '):
time.sleep(float(line.split()[1]))
else:
client.stdin.write(line + '\n')
client.stdin.flush()
try:
for name in ('Alice', 'Bob'):
send(f'join {name}')
server.wait_for(rf'{name} joined the game', timeout=120)
time.sleep(2)
for line in SETUP:
send(line)
for case, lines in CASES.items():
send(f'step {case}')
for line in lines:
send(line)
time.sleep(0.5)
send('end')
client.wait(timeout=60)
finally:
if client.poll() is None:
client.kill()
finally:
server.stop()
if not out.exists():
raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)')
return out.read_text(encoding='utf-8').splitlines()
DATA = re.compile(r'^chat \S+ has the following entity data: \[(.*)\]$')
def compared(lines):
"""Per case, what is compared: the mob's Pos and Motion (to 1e-9), and each player's motion packets and
sprint flag."""
cases = {}
for line in lines:
who, step, text = line.split(' ', 2)
step = step.removeprefix('step=')
if step not in CASES:
continue
kept = cases.setdefault(step, [])
data = DATA.match(text)
if who == 'Alice' and data:
kept.append('data ' + ' '.join(f'{float(v.rstrip("d")):.9f}' for v in data.group(1).split(', ')))
elif text.startswith('motion self') or text.startswith('sprinting'):
kept.append(f'{who} {text}')
elif text.startswith('error') or text.startswith('disconnected'):
kept.append(f'{who} {text}')
return cases
def main():
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / NAME
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/KnockbackClient.java'
classes = build / 'classes'
shutil.rmtree(classes, ignore_errors=True)
classes.mkdir()
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
cwd=lab.ROOT, check=True, capture_output=True)
subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
check=True, capture_output=True)
import json
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')
vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui']
client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.KnockbackClient']
world = generate_world(vanilla_server, build)
vanilla = compared(run_side('vanilla', vanilla_server, client, build, world))
horizon = compared(run_side('horizon', horizon_server, client, build, world))
differ, fixed = [], []
for case in CASES:
want, got = vanilla.get(case, []), horizon.get(case, [])
if case not in vanilla or any(' error ' in f' {l} ' or 'disconnected' in l for l in want):
raise AssertionError(f'{case}: vanilla recorded nothing or failed: {want}')
if want == got:
if case in KNOWN:
fixed.append(case)
continue
if case in KNOWN:
continue
import difflib
differ.append(f'{case}:\n' + '\n'.join(difflib.unified_diff(want, got, 'vanilla', 'horizon', n=1, lineterm='')))
if fixed:
print('matching vanilla now, take them out of KNOWN: ' + ', '.join(fixed))
if differ:
raise AssertionError(f'{len(differ)} cases differ (see {build}/vanilla.txt and horizon.txt):\n'
+ '\n'.join(differ)[:8000])
lab.write_json(report, dict(
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
cases=len(CASES), known=sorted(KNOWN), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
scope='Knockback on a dedicated server, as two vanilla-codec players get it: a player hitting a cow and '
'a zombie (plain, sprinting, Knockback II, critical, in the air; the mob\'s motion and path over 20 '
'ticks), a player hitting a player (the same, a raised shield, netherite, two hits, a mace smash; '
'the victim\'s motion packet and the attacker\'s sprint) and a zombie hurting a player.'))
print(f'server knockback: {len(CASES) - len(KNOWN)} of {len(CASES)} cases identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')