Add a differential test of enchanting-table offers against vanilla

A Java oracle loads the vanilla data pack's enchantment registry, binds
item components and replays EnchantmentMenu's cost, clue and enchantment
selection draws; tools/test_enchanting_parity.py compares it with the Rust
stations module for every enchantable item and the book over 32 seeds and
7 bookshelf counts (51,744 lines match).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:47:03 +02:00
parent 1861320d75
commit 9a3bf42574
4 changed files with 210 additions and 0 deletions
@@ -0,0 +1,35 @@
//! Enchanting-table offers for differential tests against vanilla
//! (tools/test_enchanting_parity.py): reads "seed bookcases item" lines and
//! prints costs, clues and applied enchantments in the oracle's format.
//!
//! usage: enchanting_fixture RESOURCES INPUT OUTPUT
use horizon_client::{enchant::Enchantments, items::{ItemStack, Items}, stations};
use std::{fmt::Write as _, fs, path::Path};
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(args.get(1).ok_or("usage: enchanting_fixture RESOURCES INPUT OUTPUT")?);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::tags_only(root)?;
let e = Enchantments::load(root);
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split(' ').collect();
let (seed, bookcases, item): (i32, i32, &str) = (f[0].parse()?, f[1].parse()?, f[2]);
let stack = ItemStack::new(item, 1);
let offers = stations::enchant_offers(&e, &items, seed, bookcases, Some(&stack));
for i in 0..3 {
let cost = offers.costs[i];
let clue = offers.clues[i].as_ref().map_or("-".to_owned(), |(id, l)| format!("{id}:{l}"));
let applied = if cost > 0 {
let list = stations::enchantment_list(&e, &items, seed, i, cost, item);
if list.is_empty() { "-".to_owned() } else { list.iter().map(|(id, l)| format!("{id}:{l}")).collect::<Vec<_>>().join(",") }
} else {
"-".to_owned()
};
writeln!(out, "{line} {i} {cost} {clue} {applied}")?;
}
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
+4
View File
@@ -211,6 +211,10 @@ impl Items {
pub fn get(&self, id: &str) -> Option<&ItemInfo> {
self.items.get(id)
}
/// Only the block and item tags, for tools that need tag membership.
pub fn tags_only(root: &Path) -> Result<Self> {
Ok(Self { items: HashMap::new(), order: Vec::new(), block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, loot: HashMap::new() })
}
/// An item table with only tags, for unit tests of item rules.
#[cfg(test)]
pub fn for_tests(item_tags: HashMap<String, HashSet<String>>) -> Self {
@@ -0,0 +1,92 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.EnchantmentTags;
import net.minecraft.tags.TagLoader;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.item.enchantment.EnchantmentInstance;
/**
* Original oracle: loads the vanilla data pack's enchantment registry and
* replays the enchanting table offer computation (EnchantmentMenu.slotsChanged
* and getEnchantmentList) through EnchantmentHelper for fixture lines
* "seed bookcases item", printing costs, clues and the enchantments applied.
*/
public final class VanillaEnchantingOracle {
private static String name(EnchantmentInstance e) {
return e.enchantment().unwrapKey().get().identifier() + ":" + e.level();
}
private static List<EnchantmentInstance> list(RandomSource random, int seed, int slot, int cost, ItemStack stack, HolderSet.Named<Enchantment> table) {
random.setSeed(seed + slot);
List<EnchantmentInstance> list = EnchantmentHelper.selectEnchantment(random, stack, cost, table.stream());
if (stack.is(Items.BOOK) && list.size() > 1) {
list.remove(random.nextInt(list.size()));
}
return list;
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
Path in = Path.of(args[0]), out = Path.of(args[1]);
var repo = ServerPacksSource.createVanillaTrustedRepository();
repo.reload();
repo.setSelected(List.of("vanilla"));
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
var layers = RegistryLayer.createRegistryAccess();
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
staticTags.forEach(Registry.PendingTags::apply);
RegistryAccess access = layers.replaceFrom(RegistryLayer.WORLD, world).compositeAccess();
// Bind default item components (enchantable values) as server reloads do.
BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(access).forEach(p -> p.apply());
var table = world.lookupOrThrow(Registries.ENCHANTMENT).get(EnchantmentTags.IN_ENCHANTING_TABLE).orElseThrow();
RandomSource random = RandomSource.create(0L);
try (var w = new PrintWriter(Files.newBufferedWriter(out, StandardCharsets.UTF_8))) {
for (String line : Files.readAllLines(in, StandardCharsets.UTF_8)) {
String[] f = line.split(" ");
int seed = Integer.parseInt(f[0]), bookcases = Integer.parseInt(f[1]);
ItemStack stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(f[2])));
int[] costs = new int[3];
random.setSeed(seed);
for (int i = 0; i < 3; i++) {
costs[i] = EnchantmentHelper.getEnchantmentCost(random, i, bookcases, stack);
if (costs[i] < i + 1) costs[i] = 0;
}
for (int i = 0; i < 3; i++) {
String clue = "-";
String applied = "-";
if (costs[i] > 0) {
List<EnchantmentInstance> l = list(random, seed, i, costs[i], stack, table);
if (!l.isEmpty()) clue = name(l.get(random.nextInt(l.size())));
List<EnchantmentInstance> again = list(RandomSource.create(0L), seed, i, costs[i], stack, table);
StringBuilder sb = new StringBuilder();
for (var e : again) sb.append(sb.length() == 0 ? "" : ",").append(name(e));
if (sb.length() > 0) applied = sb.toString();
}
w.println(line + " " + i + " " + costs[i] + " " + clue + " " + applied);
}
}
}
}
}
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Compare enchanting-table offers (costs, clues, applied enchantments) with vanilla.
Java loads the vanilla data pack's enchantment registry and runs
EnchantmentHelper as EnchantmentMenu does; Rust runs horizon_client::stations
on the prepared resources. Every enchantable item and the book are tested
across seeds and bookshelf counts.
"""
import argparse
import json
import os
from pathlib import Path
import platform
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
def corpus(items):
rng = random.Random(0x454E4348414E54)
seeds = [-2147483648, -1, 0, 1, 2147483647, *[rng.randrange(-2**31, 2**31) for _ in range(27)]]
for item in items:
for seed in seeds:
for bookcases in [0, 1, 4, 8, 12, 15, 30]:
yield f"{seed} {bookcases} {item}"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'agents/stations/enchanting-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
catalog = json.loads((resources / 'items.json').read_text())
items = sorted(k for k, v in catalog.items() if 'minecraft:enchantable' in v)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/enchanting_fixture.rs',
*sorted((lab.ROOT / 'crates/horizon-client/src').glob('*.rs'))]
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
fixtures = list(corpus(items))
inputs.write_text(''.join(line + '\n' for line in fixtures), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'enchanting_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples' / ('enchanting_fixture.exe' if os.name == 'nt' else 'enchanting_fixture')
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
references = []
for side in ['server']:
run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars[side]), deps]), 'dev.horizonlab.parity.VanillaEnchantingOracle', inputs, build / f'{side}.txt'], side)
matched = base.compare(build / f'{side}.txt', build / 'rust.txt')
references.append({'side': side, 'jar_sha256': lab.digest(jars[side], 'sha256'), 'matched_output_lines': matched})
print(f'{side}: {matched:,} enchanting offer lines match Rust', flush=True)
base.ensure_sources_unchanged(sources, tested)
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'fixtures': len(fixtures),
'items': len(items), 'references': references, 'sources_sha256': tested,
'scope': 'EnchantmentHelper.getEnchantmentCost / selectEnchantment on the data-driven enchantment registry and '
'#in_enchanting_table, EnchantmentMenu clue draws and book removal, for every enchantable item and the book.'}
lab.write_json(build / 'report.json', report)
print(f'Enchanting parity passed: {build / "report.json"}')
if __name__ == '__main__':
main()