Faster green test suite

- Removed the core processResources skip that fired on test-only invocations, which packaged a core jar with no generation kernel catalog and made all 10 probe and bukkit-plugin tests that reach GenerationKernelRegistry fail on every ./gradlew test
- Set maxParallelForks on :core:test to half the available processors, overridable with -PtestForks, and left the small modules single-forked so they do not re-pay the Minecraft bootstrap per fork or steal worker leases from core
- Resolved B.registries() per bound platform instead of latching the first one for the JVM lifetime, keeping the previous unbound behaviour, so a test that binds its own platform no longer reads a foreign platform's block states
- Resolved IrisObject.States per bound platform through accessors instead of static finals fixed at class-init, removing the NoClassDefFoundError and null material-key failures that appeared whenever class partitioning changed
- Bound an explicit platform in EngineMantleCoverageTest and IrisDimensionStackActuatorMetadataTest so they no longer depend on another class leaking a binding first
- Gated BukkitSpiConformanceTest registry probes on a live RegistryAccess and restored the IrisPlatforms binding it leaked, which was silently swallowing the stderr two SettingsHotloadWatchTest assertions read
- Initialised org.bukkit.Registry and Biome inside the RegistryAccess mock scope in ObjectStudioGeometryTest so Mockito no longer instruments Registry mid-clinit
- Replaced the SettingsHotloadWatchTest fixed 1200ms diagnostic window with a 10ms condition poll bounded at 4s
- Replaced the IrisCaveCarver3DNearParityTest wall-clock speedup benchmark with a deterministic density-sample count, cutting 28 carves to 2
- Cut HydrologyPlannerTest cold-owner parity from 12 tile plans to 4 and shared the immutable baseline plan across the early-owner tests
- Built one prototype project or staged history per class in the jigsaw studio and world replacement tests and copied it per test, replacing repeated fsync-bound fixture construction
- Replaced Mockito block-state fixtures with concrete implementations in the object IO, deposit modifier and nearest-block-index tests, removing about 2.5 million interceptions
- Replaced Thread.sleep with bounded condition polling in HydrologyTileCacheTest
- Deleted 19 test classes and 60 further test methods that asserted on production .java source text rather than behaviour, and removed the 19 now-unread iris.*Source system properties that fed them
This commit is contained in:
Brian Neumann-Fopiano committed 2026-09-07 19:59:22 -04:00
1 parent d3245aa1c2
commit 266fe0d71c
66 files changed
+1481 -3238

No files matched your search

@@ -7,10 +7,7 @@ import net.minecraft.server.Bootstrap;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -24,104 +21,6 @@ public class CustomBiomeSourceStructureContractTest {
Bootstrap.bootStrap();
}
@Test
public void authoringBiomesBypassTerrainResolutionBeforeDestinationChunksGenerate() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
int visibleStart = source.indexOf("private Holder<Biome> getVisibleNoiseBiomeWithActiveGenerationLease(");
int visibleEnd = source.indexOf("private boolean isBiomeCacheable(", visibleStart);
String visible = source.substring(visibleStart, visibleEnd);
int constantBiome = visible.indexOf("platformGenerator.usesFlatStudioTerrain()");
int terrainResolution = visible.indexOf("resolveVisibleBiomeHolder(");
assertTrue(source.contains("platformGenerator.usesFlatStudioTerrain()"));
assertTrue(constantBiome >= 0);
assertTrue(visible.indexOf("return fallbackBiome;", constantBiome) < terrainResolution);
assertTrue(terrainResolution > constantBiome);
int structureStart = source.indexOf("private Holder<Biome> getStructureNoiseBiomeWithActiveGenerationLease(");
int structureEnd = source.indexOf("boolean cacheable", structureStart);
assertTrue(source.substring(structureStart, structureEnd).contains("platformGenerator.usesFlatStudioTerrain()"));
String generator = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource")));
int createBiomes = generator.indexOf("public CompletableFuture<ChunkAccess> createBiomes(");
int buildSurface = generator.indexOf("public void buildSurface(", createBiomes);
assertTrue(generator.substring(createBiomes, buildSurface)
.contains("customBiomeSource.getVisibleNoiseBiomeWithActiveGenerationLease("));
}
@Test
public void nativeStructuresUseTerrainSafeDerivativeAtEveryBiomeBoundary() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
assertTrue(source.contains("resolveBiomeHolder(registry, i.getStructureDerivativeKey())"));
assertTrue(source.contains("resolveBiomeHolder(biomeRegistry, irisBiome.getStructureDerivativeKey())"));
assertTrue(source.contains("resolution.irisBiome.getStructureDerivativeKey()"));
assertFalse(source.contains("resolution.irisBiome.getVanillaDerivative()"));
}
@Test
public void biomeRuntimeReadsAreGenerationLeased() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
assertTrue(source.contains("tryAcquireGenerationLease(\"bukkit_possible_biomes\")"));
assertTrue(source.contains("tryAcquireGenerationLease(\"bukkit_spawn_biome\")"));
assertFalse(source.contains("Iris spawn biome lookup was rejected during an engine transition"));
assertFalse(source.contains("Iris spawn biome lookup has no active engine runtime"));
assertTrue(source.contains("runtimeBiomeState().vanillaSpawnBiomes().get(biome.value())"));
assertTrue(source.contains("requireGenerationLease(\n \"bukkit_structure_biome\""));
assertTrue(source.contains("tryAcquireGenerationLease(\"bukkit_biomes_within\")"));
assertTrue(source.contains("requireGenerationLease(\n \"bukkit_visible_biome\""));
assertTrue(source.contains("if (engine.isClosed())"));
assertTrue(source.contains("engine.isClosing() || e.isExpectedTeardown()"));
assertTrue(source.contains("catch (GenerationSessionException e)"));
assertTrue(source.contains("e.isExpectedTeardown()"));
}
@Test
public void strongholdRingSearchSamplesOneQuartColumnPerChunk() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
assertTrue(source.contains("private static final int STRONGHOLD_RING_SEARCH_Y = 0"));
assertTrue(source.contains("private static final int STRONGHOLD_RING_SEARCH_RADIUS = 112"));
assertTrue(source.contains("private static final int STRONGHOLD_RING_SEARCH_QUART_STEP = 4"));
assertTrue(source.contains(
"return super.findBiomeHorizontal(x, y, z, searchRadius, allowed, random, sampler)"));
assertTrue(source.contains("tryAcquireGenerationLease(\"bukkit_structure_ring_biome\")"));
assertTrue(source.contains("findNaturalSurfaceBiomeHorizontal("));
assertTrue(source.contains("radius += quartStep"));
assertTrue(source.contains("offsetZ += quartStep"));
assertTrue(source.contains("offsetX += quartStep"));
assertTrue(source.contains("random.nextInt(matches + 1) == 0"));
}
@Test
public void onlyConcentricRingSuitabilityUsesTheNaturalTerrainStream() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
int realResolutionStart = source.indexOf("private Holder<Biome> resolveSurfaceStructureBiomeHolder(");
int naturalResolutionStart = source.indexOf(
"private Holder<Biome> resolveNaturalSurfaceStructureBiomeHolder(");
int resolutionEnd = source.indexOf("public Holder<Biome> getVisibleNoiseBiome(", naturalResolutionStart);
assertTrue(realResolutionStart >= 0);
assertTrue(naturalResolutionStart > realResolutionStart);
assertTrue(resolutionEnd > naturalResolutionStart);
String realResolution = source.substring(realResolutionStart, naturalResolutionStart);
String naturalResolution = source.substring(naturalResolutionStart, resolutionEnd);
assertTrue(realResolution.contains("resolveSurfaceStructureBiome(engine, blockX, blockZ)"));
assertFalse(realResolution.contains("getNaturalTrueBiomeStream()"));
assertTrue(naturalResolution.contains(
"engine.getComplex().getNaturalTrueBiomeStream().get(blockX, blockZ)"));
assertFalse(naturalResolution.contains("getTrueBiomeStream()"));
int helperStart = source.indexOf("private static IrisBiome resolveSurfaceStructureBiome(");
int helperEnd = source.indexOf("private static Holder<Biome> resolveBiomeHolder(", helperStart);
String helper = source.substring(helperStart, helperEnd);
assertTrue(helper.contains("engine.getComplex().getTrueBiomeStream().get(blockX, blockZ)"));
assertFalse(helper.contains("getDimensionStackContext()"));
assertFalse(helper.contains("getSurfaceBiome("));
assertFalse(source.contains("studioBootstrapSurfaceStructureBiomeCache"));
}
@Test
public void stackedCustomBiomesUseTheirOwningDimensionNamespace() {
IrisDimension host = new IrisDimension();
@@ -137,143 +36,11 @@ public class CustomBiomeSourceStructureContractTest {
}
@Test
public void visibleBiomeResolutionSelectsStackOwnershipBeforeHostCaves() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
int resolutionStart = source.indexOf("private BiomeResolution resolveBiomeResolution(");
int resolutionEnd = source.indexOf("private BiomeResolution createBiomeResolution(", resolutionStart);
assertTrue(resolutionStart >= 0);
assertTrue(resolutionEnd > resolutionStart);
String resolution = source.substring(resolutionStart, resolutionEnd);
assertTrue(resolution.contains("resolveDimensionStackLayer("));
assertTrue(resolution.contains("!stackLayer.terrainContext().isSelfReferencing()"));
assertTrue(resolution.indexOf("resolveDimensionStackLayer(")
< resolution.indexOf("boolean deepUnderground"));
assertTrue(resolution.contains("includeDimensionStack"));
assertTrue(source.contains("resolveBiomeResolution(x, y, z, null, false)"));
assertTrue(source.contains("resolution.dimension, customBiome.getId()"));
}
@Test
public void visibleBiomeBatchReusesTheCallersGenerationLease() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
int lookupStart = source.indexOf("public Holder<Biome> getVisibleNoiseBiome(");
int lookupEnd = source.indexOf("private GenerationSessionLease tryAcquireGenerationLease(", lookupStart);
assertTrue(lookupStart >= 0);
assertTrue(lookupEnd > lookupStart);
String lookup = source.substring(lookupStart, lookupEnd);
assertTrue(lookup.contains("requireGenerationLease(\n \"bukkit_visible_biome\""));
assertTrue(lookup.contains("prepareVisibleBiomeBatch()"));
assertTrue(lookup.contains("getVisibleNoiseBiomeWithActiveGenerationLease(x, y, z, sampler)"));
assertTrue(lookup.indexOf("prepareVisibleBiomeBatch()")
< lookup.indexOf("getVisibleNoiseBiomeWithActiveGenerationLease(x, y, z, sampler)"));
assertFalse(source.contains("studioBootstrapNoiseBiomeCache"));
}
@Test
public void stackBiomesAreVisibleButExcludedFromStructureReachability() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
assertTrue(source.contains("return possibleBiomes(true).stream()"));
assertTrue(source.contains("public Set<Holder<Biome>> possibleBiomes()"));
assertTrue(source.contains("irisBiome.getDerivativeKey()"));
assertTrue(source.contains("irisBiome.getBiomeScatter()"));
assertTrue(source.contains("irisBiome.getBiomeSkyScatter()"));
assertTrue(source.contains("return possibleBiomes(false)"));
assertTrue(source.contains("for (OwnedBiome ownedBiome : getHostOwnedBiomes(engine))"));
assertTrue(source.contains("for (OwnedBiome ownedBiome : getOwnedBiomes(engine))"));
}
@Test
public void biomeLocatorSearchesTheVisibleStack() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
int start = source.indexOf("public Pair<BlockPos, Holder<Biome>> findClosestBiome3d(");
int end = source.indexOf("static int horizontalBiomeSearchQuartStep", start);
String method = source.substring(start, end);
assertTrue(method.contains("bukkit_locate_visible_biome"));
assertTrue(method.contains("return super.findClosestBiome3d("));
assertTrue(method.contains("getVisibleBiomes("));
assertTrue(method.contains("QuartPos.toBlock(quartX), QuartPos.toBlock(quartZ)"));
assertTrue(method.contains("resolveVisibleBiomeHolder("));
assertFalse(method.contains("getStructureNoiseBiomeWithActiveGenerationLease("));
assertTrue(method.indexOf("tryAcquireGenerationLease(\"bukkit_locate_visible_biome\")")
< method.indexOf("engine.getDimensionStackContext()"));
}
@Test
public void surfaceSpawnBiomeUsesTheVisibleQuartCell() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
int start = source.indexOf("Holder<Biome> getVisibleSurfaceBiome(");
int end = source.indexOf("private RegistryAccess registry()", start);
String method = source.substring(start, end);
assertTrue(method.contains("QuartPos.fromBlock(blockX)"));
assertTrue(method.contains("QuartPos.toBlock(quartX)"));
assertTrue(method.contains("QuartPos.fromBlock(internalY + engine.getWorld().minHeight())"));
assertTrue(method.contains("stackContext.getLayout(sampleX, sampleZ).surfaceLayer()"));
assertTrue(method.contains("getVisibleNoiseBiomeWithActiveGenerationLease("));
assertTrue(method.contains("quartX, quartY, quartZ, null, null, cacheable"));
assertTrue(method.indexOf("boolean cacheable = isBiomeCacheable(engine, sampleX, sampleZ)")
< method.indexOf("Engine.hostHeight(engine, sampleX, sampleZ, true)"));
}
@Test
public void temporaryNaturalBiomeAnswersAreNotMemoized() throws IOException {
public void temporaryNaturalBiomeAnswersAreNotMemoized() {
Engine temporary = engineAnsweringNaturalFallback(true, 12, -8);
Engine stable = engineAnsweringNaturalFallback(false, 12, -8);
assertFalse(CustomBiomeSource.isBiomeCacheable(temporary, 12, -8));
assertTrue(CustomBiomeSource.isBiomeCacheable(stable, 12, -8));
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")));
int structureStart = source.indexOf(
"private Holder<Biome> getStructureNoiseBiomeWithActiveGenerationLease(");
int structureEnd = source.indexOf("@Override\n public Pair<BlockPos, Holder<Biome>> findBiomeHorizontal(",
structureStart);
assertCacheGuarded(source.substring(structureStart, structureEnd), "structureBiomeCache");
int firstVisible = source.indexOf(
"Holder<Biome> getVisibleNoiseBiomeWithActiveGenerationLease(");
int visibleStart = source.indexOf(
"Holder<Biome> getVisibleNoiseBiomeWithActiveGenerationLease(", firstVisible + 1);
int visibleEnd = source.indexOf("private boolean isBiomeCacheable(", visibleStart);
assertCacheGuarded(source.substring(visibleStart, visibleEnd), "noiseBiomeCache");
String predicate = source.substring(
visibleEnd,
source.indexOf("private GenerationSessionLease tryAcquireGenerationLease(", visibleEnd)
);
assertTrue(predicate.contains("QuartPos.toBlock(quartX)"));
assertTrue(predicate.contains("QuartPos.toBlock(quartZ)"));
assertTrue(predicate.contains("return !engine.answersFromNaturalTerrain(blockX, blockZ)"));
assertFalse(predicate.contains("getDimensionStackContext()"));
}
@Test
public void importedFeaturesCollectOnlyHostOwnedStackCells() throws IOException {
Path biomeSource = Path.of(System.getProperty("iris.customBiomeSource"));
String source = Files.readString(biomeSource.getParent().resolve("ImportedFeatureStage.java"));
assertTrue(source.contains("stackContext.getLayerAt("));
assertTrue(source.contains("layer.terrainContext().isSelfReferencing()"));
assertTrue(source.contains("section.getBiomes().get(quartX, quartY, quartZ)"));
}
private static void assertCacheGuarded(String method, String cacheName) {
int predicate = method.indexOf("boolean cacheable = isBiomeCacheable(");
int read = method.indexOf(cacheName + ".get(", predicate);
int readGuard = method.lastIndexOf("if (cacheable)", read);
int bypass = method.indexOf("if (!cacheable)", read);
int write = method.indexOf(cacheName + ".putIfAbsent(", bypass);
assertTrue(predicate >= 0);
assertTrue(read > predicate);
assertTrue(readGuard >= predicate);
assertTrue(bypass > read);
assertTrue(write > bypass);
}
private static Engine engineAnsweringNaturalFallback(
@@ -1,167 +0,0 @@
package art.arcane.iris.core.nms.v26_2_R1;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class GenerationHistoryRoutingContractTest {
@Test
public void everyChunkStageScopesItsHistoryRuntimeBeforeSessionAdmission() throws IOException {
String source = chunkGeneratorSource();
assertRoutedStage(source, "public void createStructures(", "private void adjustGeneratedStructures");
assertRoutedStage(source, "public void createReferences(", "public CompletableFuture<ChunkAccess> createBiomes");
assertRoutedStage(source, "public CompletableFuture<ChunkAccess> createBiomes", "public void buildSurface");
assertRoutedStage(source, "public void buildSurface(", "public void applyCarvers(");
assertRoutedStage(source, "public void applyCarvers(", "public CompletableFuture<ChunkAccess> fillFromNoise");
assertRoutedStage(source, "public void spawnOriginalMobs(", "private boolean allowsRoutedDiscreteGeneration(");
assertRoutedStage(
source,
"public void applyBiomeDecoration(WorldGenLevel generatoraccessseed, ChunkAccess ichunkaccess, StructureManager structuremanager, boolean vanilla)",
"public BiomeGenerationSettings getBiomeGenerationSettings");
String baseHeight = method(source, "public int getBaseHeight(", "public NoiseColumn getBaseColumn(");
String baseColumn = method(source, "public NoiseColumn getBaseColumn(", "private GenerationSessionLease requireGenerationLease");
assertBefore(baseHeight, "openHistoryCoordinateScope(", "engine.acquireGenerationLease(");
assertBefore(baseColumn, "openHistoryCoordinateScope(", "engine.acquireGenerationLease(");
}
@Test
public void asyncNoiseKeepsRouteUntilCompletionAndReopensThreadLocalScopes() throws IOException {
String source = chunkGeneratorSource();
String noise = method(
source,
"public CompletableFuture<ChunkAccess> fillFromNoise",
"private static boolean isCancellationFailure");
assertBefore(noise, "requireNoiseGenerationStage(", "openHistoryRoute(");
assertBefore(noise, "openHistoryRoute(", "requireGenerationLease(");
assertTrue(count(noise, "openHistoryRuntimeScope(route)") >= 2);
assertBefore(noise, ".thenApply(filled ->", "pipeline.whenComplete(");
assertBefore(noise, "pipeline.whenComplete(", "lease.detachThread()");
assertBefore(noise, "lease.detachThread()", "route.detachThread()");
assertBefore(noise, "route.detachThread()", "return completion;");
assertTrue(noise.contains("closeNoisePipelineResources(\n failure, lease, route, stage)"));
}
@Test
public void transitionBandSuppressesDiscreteGenerationAndCrossingStarts() throws IOException {
String source = chunkGeneratorSource();
String structures = method(source, "public void createStructures(", "private void adjustGeneratedStructures");
String adjustment = method(source, "private void adjustGeneratedStructures", "public ChunkGeneratorStructureState createState");
String decoration = method(
source,
"public void applyBiomeDecoration(WorldGenLevel generatoraccessseed, ChunkAccess ichunkaccess, StructureManager structuremanager, boolean vanilla)",
"public BiomeGenerationSettings getBiomeGenerationSettings");
assertTrue(structures.contains("allowsRoutedDiscreteGeneration(access, ChunkStatus.STRUCTURE_STARTS)"));
assertTrue(decoration.contains("allowsRoutedDiscreteGeneration(ichunkaccess, ChunkStatus.FEATURES)"));
String discrete = method(source, "private boolean allowsRoutedDiscreteGeneration(",
"private static WeightedList<MobSpawnSettings.SpawnerData> mergeSpawnTables(");
assertTrue(discrete.contains("chunk.getPersistedStatus().isOrAfter(stage)"));
assertTrue(discrete.contains("engine.getComplex().allowsNewGenerationChunk(chunkPos.x(), chunkPos.z())"));
assertBefore(decoration, "delegate.applyBiomeDecoration(", "claimGeneratedSemantics(route,");
assertTrue(adjustment.contains("start.getBoundingBox()"));
assertTrue(adjustment.contains("allowsNewGenerationFootprint("));
assertTrue(adjustment.contains("NativeStructureOwnershipStore.discard("));
}
@Test
public void biomeCachesAndVisibleHistoricalBiomesAreRuntimeAware() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.customBiomeSource")))
.replace("\r\n", "\n");
String visibleResolution = method(
source,
"private Holder<Biome> resolveVisibleBiomeHolder(",
"private Holder<Biome> resolveCustomHolder(");
String activeBatch = method(
source,
"Holder<Biome> getVisibleNoiseBiomeWithActiveGenerationLease(\n int x,",
"private GenerationSessionLease tryAcquireGenerationLease");
assertTrue(source.contains("record RuntimeNoiseKey(int runtimeId, long coordinateKey)"));
assertTrue(source.contains("record RuntimeColumnKey(int runtimeId, long coordinateKey)"));
assertTrue(source.contains("ConcurrentHashMap<Integer, RuntimeBiomeState> runtimeBiomeStates"));
assertTrue(source.contains("addGenerationRuntimeRetirementListener(this::evictRuntimeCaches)"));
assertTrue(source.contains("runtimeBiomeStates.remove(runtimeId)"));
assertTrue(source.contains("noiseBiomeCache.keySet().removeIf(key -> key.runtimeId() == runtimeId)"));
assertBefore(visibleResolution, "historicalPhysicalBiomeKeyAt(", "resolveBiomeResolution(");
assertFalse(activeBatch.contains("openHistoryCoordinateScope("));
String chunkGenerator = chunkGeneratorSource();
assertTrue(chunkGenerator.contains("addGenerationRuntimeRetirementListener(this::evictRuntimeCaches)"));
assertTrue(chunkGenerator.contains("mergedSpawnTables.keySet().removeIf(key -> key.runtimeId() == runtimeId)"));
}
@Test
public void importedFeatureTablesAreRuntimeScopedAndRetiredCentrally() throws IOException {
String stage = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))
.resolveSibling("ImportedFeatureStage.java"))
.replace("\r\n", "\n");
String generator = chunkGeneratorSource();
assertTrue(stage.contains("ConcurrentHashMap<Integer, RuntimeFeatureState> runtimeStates"));
assertTrue(stage.contains("runtimeStates.get(engine.getCacheID())"));
assertTrue(stage.contains("runtimeStates.remove(runtimeId)"));
assertFalse(stage.contains("volatile FeatureTable featureTable"));
assertFalse(stage.contains("volatile int settledRuntimeId"));
assertTrue(generator.contains("importedFeatures.evictRuntime(runtimeId)"));
}
@Test
public void nativeReferencesResolvePolicyInTheOriginRuntime() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nativeStructureVolumeIndexSource"))
.resolveSibling("NativeStructureReferenceRepair.java"))
.replace("\r\n", "\n");
String references = method(source, "public static void createReferences(",
"private static GenerationHistoryRuntimeRouter.CoordinateScope openOriginRuntimeScope(");
assertBefore(references, "openOriginRuntimeScope(engine, originChunkX, originChunkZ)", "scanStart(");
assertBefore(references, "scanStart(", "isTargetRelevant(");
assertTrue(source.contains("irisEngine.openGenerationHistoryCoordinateScope(chunkX << 4, chunkZ << 4)"));
assertFalse(references.contains("allowsNewGenerationFootprint("));
}
private static void assertRoutedStage(String source, String start, String end) {
String stage = method(source, start, end);
assertBefore(stage, "requireGenerationStage(", "openHistoryRoute(");
assertBefore(stage, "openHistoryRoute(", "requireGenerationLease(");
assertBefore(stage, "openHistoryRuntimeScope(route)", "requireGenerationLease(");
}
private static String chunkGeneratorSource() throws IOException {
return Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource")))
.replace("\r\n", "\n");
}
private static String method(String source, String startToken, String endToken) {
int start = source.indexOf(startToken);
int end = source.indexOf(endToken, start);
assertTrue("Missing source contract token: " + startToken, start >= 0);
assertTrue("Missing source contract token: " + endToken, end > start);
return source.substring(start, end);
}
private static void assertBefore(String source, String first, String second) {
int firstIndex = source.indexOf(first);
int secondIndex = source.indexOf(second);
assertTrue("Missing source contract token: " + first, firstIndex >= 0);
assertTrue("Missing source contract token: " + second, secondIndex >= 0);
assertTrue(first + " must occur before " + second, firstIndex < secondIndex);
}
private static int count(String source, String token) {
int count = 0;
int index = 0;
while ((index = source.indexOf(token, index)) >= 0) {
count++;
index += token.length();
}
return count;
}
}
@@ -2,9 +2,6 @@ package art.arcane.iris.core.nms.v26_2_R1;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
@@ -23,356 +20,6 @@ import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class IrisChunkGeneratorFailureContractTest {
@Test
public void structureLocateDoesNotCatchAndFallThroughToAnotherImplementation() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int locateStart = source.indexOf("public @Nullable Pair<BlockPos, Holder<Structure>> findNearestMapStructure");
int locateEnd = source.indexOf("private HolderSet<Structure> filterReachableStructures", locateStart);
String locate = source.substring(locateStart, locateEnd);
int reachabilityStart = source.indexOf("private Set<String> reachableStructureKeys");
int reachabilityEnd = source.indexOf("protected MapCodec", reachabilityStart);
String reachability = source.substring(reachabilityStart, reachabilityEnd);
int bootstrapGate = locate.indexOf("!platformGenerator.shouldGenerateStructures()");
int generatorIdentity = locate.indexOf("level.getChunkSource().getGenerator() != this");
int lease = locate.indexOf("requireGenerationLease(\"bukkit_nms_structure_locate\")");
int nativePrediction = locate.indexOf("NativeStructureVanillaLocator.predict(");
assertTrue(locate.contains("reached its safety limit"));
assertTrue(locate.contains("unregistered structure holder"));
assertTrue(bootstrapGate >= 0);
assertTrue(generatorIdentity > bootstrapGate);
assertTrue(lease > generatorIdentity);
assertTrue(nativePrediction > lease);
assertFalse(locate.contains("catch (Throwable"));
assertFalse(locate.contains("IrisLogging.reportError"));
assertFalse(reachability.contains("catch (Throwable"));
assertFalse(reachability.contains("reachable = Set.of()"));
}
@Test
public void structureGenerationAbortsInsteadOfLoggingAndContinuing() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int adjustmentStart = source.indexOf("private void adjustGeneratedStructures");
int adjustmentEnd = source.indexOf("public ChunkGeneratorStructureState createState", adjustmentStart);
String adjustment = source.substring(adjustmentStart, adjustmentEnd);
int placementStart = source.indexOf("private void placeVanillaStructures");
int placementEnd = source.indexOf("private void placeVanillaStructure(", placementStart + 1);
String placement = source.substring(placementStart, placementEnd);
assertTrue(adjustment.contains("NativeStructureGenerationException.failure("));
assertTrue(adjustment.contains("\"vertical adjustment\""));
assertFalse(adjustment.contains("IrisLogging.reportError"));
assertTrue(placement.contains("\"resolution\""));
assertTrue(placement.contains("\"terrain integration\""));
assertTrue(placement.contains("\"terrain preparation\""));
assertTrue(placement.contains("\"foundation repair\""));
assertFalse(placement.contains("\"terrain carving\""));
assertTrue(placement.contains("\"vegetation cleanup\""));
assertTrue(placement.contains("\"placement\""));
assertTrue(placement.contains("because structure generation is disabled outside the pack"));
assertTrue(placement.contains("prepareSurfaceStructures"));
assertTrue(placement.contains("clearIntersectingVegetation"));
assertTrue(placement.indexOf("clearIntersectingVegetation")
< placement.indexOf("prepareSurfaceStructures"));
assertTrue(placement.indexOf("prepareSurfaceStructures")
< placement.indexOf("for (NativePlacementGroup group"));
assertTrue(placement.indexOf("repairVacuumFoundations")
> placement.indexOf("for (NativePlacementGroup group"));
assertTrue(placement.contains("nativeStructureProtection(staticObjects)"));
assertTrue(placement.contains("Engine.hostHeight(engine, x, z, true)"));
assertFalse(placement.contains("IrisLogging.reportError"));
}
@Test
public void heightmapRuntimeReadsAreGenerationLeased() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
assertTrue(source.contains("engine.acquireGenerationLease(\"bukkit_nms_heightmaps\")"));
assertTrue(source.contains("engine.acquireGenerationLease(\"bukkit_nms_base_height\")"));
assertTrue(source.contains("engine.acquireGenerationLease(\"bukkit_nms_base_column\")"));
assertTrue(source.contains("catch (GenerationSessionException e)"));
}
@Test
public void structureReferenceRepairIsGenerationLeased() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int referencesStart = source.indexOf("public void createReferences");
int referencesEnd = source.indexOf("public CompletableFuture<ChunkAccess> createBiomes", referencesStart);
String references = source.substring(referencesStart, referencesEnd);
int nativeStructureGate = references.indexOf("!platformGenerator.shouldGenerateStructures()");
int generatorIdentity = references.indexOf("runtimeLevel.getChunkSource().getGenerator() != this");
int stage = references.indexOf("requireGenerationStage(\"bukkit_nms_create_references\")");
int lease = references.indexOf("requireGenerationLease(\"bukkit_nms_create_references\")");
int repair = references.indexOf("NativeStructureReferenceRepair.createReferences(");
assertTrue(nativeStructureGate >= 0);
assertTrue(generatorIdentity > nativeStructureGate);
assertTrue(stage > generatorIdentity);
assertTrue(lease > stage);
assertTrue(repair > lease);
assertTrue(references.contains("IrisContext.open(engine, lease.sessionId(), null)"));
assertFalse(references.contains("delegate.createReferences("));
assertFalse(references.contains("catch ("));
}
@Test
public void structureGenerationAcquiresBootstrapGateBeforeUsingPublishedState() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int generationStart = source.indexOf("public void createStructures(");
int generationEnd = source.indexOf("private void adjustGeneratedStructures", generationStart);
String generation = source.substring(generationStart, generationEnd);
int gate = generation.indexOf("!platformGenerator.shouldGenerateStructures()");
int currentGenerator = generation.indexOf(
"runtimeLevel.getChunkSource().getGenerator() != this");
int stateIdentity = generation.indexOf(
"runtimeLevel.getChunkSource().getGeneratorState() != structureState");
int stage = generation.indexOf(
"requireGenerationStage(\"bukkit_nms_create_structures\")");
int lease = generation.indexOf(
"requireGenerationLease(\"bukkit_nms_create_structures\")");
int generationCall = generation.indexOf(
"super.createStructures(registryAccess, structureState");
assertTrue(gate >= 0);
assertTrue(currentGenerator > gate);
assertTrue(stateIdentity > currentGenerator);
assertTrue(stage > stateIdentity);
assertTrue(lease > stage);
assertTrue(generationCall > lease);
assertTrue(generation.contains("structureState,\n structureManager"));
assertFalse(generation.contains("resolvePublishedStructureState"));
}
@Test
public void nativeRingBootstrapTracksTheExactMinecraftFutures() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int initializeStart = source.indexOf("private CompletableFuture<Void> initializeStructureState(");
int initializeEnd = source.indexOf("private Map<?, ?> structureRingPositions", initializeStart);
String initialize = source.substring(initializeStart, initializeEnd);
int completionStart = source.indexOf(
"private CompletableFuture<Void> structureRingCompletion", initializeEnd);
int completionEnd = source.indexOf("private void requireCurrentStructureOwner", completionStart);
String completion = source.substring(completionStart, completionEnd);
assertBefore(initialize,
"structureRingPositions(structureState)",
"structureState.ensureStructuresGenerated()");
assertBefore(initialize,
"structureState.ensureStructuresGenerated()",
"structureRingCompletion(ringPositions)");
assertFalse(initialize.contains("catch ("));
assertTrue(completion.contains("for (Object candidate : ringPositions.values())"));
assertTrue(completion.contains("CompletableFuture.allOf(completions)"));
assertTrue(completion.contains("throw new IllegalStateException("));
assertFalse(completion.contains("join()"));
assertFalse(completion.contains("get()"));
}
@Test
public void standardActivationClaimsTheExactPublishedStateBeforeInitialization() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int activationStart = source.indexOf("CompletableFuture<Void> activateStudioStructureState(");
int activationEnd = source.indexOf(
"private CompletableFuture<Void> startStructureStateBootstrap", activationStart);
String activation = source.substring(activationStart, activationEnd);
int bootstrapStart = activationEnd;
int bootstrapEnd = source.indexOf(
"private CompletableFuture<Void> initializeStructureState", bootstrapStart);
String bootstrap = source.substring(bootstrapStart, bootstrapEnd);
assertTrue(activation.contains("retained.structureState()"));
assertBefore(activation,
"retainedStudioStructureState(",
"claimStudioStructureState(retained)");
assertBefore(bootstrap,
"claim,",
"initializeStructureState(");
assertBefore(bootstrap,
"initializeStructureState(",
"activation.run()");
assertFalse(activation.contains("publishStructureState("));
assertFalse(source.contains("ChunkGeneratorStructureState fullState"));
}
@Test
public void terrainWritesPrimeTheWorldgenHeightmapsForEveryChunk() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int fillStart = source.indexOf("public CompletableFuture<ChunkAccess> fillFromNoise");
int fillEnd = source.indexOf("public WeightedList<MobSpawnSettings.SpawnerData> getMobsAt", fillStart);
String fill = source.substring(fillStart, fillEnd);
int decorationStart = source.indexOf("public void addVanillaDecorations");
int decorationEnd = source.indexOf("public void spawnOriginalMobs", decorationStart);
String decorations = source.substring(decorationStart, decorationEnd);
int placementStart = source.indexOf("private void placeVanillaStructures");
int placementEnd = source.indexOf("private static String nativeStructureBatchContext", placementStart);
String placement = source.substring(placementStart, placementEnd);
assertTrue(fill.contains("thenApply"));
assertTrue(fill.contains("primeWorldgenHeightmaps"));
assertTrue(decorations.contains("primeWorldgenHeightmaps"));
assertFalse(decorations.contains("Heightmap.Types.WORLD_SURFACE_WG"));
assertFalse(decorations.contains("Heightmap.Types.OCEAN_FLOOR_WG"));
assertEquals(1, occurrences(source, "WorldgenTerrainHeightmaps.primeTerrain("));
assertTrue(placement.contains("WorldgenTerrainHeightmaps.primeStructurePlacement("));
assertTrue(placement.indexOf("WorldgenTerrainHeightmaps.primeStructurePlacement(")
< placement.indexOf("prepareSurfaceStructures"));
assertTrue(fill.contains("requireGenerationLease(\"bukkit_nms_chunk_pipeline\")"));
assertTrue(source.contains("int minY = chunk.getMinY() + 1;"));
}
@Test
public void authoringHeightmapStagesReturnBeforeAnyTerrainHeightResolver() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource")));
int primeStart = source.indexOf("private void primeWorldgenHeightmaps(");
int primeEnd = source.indexOf("private IntBinaryOperator worldgenSurfaceHeight()", primeStart);
String prime = source.substring(primeStart, primeEnd);
assertBefore(prime, "platformGenerator.usesFlatStudioTerrain()", "worldgenSurfaceHeight()");
assertBefore(prime, "primeAuthoringHeightmaps(chunkAccess);", "return;");
assertBefore(prime, "return;", "WorldgenTerrainHeightmaps.primeTerrain(");
int decorationStart = source.indexOf("public void addVanillaDecorations(");
int decorationEnd = source.indexOf("public void spawnOriginalMobs(", decorationStart);
String decorations = source.substring(decorationStart, decorationEnd);
assertBefore(decorations, "primeWorldgenHeightmaps(chunkAccess);", "platformGenerator.usesFlatStudioTerrain()");
assertBefore(decorations, "platformGenerator.usesFlatStudioTerrain()", "return;");
assertBefore(decorations, "return;", "engine.getHeight(");
}
@Test
public void authoringDecorationSkipsNativeFeaturesButRetainsHeightmapsAndBukkitPopulators() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource")));
String decoration = method(source,
"public void applyBiomeDecoration(WorldGenLevel generatoraccessseed, ChunkAccess ichunkaccess, StructureManager structuremanager, boolean vanilla)",
"public BiomeGenerationSettings getBiomeGenerationSettings");
int structuresGuard = decoration.indexOf("if (!flatStudioTerrain && !ichunkaccess.getPersistedStatus().isOrAfter(ChunkStatus.FEATURES))");
assertTrue(structuresGuard >= 0);
int structuresEnd = decoration.indexOf("\n }", structuresGuard);
String structures = decoration.substring(structuresGuard, structuresEnd);
assertTrue(structures.contains("placeVanillaStructures(generatoraccessseed, ichunkaccess, structuremanager);"));
int preparationGuard = decoration.indexOf("if (!flatStudioTerrain)");
assertTrue(structuresEnd < preparationGuard);
assertTrue(decoration.indexOf("NativeGenerationWriteGuard.allowsDecoration") > structuresEnd);
int preparationEnd = decoration.indexOf("\n }", preparationGuard);
String preparation = decoration.substring(preparationGuard, preparationEnd);
assertTrue(preparation.contains("importedFeatures.prepare(generatoraccessseed);"));
int placementGuard = decoration.indexOf("if (!flatStudioTerrain)", preparationEnd);
int placementEnd = decoration.indexOf("\n }", placementGuard);
String placement = decoration.substring(placementGuard, placementEnd);
assertTrue(placement.contains("importedFeatures.run(generatoraccessseed, ichunkaccess, this);"));
int heightmaps = decoration.indexOf("addVanillaDecorations(generatoraccessseed, ichunkaccess, structuremanager);");
int populators = decoration.indexOf("delegate.applyBiomeDecoration(generatoraccessseed, ichunkaccess, structuremanager, false);");
assertTrue(heightmaps > preparationEnd && heightmaps < placementGuard);
assertTrue(populators > placementEnd);
assertTrue(decoration.indexOf("claimGeneratedSemantics(route,") > populators);
assertTrue(decoration.contains("requireGenerationStage(\"bukkit_nms_biome_decoration\")"));
assertTrue(decoration.contains("requireGenerationLease(\"bukkit_nms_biome_decoration\")"));
}
@Test
public void everyChunkUsesTheProductionGenerationStages() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource")))
.replace("\r\n", "\n");
String createBiomes = method(
source,
"public CompletableFuture<ChunkAccess> createBiomes",
"public void buildSurface");
String buildSurface = method(
source,
"public void buildSurface",
"public void applyCarvers");
String carvers = method(
source,
"public void applyCarvers",
"public CompletableFuture<ChunkAccess> fillFromNoise");
String noise = method(
source,
"public CompletableFuture<ChunkAccess> fillFromNoise",
"private static boolean isCancellationFailure");
String decoration = method(
source,
"public void applyBiomeDecoration(WorldGenLevel generatoraccessseed, ChunkAccess ichunkaccess, StructureManager structuremanager, boolean vanilla)",
"public BiomeGenerationSettings getBiomeGenerationSettings");
String spawning = method(
source,
"public void spawnOriginalMobs",
"private static WeightedList<MobSpawnSettings.SpawnerData> mergeSpawnTables");
String baseHeight = method(
source,
"public int getBaseHeight",
"public NoiseColumn getBaseColumn");
String baseColumn = method(
source,
"public NoiseColumn getBaseColumn",
"private GenerationSessionLease requireGenerationLease");
assertTrue(createBiomes.contains("requireGenerationStage(\"bukkit_nms_create_biomes\")"));
assertTrue(createBiomes.contains("customBiomeSource.prepareVisibleBiomeBatch()"));
assertTrue(createBiomes.contains("new IrisDimensionCarvingResolver.State()"));
assertTrue(createBiomes.contains("sampler, resolverState"));
assertTrue(buildSurface.contains("delegate.buildSurface("));
assertTrue(carvers.contains("delegate.applyCarvers("));
assertTrue(noise.contains("requireNoiseGenerationStage("));
assertTrue(noise.contains("\"bukkit_nms_chunk_pipeline\""));
assertTrue(noise.contains("stage.close()"));
assertTrue(noise.contains("completion.cancel(false)"));
assertTrue(decoration.contains("requireGenerationStage(\"bukkit_nms_biome_decoration\")"));
assertTrue(spawning.contains("NaturalSpawner.spawnMobsForChunkGeneration("));
assertTrue(baseHeight.contains("engine.getHeight("));
assertTrue(baseColumn.contains("engine.getHeight("));
assertFalse(source.contains("synthetic_entry"));
assertFalse(source.contains("StudioEntryChunkGenerator"));
}
@Test
public void fillFromNoiseLeaseSpansTheDelegateAndHeightmapPipeline() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int fillStart = source.indexOf("public CompletableFuture<ChunkAccess> fillFromNoise");
int fillEnd = source.indexOf("private static boolean isCancellationFailure", fillStart);
String fill = source.substring(fillStart, fillEnd);
int productionStart = fill.indexOf(
" BukkitChunkGenerator.GenerationStagePermit stage = requireNoiseGenerationStage(",
0);
assertTrue(productionStart >= 0);
String productionFill = fill.substring(productionStart);
int completionStart = productionFill.indexOf("pipeline.whenComplete(");
int completionEnd = productionFill.indexOf(" return completion;", completionStart);
assertTrue(completionStart >= 0);
assertTrue(completionEnd > completionStart);
String completion = productionFill.substring(completionStart, completionEnd);
assertBefore(productionFill,
"BukkitChunkGenerator.GenerationStagePermit stage = requireNoiseGenerationStage(",
"GenerationHistoryRuntimeRouter.RuntimeRoute route");
assertBefore(productionFill,
"GenerationHistoryRuntimeRouter.RuntimeRoute route",
"GenerationSessionLease lease");
assertBefore(productionFill,
"requireNoiseGenerationStage(",
"\"bukkit_nms_chunk_pipeline\")");
assertBefore(productionFill,
"lease = requireGenerationLease(\"bukkit_nms_chunk_pipeline\")",
"delegate.fillFromNoise(");
assertTrue(productionFill.contains("IrisContext.open(engine, lease.sessionId(), null)"));
assertTrue(productionFill.contains("openHistoryRuntimeScope(route)"));
assertBefore(productionFill, "primeWorldgenHeightmaps(filled)", "pipeline.whenComplete(");
assertTrue(productionFill.contains("CompletableFuture<ChunkAccess> completion = new CompletableFuture<>()"));
assertBefore(completion, "boolean cancelled = isCancellationFailure(failure);", "closeNoisePipelineResources(");
assertBefore(completion, "closeNoisePipelineResources(", "completion.complete(filled)");
assertBefore(completion, "closeNoisePipelineResources(", "completion.cancel(false)");
assertBefore(completion, "closeNoisePipelineResources(", "completion.completeExceptionally(completionFailure)");
assertTrue(completion.contains("else if (cancelled)"));
assertFalse(completion.contains("pipeline.isCancelled()"));
assertFalse(completion.contains("finally"));
assertTrue(productionFill.contains("catch (RuntimeException | Error failure)"));
assertTrue(productionFill.contains("lease.close();\n closeHistoryRoute(route, failure);\n stage.close();\n throw failure;"));
assertTrue(productionFill.contains("return completion;"));
assertFalse(productionFill.contains("return pipeline;"));
assertFalse(productionFill.contains("pipeline.cancel("));
assertFalse(productionFill.contains("bukkit_nms_worldgen_heightmaps"));
}
@Test
public void releasedNoiseAdmissionLetsSynchronousDependentWaitForQueuedExclusive() throws Exception {
Semaphore admission = new Semaphore(1, true);
@@ -429,7 +76,7 @@ public class IrisChunkGeneratorFailureContractTest {
}
@Test
public void transformedDelegateCancellationIsDetectedThroughItsCompletionFailure() throws IOException {
public void transformedDelegateCancellationIsDetectedThroughItsCompletionFailure() {
CompletableFuture<Void> delegate = new CompletableFuture<>();
CompletableFuture<Void> transformed = delegate.thenApply(value -> value);
@@ -437,130 +84,6 @@ public class IrisChunkGeneratorFailureContractTest {
assertFalse(transformed.isCancelled());
CompletionException failure = assertThrows(CompletionException.class, transformed::join);
assertTrue(failure.getCause() instanceof CancellationException);
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
String cancellation = method(
source,
"private static boolean isCancellationFailure",
"private void primeWorldgenHeightmaps");
assertTrue(cancellation.contains("current instanceof CompletionException"));
assertTrue(cancellation.contains("current instanceof CancellationException"));
}
@Test
public void noiseAdmissionCanPrepareStudioBeforeAcquiringTheGenerationLease() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
String fill = method(
source,
"public CompletableFuture<ChunkAccess> fillFromNoise",
"private static boolean isCancellationFailure");
String admission = method(
source,
"private BukkitChunkGenerator.GenerationStagePermit requireNoiseGenerationStage",
"public Optional<Identifier> getTypeNameForDataFixer");
assertBefore(fill,
"requireNoiseGenerationStage(",
"requireGenerationLease(\"bukkit_nms_chunk_pipeline\")");
assertTrue(admission.contains("platformGenerator.acquireNoiseGenerationStage("));
assertBefore(admission, "engine,", "chunkPos.x(),");
assertBefore(admission, "chunkPos.x(),", "chunkPos.z(),");
assertFalse(fill.contains("requireGenerationStage(\"bukkit_nms_chunk_pipeline\")"));
}
@Test
public void everyTopLevelMoonriseStageEntersTheFairGateBeforeItsGenerationLease() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
String structures = method(source, "public void createStructures(", "private void adjustGeneratedStructures");
String references = method(source, "public void createReferences(", "public CompletableFuture<ChunkAccess> createBiomes");
String biomes = method(source, "public CompletableFuture<ChunkAccess> createBiomes", "public void buildSurface");
String surface = method(source, "public void buildSurface(", "public void applyCarvers(");
String carvers = method(source, "public void applyCarvers(", "public CompletableFuture<ChunkAccess> fillFromNoise");
String mobs = method(source, "public void spawnOriginalMobs(", "private boolean allowsRoutedDiscreteGeneration(");
String noise = method(source, "public CompletableFuture<ChunkAccess> fillFromNoise", "private static boolean isCancellationFailure");
String decoration = method(source,
"public void applyBiomeDecoration(WorldGenLevel generatoraccessseed, ChunkAccess ichunkaccess, StructureManager structuremanager, boolean vanilla)",
"public BiomeGenerationSettings getBiomeGenerationSettings");
assertStageBeforeLease(structures, "bukkit_nms_create_structures");
assertStageBeforeLease(references, "bukkit_nms_create_references");
assertStageBeforeLease(biomes, "bukkit_nms_create_biomes");
assertStageBeforeLease(surface, "bukkit_nms_build_surface");
assertStageBeforeLease(carvers, "bukkit_nms_apply_carvers");
assertStageBeforeLease(mobs, "bukkit_nms_spawn_original_mobs");
assertBefore(noise,
"requireNoiseGenerationStage(",
"requireGenerationLease(\"bukkit_nms_chunk_pipeline\")");
assertStageBeforeLease(decoration, "bukkit_nms_biome_decoration");
assertBefore(decoration,
"requireGenerationLease(\"bukkit_nms_biome_decoration\")",
"importedFeatures.prepare(generatoraccessseed)");
assertEquals(7, occurrences(source, "requireGenerationStage(\"bukkit_nms_"));
assertEquals(2, occurrences(source, "requireNoiseGenerationStage("));
assertFalse(source.contains("GenerationSessionManager"));
}
@Test
public void worldgenHeightmapPrimingLivesInTheSharedNativegenSources() throws IOException {
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
Path shared = nativegen.resolve("WorldgenTerrainHeightmaps.java");
assertTrue("Worldgen heightmap priming must be shared with the modded loaders through "
+ nativegen, Files.isRegularFile(shared));
String heightmaps = Files.readString(shared).replace("\r\n", "\n");
assertTrue(heightmaps.contains("package art.arcane.iris.nativegen;"));
assertTrue(heightmaps.contains("public static void primeTerrain("));
assertTrue(heightmaps.contains("public static void primeStructurePlacement("));
assertFalse(heightmaps.contains("org.bukkit"));
assertFalse(heightmaps.contains("craftbukkit"));
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
assertTrue(source.contains("import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps;"));
}
@Test
public void onlySidecarOwnedInjectedStartsUsePersistedPlacementPolicy() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int placementStart = source.indexOf("private void placeVanillaStructures");
int placementEnd = source.indexOf("private static String nativeStructureBatchContext", placementStart);
String placement = source.substring(placementStart, placementEnd);
int ownershipResolution = placement.indexOf(
"NativeStructureOwnershipRecovery.resolve(");
int persistedDecision = placement.indexOf("ownership.restoredDecision()", ownershipResolution);
int adjustmentStart = source.indexOf("private void adjustGeneratedStructures");
int adjustmentEnd = source.indexOf("public ChunkGeneratorStructureState createState", adjustmentStart);
String adjustment = source.substring(adjustmentStart, adjustmentEnd);
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
String factory = Files.readString(nativegen.resolve("NativeStructureFactory.java")).replace("\r\n", "\n");
String injector = Files.readString(nativegen.resolve("NativeStructureStartInjector.java")).replace("\r\n", "\n");
String recovery = Files.readString(nativegen.resolve("NativeStructureOwnershipRecovery.java")).replace("\r\n", "\n");
int ownershipRecord = injector.indexOf("NativeStructureOwnershipStore.record(");
int startPublication = injector.indexOf(
"context.structureManager().setStartForStructure(", ownershipRecord);
assertTrue(ownershipResolution >= 0);
assertTrue(persistedDecision > ownershipResolution);
assertTrue(recovery.contains("NativeStructureOwnershipStore.findPersisted("));
assertTrue(recovery.contains("NativeStructureOwnershipStore.record("));
assertTrue(ownershipRecord >= 0);
assertTrue(startPublication > ownershipRecord);
assertTrue(factory.contains("NativeStructureReferenceEnvelope.wrapForPublication("));
assertTrue(adjustment.contains("NativeStructureReferenceEnvelope.wrapForPublication("));
assertFalse(source.contains("wrapManaged("));
assertFalse(source.contains("isIrisManagedStart("));
}
private static int occurrences(String source, String needle) {
int count = 0;
int index = source.indexOf(needle);
while (index >= 0) {
count++;
index = source.indexOf(needle, index + needle.length());
}
return count;
}
private static void awaitQueueLength(Semaphore semaphore, int expected) {
@@ -571,41 +94,4 @@ public class IrisChunkGeneratorFailureContractTest {
assertTrue("Expected at least " + expected + " queued semaphore threads",
semaphore.getQueueLength() >= expected);
}
private static String method(String source, String startToken, String endToken) {
int start = source.indexOf(startToken);
int end = source.indexOf(endToken, start);
assertTrue("Missing source contract token: " + startToken, start >= 0);
assertTrue("Missing source contract token: " + endToken, end > start);
return source.substring(start, end);
}
private static void assertStageBeforeLease(String source, String operation) {
assertBefore(source,
"requireGenerationStage(\"" + operation + "\")",
"requireGenerationLease(\"" + operation + "\")");
}
private static void assertBefore(String source, String first, String second) {
int firstIndex = source.indexOf(first);
int secondIndex = source.indexOf(second);
assertTrue("Missing source contract token: " + first, firstIndex >= 0);
assertTrue("Missing source contract token: " + second, secondIndex >= 0);
assertTrue(first + " must occur before " + second, firstIndex < secondIndex);
}
@Test
public void vanillaChunkGenerationMobsUseTheVisibleBiomesVanillaDerivative() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int spawnStart = source.indexOf("public void spawnOriginalMobs");
int spawnEnd = source.indexOf("private static WeightedList", spawnStart);
String spawn = source.substring(spawnStart, spawnEnd);
assertTrue(spawn.contains("customBiomeSource.getVanillaSpawnBiome(visibleBiome)"));
assertTrue(spawn.contains("customBiomeSource.getVisibleSurfaceBiome("));
assertTrue(spawn.contains("NaturalSpawner.spawnMobsForChunkGeneration("));
assertTrue(spawn.contains("new LegacyRandomSource(RandomSupport.generateUniqueSeed())"));
assertTrue(spawn.contains("random.setDecorationSeed(region.getSeed()"));
assertFalse(spawn.contains("delegate.spawnOriginalMobs"));
}
}
@@ -7,73 +7,12 @@ import net.minecraft.core.Holder;
import net.minecraft.world.level.levelgen.structure.Structure;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
public class IrisChunkGeneratorMonumentLocateContractTest {
@Test
public void nativeLocateAllowsMonumentsAfterPolicyAndReachabilityChecks() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int findStart = source.indexOf("findNearestMapStructure(ServerLevel level");
assertTrue(findStart >= 0);
int irisHelperStart = source.indexOf("private Pair<BlockPos, Holder<Structure>> findNearestIrisStructure(", findStart);
int filterStart = source.indexOf("private HolderSet<Structure> filterReachableStructures", irisHelperStart);
assertTrue(irisHelperStart > findStart);
assertTrue(filterStart > irisHelperStart);
String outerMethod = source.substring(findStart, irisHelperStart);
String irisHelper = source.substring(irisHelperStart, filterStart);
int registryLookup = irisHelper.indexOf("level.registryAccess().lookupOrThrow(Registries.STRUCTURE)");
int placedCheck = irisHelper.indexOf(
"if (!IrisStructureLocator.hasNativePlacement(engine, structureId))");
int irisLocate = irisHelper.indexOf("NativeStructureLocatePersistence.search(", placedCheck);
int searchLimit = irisHelper.indexOf("LocateStatus.SEARCH_LIMIT_REACHED", irisLocate);
int nativeFilter = outerMethod.indexOf("filterReachableStructures(level, holders)");
int nativePrediction = outerMethod.indexOf("NativeStructureVanillaLocator.predict(", nativeFilter);
int irisResolution = outerMethod.indexOf("return findNearestIrisStructure(", nativePrediction);
int nearestSelection = irisHelper.indexOf(
"NativeStructureLocateResults.nearest(pos, predicted, nativeLocated)");
int selectedVerification = irisHelper.indexOf("bestSearch.search().verify(bestResult)", nearestSelection);
int selectedReference = irisHelper.indexOf(
"selectedSearch.search().reference(selectedStart)", selectedVerification);
int reachabilityStart = source.indexOf("private Set<String> reachableStructureKeys", filterStart);
assertTrue(reachabilityStart > filterStart);
String filterMethod = source.substring(filterStart, reachabilityStart);
int policyFilter = filterMethod.indexOf("if (!decision.generate())");
int filterContinue = filterMethod.indexOf("continue;", policyFilter);
int emptyNativePartition = filterMethod.indexOf("if (candidates.isEmpty())", filterContinue);
int reachabilityLookup = filterMethod.indexOf("reachableStructureKeys(level)", emptyNativePartition);
assertTrue(registryLookup >= 0);
assertTrue(placedCheck > registryLookup);
assertTrue(irisLocate > placedCheck);
assertTrue(searchLimit > irisLocate);
assertTrue(nativeFilter >= 0);
assertTrue(nativePrediction > nativeFilter);
assertTrue(irisResolution > nativePrediction);
assertTrue(nearestSelection > irisLocate);
assertTrue(selectedVerification > nearestSelection);
assertTrue(selectedReference > selectedVerification);
assertTrue(policyFilter >= 0);
assertTrue(filterContinue > policyFilter);
assertTrue(emptyNativePartition > filterContinue);
assertTrue(reachabilityLookup > emptyNativePartition);
assertFalse(filterMethod.contains("NativeStructureLocateCapability"));
assertFalse(irisHelper.contains("NativeStructureLocateCapability.isPaperUnavailable(structureId)"));
assertTrue(irisHelper.contains("NativeStructureLocatePersistence.probe("));
assertTrue(irisHelper.contains("NativeStructureLocateResults.selectAndReference("));
assertTrue(irisHelper.contains("selectedSearch.search().reference(selectedStart)"));
assertTrue(irisHelper.contains("findUnexplored"));
assertTrue(irisHelper.contains("verified.ownership().locatorY()"));
assertFalse(outerMethod.contains("delegate.findNearestMapStructure("));
}
@Test
public void mixedLocateSelectsNearestProviderAndPrefersNativeOnTie() {
BlockPos origin = BlockPos.ZERO;
@@ -116,75 +55,4 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
assertEquals(1, irisReferences.get());
assertEquals(1, nativeReferences.get());
}
@Test
public void nativePredictionIsReadOnlyUntilTheWinnerIsCommitted() throws IOException {
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
String source = Files.readString(nativegen.resolve("NativeStructureVanillaLocator.java")).replace("\r\n", "\n");
int predictionStart = source.indexOf("private static Candidate predictAt(");
int candidateStart = source.indexOf("public static final class Candidate", predictionStart);
String prediction = source.substring(predictionStart, candidateStart);
String candidate = source.substring(candidateStart);
assertFalse(prediction.contains("addReference("));
assertTrue(candidate.contains("structureManager.addReference(referenceStart)"));
assertTrue(candidate.contains("committed.compareAndSet(false, true)"));
}
@Test
public void stiltSupportUsesPlacedSolidOccupancyWithoutSnapshotDifferenceRequirement() throws IOException {
Path processor = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource"));
String source = Files.readString(processor).replace("\r\n", "\n");
String foundation = Files.readString(
processor.resolveSibling("NativeStructureFoundationBuilder.java")).replace("\r\n", "\n");
int placement = source.indexOf("start.placeInChunk(world, structureManager, generator");
int stiltPlacement = source.indexOf("placeStilts(world, area, structureId, start", placement);
int stiltDefinition = foundation.indexOf("static void placeStilts(");
int occupancyCheck = foundation.indexOf("if (state.isSolid())", stiltDefinition);
int terrainFloor = foundation.indexOf("Math.max(terrainY,", stiltDefinition);
assertTrue(placement >= 0);
assertTrue(stiltPlacement > placement);
assertTrue(stiltDefinition >= 0);
assertTrue(occupancyCheck > stiltDefinition);
assertTrue(terrainFloor > stiltDefinition);
assertFalse(source.contains("state.equals("));
assertFalse(foundation.contains("state.equals("));
assertFalse(source.contains("snapshot.states"));
assertFalse(foundation.contains("snapshot.states"));
}
@Test
public void verticalPlacementMovesPiecesMonumentChildrenJigsawJunctionsAndCachedBoundsTogether() throws IOException {
String source = Files.readString(
Path.of(System.getProperty("iris.nativeStructurePostProcessorSource"))
.resolveSibling("NativeStructureVerticalPlacer.java")).replace("\r\n", "\n");
int placementStart = source.indexOf("public static int applyVerticalPlacement");
int shiftStart = source.indexOf("public static int applyVerticalShift", placementStart);
int alignmentStart = source.indexOf("static int alignOceanMonumentToSeaLevel", shiftStart);
int moveStart = source.indexOf("private static void moveStructureStart", alignmentStart);
int movePieceStart = source.indexOf("private static void moveStructurePiece", moveStart);
int monumentChildrenStart = source.indexOf("static List<StructurePiece> monumentChildPieces", movePieceStart);
assertTrue(placementStart >= 0);
assertTrue(shiftStart > placementStart);
assertTrue(alignmentStart > shiftStart);
assertTrue(moveStart > alignmentStart);
assertTrue(movePieceStart > moveStart);
assertTrue(monumentChildrenStart > movePieceStart);
String placementMethod = source.substring(placementStart, shiftStart);
String shiftMethod = source.substring(shiftStart, alignmentStart);
String moveMethod = source.substring(moveStart, movePieceStart);
String movePieceMethod = source.substring(movePieceStart, monumentChildrenStart);
assertTrue(placementMethod.contains("return alignOceanMonumentToSeaLevel("));
assertTrue(placementMethod.contains("return applyVerticalShift("));
assertTrue(shiftMethod.contains("StructureVerticalBounds.clampOffset"));
assertTrue(shiftMethod.contains("moveStructureStart(start, bounds, offsetY)"));
assertTrue(moveMethod.contains("moveStructurePiece(piece, offsetY)"));
assertTrue(moveMethod.contains("cachedBounds.move(0, offsetY, 0)"));
assertTrue(movePieceMethod.contains("piece.move(0, offsetY, 0)"));
assertTrue(movePieceMethod.contains("child.move(0, offsetY, 0)"));
assertTrue(movePieceMethod.contains("junction.getSourceGroundY() + offsetY"));
}
}
@@ -29,8 +29,6 @@ import org.junit.BeforeClass;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -42,7 +40,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class NMSBindingDatapackStructureScopeTest {
private static final String SOURCE = "https://example.test/managed.zip";
@@ -351,103 +348,6 @@ public class NMSBindingDatapackStructureScopeTest {
assertEquals(0, DatapackStructureStateFilter.exclusionZone(scopedPlacement).stream().count());
}
@Test
public void standardPublishesOneDeferredStateWhileAuthoringPublishesInitializedEmptyState() throws IOException {
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java")).replace("\r\n", "\n");
int methodStart = source.indexOf("public DatapackStructureScopeResult scopeDatapackStructures(");
int methodEnd = source.indexOf(
"\n @Override\n public CompletableFuture<Void> completeStudioStructureBootstrap",
methodStart);
assertTrue(methodStart >= 0);
assertTrue(methodEnd > methodStart);
String method = source.substring(methodStart, methodEnd);
int filteredState = method.indexOf("possibleSetsField.set(scopedState, selection.structureSets());");
int jigsawMode = method.indexOf(
"boolean authoringStudio = platformGenerator != null");
int jigsawOnly = method.indexOf("if (authoringStudio)");
int emptyCreation = method.indexOf("ChunkGeneratorStructureState bootstrapState = createStructureState(");
int emptyFiltering = method.indexOf("bootstrapSetsField.set(bootstrapState, List.of());");
int emptyInitialization = method.indexOf("bootstrapState.ensureStructuresGenerated();");
int emptyPublication = method.indexOf("stateField.set(chunkMap, bootstrapState);");
int standardOnly = method.indexOf("else if (studioBootstrap)");
int retention = method.indexOf("irisGenerator.retainStudioStructureState(");
int standardPublication = method.indexOf("stateField.set(chunkMap, scopedState);");
int immediateInitialization = method.indexOf("initializeAndPublishStructureState(");
assertTrue(filteredState >= 0);
assertTrue(jigsawMode > filteredState);
assertTrue(jigsawOnly > jigsawMode);
assertTrue(emptyCreation > jigsawOnly);
assertTrue(emptyFiltering > emptyCreation);
assertTrue(emptyInitialization > emptyFiltering);
assertTrue(emptyPublication > emptyInitialization);
assertTrue(standardOnly > emptyPublication);
assertTrue(retention > standardOnly);
assertTrue(standardPublication > retention);
assertTrue(immediateInitialization > standardPublication);
assertFalse(method.contains("scopedState.ensureStructuresGenerated();"));
assertFalse(method.contains("if (studioBootstrap && platformGenerator.isJigsawStudioActive())"));
}
@Test
public void standardCompletionReturnsTheExactActivationFutureWithoutReplacingState() throws IOException {
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java")).replace("\r\n", "\n");
int methodStart = source.indexOf("public CompletableFuture<Void> completeStudioStructureBootstrap(World world)");
int methodEnd = source.indexOf("\n @Override\n public void abandonStudioStructureBootstrap", methodStart);
assertTrue(methodStart >= 0);
assertTrue(methodEnd > methodStart);
String method = source.substring(methodStart, methodEnd);
int retained = method.indexOf("generator.retainedStudioStructureState(level, chunkMap)");
int emptyCompletion = method.indexOf("return CompletableFuture.completedFuture(null);");
int activation = method.indexOf("return generator.activateStudioStructureState(retained);");
assertTrue(retained >= 0);
assertTrue(emptyCompletion > retained);
assertTrue(activation > retained);
assertFalse(method.contains("stateField.set("));
assertFalse(method.contains("retained.fullState()"));
}
@Test
public void injectionVerifiesTheCanonicalPaperGeneratorBeforeStructureRetargeting() throws IOException {
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java")).replace("\r\n", "\n");
int methodStart = source.indexOf("public void inject(long seed, Engine engine, World world)");
int methodEnd = source.indexOf("\n @Override\n public DatapackStructureScopeResult", methodStart);
assertTrue(methodStart >= 0);
assertTrue(methodEnd > methodStart);
String method = source.substring(methodStart, methodEnd);
int publication = method.indexOf("worldGenContextField.set(chunkMap, newContext);");
int canonicalRead = method.indexOf("level.getChunkSource().getGenerator()", publication);
int identityGate = method.indexOf("activeGenerator != irisGenerator", canonicalRead);
int structureRetarget = method.indexOf("retargetStructureCheck(level, irisGenerator)", identityGate);
assertTrue(publication >= 0);
assertTrue(canonicalRead > publication);
assertTrue(identityGate > canonicalRead);
assertTrue(structureRetarget > identityGate);
}
@Test
public void structureStateRecreationUsesTheWorldOwnedSpigotConfiguration() throws IOException {
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java")).replace("\r\n", "\n");
int methodStart = source.indexOf("private ChunkGeneratorStructureState createStructureState(");
int methodEnd = source.indexOf(
"\n private void initializeAndPublishStructureState(", methodStart);
assertTrue(methodStart >= 0);
assertTrue(methodEnd > methodStart);
String method = source.substring(methodStart, methodEnd);
assertTrue(method.contains("level.spigotConfig"));
assertFalse(method.contains("currentState.conf"));
}
private static DatapackStructureScopeIndex index(
List<String> structureKeys,
List<String> structureSetKeys
@@ -1,29 +0,0 @@
package art.arcane.iris.core.nms.v26_2_R1;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NMSBindingPlacementFailureContractTest {
@Test
public void structurePlacementPropagatesRuntimeFailuresWithContext() throws IOException {
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java")).replace("\r\n", "\n");
int methodStart = source.indexOf("public int[] placeStructure(");
int methodEnd = source.indexOf("\n @Override", methodStart + 1);
String method = source.substring(methodStart, methodEnd);
int catchStart = method.indexOf("catch (RuntimeException e)");
assertTrue(catchStart >= 0);
String failurePath = method.substring(catchStart);
assertTrue(failurePath.contains("throw NativeStructureGenerationException.failure("));
assertTrue(failurePath.contains("\"capture placement\", structureKey, chunkX, chunkZ, e"));
assertFalse(failurePath.contains("return null;"));
assertFalse(failurePath.contains("catch (Throwable"));
}
}
@@ -1,43 +0,0 @@
package art.arcane.iris.core.nms.v26_2_R1;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NMSBindingStructureFailureContractTest {
@Test
public void structureRegistryHooksThrowInsteadOfReturningEmptyOnFailure() throws IOException {
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java")).replace("\r\n", "\n");
List<String> methodNames = List.of(
"getStructureKeys",
"getStructureSetKeys",
"getReachableStructureKeys",
"getStructureBiomeKeys",
"getPossibleBiomeKeys");
for (String methodName : methodNames) {
String method = methodSource(source, methodName);
assertTrue(methodName + " must preserve failure context", method.contains("throw new IllegalStateException("));
assertTrue(methodName + " must retain its root cause", method.contains(", e);"));
assertFalse(methodName + " must not log and return an empty registry result",
method.contains("IrisLogging.reportError"));
assertFalse(methodName + " must not catch fatal JVM errors", method.contains("catch (Throwable"));
}
}
private static String methodSource(String source, String methodName) {
int start = source.indexOf("public KList<String> " + methodName + "(");
int end = source.indexOf("\n @Override", start + 1);
if (start < 0 || end < 0) {
throw new IllegalArgumentException("Unable to find NMS binding method " + methodName);
}
return source.substring(start, end);
}
}
@@ -1,30 +0,0 @@
package art.arcane.iris.core.nms.v26_2_R1;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertTrue;
public class NMSBindingTileDeserializeContractTest {
@Test
public void ownedRegionTileDataMergesBeforeScheduledFallback() throws IOException {
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java")).replace("\r\n", "\n");
int methodStart = source.indexOf("public void deserializeTile(");
int methodEnd = source.indexOf("\n private void merge(", methodStart);
String method = source.substring(methodStart, methodEnd);
int ownershipCheck = method.indexOf("J.isOwnedByCurrentRegion(");
int synchronousMerge = method.indexOf("merge(level, blockPos, tag);", ownershipCheck);
int synchronousReturn = method.indexOf("return;", synchronousMerge);
int scheduledFallback = method.indexOf("J.runAt(pos, () -> merge(level, blockPos, tag))");
assertTrue(ownershipCheck >= 0);
assertTrue(synchronousMerge > ownershipCheck);
assertTrue(synchronousReturn > synchronousMerge);
assertTrue(scheduledFallback > synchronousReturn);
}
}
@@ -1,103 +0,0 @@
package art.arcane.iris.core.nms.v26_2_R1;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NmsWorldLifecycleServerLevelAdviceContractTest {
@Test
public void serverLevelAdviceSupportsCurrentSpigotAndPaperConstructorLayouts() throws Exception {
String source = Files.readString(
Path.of(System.getProperty("iris.nmsBindingSource")).resolveSibling("NmsWorldLifecycle.java")).replace("\r\n", "\n");
String transformer = section(
source,
"public boolean injectBukkit()",
"public void ensureServerLevelInjection()");
String advice = section(
source,
"private static class ServerLevelAdvice",
"\n }\n}");
assertTrue(transformer.contains("takesArgument(0, MinecraftServer.class)"));
assertTrue(transformer.contains("takesArgument(5, LevelStem.class)"));
assertFalse(transformer.contains("takesArgument(12, ChunkGenerator.class)"));
assertFalse(transformer.contains("takesArgument(13, ChunkGenerator.class)"));
assertTrue(advice.contains("@Advice.AllArguments Object[] constructorArguments"));
assertTrue(advice.contains("argument instanceof ChunkGenerator candidate"));
assertFalse(advice.contains("@Advice.Argument(12)"));
assertFalse(advice.contains("@Advice.Argument(13)"));
}
@Test
public void currentSpigotStorageAccessReceivesManagedIdentityBeforeConstruction() throws Exception {
String source = Files.readString(
Path.of(System.getProperty("iris.nmsBindingSource")).resolveSibling("NmsWorldLifecycle.java")).replace("\r\n", "\n");
String transformer = section(
source,
"public boolean injectBukkit()",
"public void ensureServerLevelInjection()");
String advice = section(
source,
"private static class LevelStorageAccessAdvice",
"private static class ServerLevelAdvice");
assertTrue(transformer.contains(
".type(ElementMatchers.is(LevelStorageSource.LevelStorageAccess.class))"));
assertTrue(transformer.contains("Advice.to(LevelStorageAccessAdvice.class)"));
assertTrue(transformer.contains("ElementMatchers.takesArguments(4)"));
assertTrue(transformer.contains(
"ElementMatchers.takesArgument(0, LevelStorageSource.class)"));
assertTrue(transformer.contains("ElementMatchers.takesArgument(1, String.class)"));
assertTrue(transformer.contains("ElementMatchers.takesArgument(2, Path.class)"));
assertTrue(transformer.contains("ElementMatchers.takesArgument(3, ResourceKey.class)"));
assertTrue(advice.contains("@Advice.Argument(1) String levelId"));
assertTrue(advice.contains(
"@Advice.Argument(value = 3, readOnly = false) ResourceKey<LevelStem> dimensionType"));
assertTrue(advice.contains("getDeclaredMethod(\"peekStemGenerator\", String.class)"));
assertTrue(advice.contains(".invoke(null, levelId)"));
assertTrue(advice.contains(
"dimensionType = ResourceKey.create(Registries.LEVEL_STEM, worldIdentifier);"));
assertFalse(advice.contains("dimensionRoot("));
assertFalse(advice.contains("Files.copy"));
}
@Test
public void ownedWorldPublishesItsManagedIdentityAndRuntimeStemTogether() throws Exception {
String source = Files.readString(
Path.of(System.getProperty("iris.nmsBindingSource")).resolveSibling("NmsWorldLifecycle.java")).replace("\r\n", "\n");
String advice = section(
source,
"private static class ServerLevelAdvice",
"\n }\n}");
assertTrue(advice.contains(
"@Advice.Argument(value = 4, readOnly = false) ResourceKey<Level> dimensionKey"));
assertTrue(advice.contains("getMethod(\"getTarget\")"));
assertTrue(advice.contains("getMethod(\"getWorld\")"));
assertTrue(advice.contains("getMethod(\"identity\")"));
assertTrue(advice.contains("\"iris\".equals(worldIdentifier.getNamespace())"));
assertTrue(advice.contains("\"minecraft\".equals(worldIdentifier.getNamespace())"));
int resolvedStem = advice.indexOf("Object resolvedStem = stemMethod.invoke(");
int validatedStem = advice.indexOf("resolvedStem instanceof LevelStem runtimeStem");
int identityPublication = advice.indexOf(
"dimensionKey = ResourceKey.create(Registries.DIMENSION, worldIdentifier);");
int stemPublication = advice.indexOf("levelStem = runtimeStem;");
assertTrue(resolvedStem >= 0);
assertTrue(validatedStem > resolvedStem);
assertTrue(identityPublication > validatedStem);
assertTrue(stemPublication > identityPublication);
}
private static String section(String source, String startMarker, String endMarker) {
int start = source.indexOf(startMarker);
int end = source.indexOf(endMarker, start);
assertTrue("Missing source section starting with " + startMarker, start >= 0);
assertTrue("Missing source section ending with " + endMarker, end > start);
return source.substring(start, end);
}
}
@@ -1,60 +0,0 @@
package art.arcane.iris.core.nms.v26_2_R1;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class NmsWorldLifecycleShutdownBoundaryContractTest {
@Test
public void shutdownClassificationUsesTheServerStopFlagInsteadOfPluginEnablement() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.nmsBindingSource")).resolveSibling("NmsWorldLifecycle.java"));
String stopping = section(source, "public boolean isServerStopping()", "public ServerShutdownBoundary createServerShutdownBoundary");
assertTrue(stopping.contains("((CraftServer) Bukkit.getServer()).getServer().hasStopped()"));
assertFalse(stopping.contains("isEnabled()"));
assertFalse(stopping.contains("isRunning()"));
}
@Test
public void pluginLoaderGuardUsesSystemAgentIdentityAndIsRemovedAtRelease() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.nmsBindingSource")).resolveSibling("NmsWorldLifecycle.java"));
String injection = section(source, "public boolean injectBukkit()", "public void ensureServerLevelInjection()");
String guard = section(source, "private static class PluginClassLoaderCloseAdvice", "private static class LevelStorageAccessAdvice");
String release = section(source, "public void releasePluginClassLoaderClose()", "private static final class PluginClassLoaderInjectionListener");
assertTrue(injection.contains("Agent.requireClassLoaderCloseDeferral()"));
assertTrue(injection.contains("getMethod(\"close\").getDeclaringClass()"));
assertTrue(injection.contains("Advice.to(PluginClassLoaderCloseAdvice.class)"));
assertTrue(guard.contains("skipOn = Advice.OnNonDefaultValue.class"));
assertTrue(guard.contains("ClassLoader.getSystemClassLoader()"));
assertTrue(guard.contains("getMethod(\"deferClassLoaderClose\", ClassLoader.class)"));
assertTrue(guard.contains(".invoke(null, loader)"));
assertFalse(guard.contains("Bukkit.getPluginManager()"));
assertTrue(release.indexOf("transformer.reset(") > release.indexOf("pluginClassLoaderCloseDeferred = false"));
assertTrue(release.indexOf("Agent.releaseClassLoader(") > release.indexOf("transformer.reset("));
}
@Test
public void shutdownBoundaryUsesPaperFullyShutdownStateAndServerThread() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.nmsBindingSource")).resolveSibling("NmsWorldLifecycle.java")).replace("\r\n", "\n");
String boundary = section(source, "public ServerShutdownBoundary createServerShutdownBoundary", "private static final class PluginClassLoaderInjectionListener");
assertTrue(boundary.contains("new ServerShutdownBoundary("));
assertTrue(boundary.contains("server.hasFullyShutdown"));
assertTrue(boundary.contains("server.getRunningThread()"));
assertTrue(boundary.contains("((CraftServer) Bukkit.getServer()).getServer()"));
assertFalse(boundary.contains("getHandle()"));
}
private static String section(String source, String startMarker, String endMarker) {
int start = source.indexOf(startMarker);
int end = source.indexOf(endMarker, start);
assertTrue("Missing source section starting with " + startMarker, start >= 0);
assertTrue("Missing source section ending with " + endMarker, end > start);
return source.substring(start, end);
}
}
@@ -1,38 +0,0 @@
package art.arcane.iris.core.nms.v26_2_R1;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* A registered structure with an EMPTY biome filter is legal datapack content: opt-in structures
* (e.g. Towns and Towers' towns_and_towers:exclusives/*) ship biome tags that only reference
* optional modded biomes, so the filter resolves to zero entries on a vanilla server. Resolving
* biome keys for such a structure must return an empty set (the structure is simply unreachable),
* never throw — a throw here aborts the whole /iris structure verify run and degrades /iris find.
* The defensive throw is only kept for a NON-empty filter whose holders all fail to resolve keys.
*/
public class VanillaStructureBiomesEmptyFilterContractTest {
@Test
public void emptyBiomeFilterReturnsEmptyKeysInsteadOfThrowing() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.vanillaStructureBiomesSource")));
assertTrue(source.contains("if (keys.isEmpty() && hasFilterEntries)"));
assertTrue(source.contains("has biome filter entries but none resolve to registered biome keys"));
assertFalse(source.contains("exposes no registered biome keys"));
}
@Test
public void moddedHookMatchesEmptyFilterContract() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.moddedStructureHooksSource")));
assertTrue(source.contains("if (keys.isEmpty() && hasFilterEntries)"));
assertTrue(source.contains("has biome filter entries but none resolve to registered biome keys"));
assertFalse(source.contains("exposes no registered biome keys"));
}
}
@@ -59,9 +59,6 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemp
import org.junit.BeforeClass;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -316,52 +313,6 @@ public class NativeStructureFactoryTest {
assertEquals(1, oversized.getPieces().size());
}
@Test
public void failedManualGenerationClearsStaleOwnershipAfterReplacementHandling() throws Exception {
String source = Files.readString(
Path.of(System.getProperty("iris.nativeStructureStartInjectorSource")),
StandardCharsets.UTF_8);
int failureStart = source.indexOf("if (!isUsableGeneratedStart(generated))");
int failureEnd = source.indexOf("continue;", failureStart);
String failureBranch = source.substring(failureStart, failureEnd);
assertTrue(failureBranch.contains("if (replacement)"));
assertTrue(failureBranch.indexOf("NativeStructureOwnershipStore.discard(")
> failureBranch.lastIndexOf("}") );
assertTrue(failureStart < source.indexOf("NativeStructureOwnershipFingerprint.capture("));
assertTrue(failureStart < source.indexOf("NativeStructureOwnershipStore.record("));
}
@Test
public void manualNativeStructureGenerationUsesTheRootTerrainHeight() throws Exception {
String source = Files.readString(
Path.of(System.getProperty("iris.nativeStructureStartInjectorSource")),
StandardCharsets.UTF_8);
assertTrue(source.contains(
"Engine.hostHeight(context.engine(), x, z, true)"));
assertFalse(source.contains(
"context.engine().getHeight(x, z, true)"));
}
@Test
public void failedManualStartPublicationClearsRecordedOwnershipAndPreservesTheFailure() throws Exception {
String source = Files.readString(
Path.of(System.getProperty("iris.nativeStructureStartInjectorSource")),
StandardCharsets.UTF_8);
int ownershipRecord = source.indexOf("NativeStructureOwnershipStore.record(");
int publication = source.indexOf("context.structureManager().setStartForStructure(", ownershipRecord);
int cleanup = source.indexOf("NativeStructureOwnershipStore.discard(", publication);
int suppressed = source.indexOf("publicationError.addSuppressed(cleanupError)", cleanup);
int rethrow = source.indexOf("throw publicationError;", suppressed);
assertTrue(ownershipRecord >= 0);
assertTrue(publication > ownershipRecord);
assertTrue(cleanup > publication);
assertTrue(suppressed > cleanup);
assertTrue(rethrow > suppressed);
}
private static final class TestChunkGenerator extends ChunkGenerator {
private TestChunkGenerator() {
super(new FixedBiomeSource(Holder.direct((Biome) null)));
@@ -9,9 +9,6 @@ import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
@@ -24,20 +21,6 @@ public class NativeStructureGenerationKeysContractTest {
Bootstrap.bootStrap();
}
@Test
public void reachabilityUsesEnabledActiveStructureSetsWithoutLazyPlacementGeneration() throws IOException {
String source = Files.readString(Path.of(
System.getProperty("iris.nativeStructureGenerationKeysSource")));
assertTrue(source.contains("getWorldGenSettings().options().generateStructures()"));
assertTrue(source.contains("getGeneratorState().possibleStructureSets()"));
assertTrue(source.contains("isEnabledPlacement(structureSet.placement())"));
assertTrue(source.contains("StructurePlacement.class.getDeclaredMethods()"));
assertTrue(source.contains("entry.weight() <= 0"));
assertTrue(source.contains("hasPossibleBiome(entry.structure().value(), possibleBiomes)"));
assertFalse(source.contains("getPlacementsForStructure("));
}
@Test
public void frequencyGateUsesMappedAccessorAndRejectsNonPositivePlacements() {
assertFalse(NativeStructureGenerationKeys.isEnabledPlacement(placement(0.0F)));
@@ -39,11 +39,8 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProc
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
@@ -221,18 +218,6 @@ public class NativeStructurePostProcessorEncaseTest {
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
}
@Test
public void encaseFillRunsBeforeNativePlacement() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
int prepareTerrain = source.indexOf("NativeStructurePostProcessor.prepareTerrain(");
int placementLoop = source.indexOf("for (NativePlacementGroup group : placementGroups)", prepareTerrain);
int placement = source.indexOf("placeVanillaStructure(boundedWorld, structureManager, random", placementLoop);
assertTrue(prepareTerrain >= 0);
assertTrue(placementLoop > prepareTerrain);
assertTrue(placement > placementLoop);
}
@Test
public void omittedTerrainConfigurationRetainsSourceSemantics() {
for (TerrainAdjustment adjustment : TerrainAdjustment.values()) {
@@ -19,8 +19,6 @@ import net.minecraft.world.level.levelgen.structure.structures.SwampHutStructure
import org.junit.BeforeClass;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import java.lang.reflect.Proxy;
import java.lang.reflect.Field;
import java.util.List;
@@ -326,38 +324,6 @@ public class NativeStructureVolumeIndexTest {
assertEquals("8:8", volumes.getLast().structure());
}
@Test
public void volumeResolutionNeverReadsChunkOrOwnershipState() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.nativeStructureVolumeIndexSource")));
assertFalse(source.contains("StructureManager"));
assertFalse(source.contains("getStartForStructure"));
assertFalse(source.contains("getAllStarts"));
assertFalse(source.contains("ChunkAccess"));
assertFalse(source.contains("NativeStructureOwnershipStore"));
assertFalse(source.contains("NativeStructureOwnershipRecovery"));
}
@Test
public void vanillaVolumesAreGatedOnPackPolicy() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.nativeStructureVolumeIndexSource")));
assertTrue(source.contains("NativeStructureGenerationPolicy.resolve("));
assertTrue(source.contains("if (!decision.generate())"));
assertTrue(source.contains("isStructureChunk("));
}
@Test
public void originResolutionRoutesAndCachesByScopedRuntime() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.nativeStructureVolumeIndexSource")));
assertTrue(source.contains("openHistoryCoordinateScope(engine, chunkX, chunkZ)"));
assertTrue(source.contains("new RuntimeChunkKey(runtimeId, chunkKey(chunkX, chunkZ))"));
assertTrue(source.contains("addGenerationRuntimeRetirementListener(retirementListener)"));
assertTrue(source.contains("originCache.keySet().removeIf(key -> key.runtimeId() == runtimeId)"));
assertTrue(source.contains("queryCache.keySet().removeIf(key -> key.runtimeId() == runtimeId)"));
}
private static ScopedEngine scopedEngine(boolean scoped, int ownerRuntimeId) throws Exception {
IrisEngine engine = mock(IrisEngine.class);
GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class);
@@ -378,7 +344,6 @@ public class NativeStructureVolumeIndexTest {
return new ScopedEngine(engine, scopes);
}
@SuppressWarnings("unchecked")
private static Map<Engine, NativeStructureVolumeIndex> installedIndexes() throws Exception {
Field indexes = NativeStructureVolumeIndex.class.getDeclaredField("INDEXES");
-6
View File
@@ -59,15 +59,9 @@ tasks.named('jar', Jar).configure {
}
tasks.named('test').configure {
systemProperty('iris.commandFindSource', file('src/main/java/art/arcane/iris/core/commands/CommandFind.java').absolutePath)
systemProperty('iris.commandStructureSource', file('src/main/java/art/arcane/iris/core/commands/CommandStructure.java').absolutePath)
systemProperty('iris.commandIrisSource', file('src/main/java/art/arcane/iris/core/commands/CommandIris.java').absolutePath)
systemProperty('iris.bukkitChunkGeneratorSource', rootProject.file('core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java').absolutePath)
systemProperty('iris.pregeneratorJobSource', rootProject.file('core/src/main/java/art/arcane/iris/core/gui/PregeneratorJob.java').absolutePath)
systemProperty('iris.bukkitEnginePlatformHooksSource', file('src/main/java/art/arcane/iris/core/runtime/BukkitEnginePlatformHooks.java').absolutePath)
systemProperty('iris.engineSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisEngineSVC.java').absolutePath)
systemProperty('iris.jigsawStudioSvcSource', rootProject.file('core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java').absolutePath)
systemProperty('iris.studioSvcSource', rootProject.file('core/src/main/java/art/arcane/iris/core/service/StudioSVC.java').absolutePath)
systemProperty('iris.terrainSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisTerrainSVC.java').absolutePath)
systemProperty('iris.apiEventSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisApiEventSVC.java').absolutePath)
systemProperty('iris.worldInfoFactorySource', file('src/main/java/art/arcane/iris/core/service/terrain/IrisWorldInfoFactory.java').absolutePath)
@@ -1,222 +0,0 @@
package art.arcane.iris;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class IrisShutdownOrderingTest {
@Test
public void serverStopHoldsThePluginLoaderUntilTerminalCleanupCompletes() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String quiesce = section(source, "private void quiesceRuntimeForServerShutdown", "private void startPostStopFinisher");
String cleanup = section(source, "private void finishTerminalCleanup()", "private void drainWorldGenerators");
String teardown = section(source, "private void teardownRuntime", "private void quiesceRuntimeForServerShutdown");
String deferred = section(source, "private void finishDeferredRuntimeTeardown", "private void finishTerminalCleanup");
assertOrdered(quiesce, "serverStopTeardownDeferred.set(true)", "deferPluginClassLoaderClose()",
"jigsawStudioService.quiesceForServerShutdown()");
assertOrdered(cleanup, "runPostShutdown()", "hasActiveShutdownResources()", "IrisPlatforms.unbind()",
"runtimeTeardownFailed.get()", "releasePluginClassLoaderClose()");
assertTrue(cleanup.contains("!MultiBurst.burst.isTerminated() || !MultiBurst.ioBurst.isTerminated()"));
assertTrue(cleanup.contains("preservation.hasActiveResources()"));
assertOrdered(teardown, "drainWorldGenerators(reason, timeoutSeconds)", "!generatorDrainCompleted",
"return;", "service.onDisable()");
assertOrdered(deferred, "teardownRuntime(reason, timeoutSeconds)", "!generatorDrainCompleted",
"SHUTDOWN_ERRORS.println", "return;", "finishTerminalCleanup()");
}
@Test
public void deferredShutdownErrorsBypassClosedLoggingServices() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String throwableReport = section(source, "public static void reportError(Throwable e)",
"public static void reportError(String context, Throwable e)");
String contextualReport = section(source, "public static void reportError(String context, Throwable e)",
"public static void dump()");
assertOrdered(throwableReport, "serverStopTeardownDeferred.get()",
"e.printStackTrace(SHUTDOWN_ERRORS)", "boolean debug = false");
assertOrdered(contextualReport, "serverStopTeardownDeferred.get()",
"SHUTDOWN_ERRORS.println(", "error.printStackTrace(SHUTDOWN_ERRORS)", "Iris.error(message)");
}
@Test
public void drainWorldGenerators_closesGeneratorsWithoutEagerMantleSave() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String drain = section(source, "private void drainWorldGenerators", "private void setupPapi");
assertTrue("Shutdown must close each Iris generator", drain.contains("generator.closeAsync()"));
assertFalse("Shutdown must not close Mantle plates before generation drains", drain.contains("saveAllNow()"));
}
@Test
public void shutdownBoundaryIsPreparedBeforeHookRegistrationAndDoesNotUseClosedBindings() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String registration = section(source, "public void addShutdownHook()", "public void removeShutdownHook()");
String boundary = section(source, "private boolean awaitServerShutdownBoundary()",
"private void finishDeferredRuntimeTeardown");
assertOrdered(registration, "createServerShutdownBoundary()", "new Thread(this::runShutdownHook",
"Runtime.getRuntime().addShutdownHook");
assertTrue(boundary.contains("boundary.await("));
assertFalse(boundary.contains("INMS.get()"));
assertFalse(boundary.contains("Iris.reportError"));
assertTrue(source.contains("new FileOutputStream(FileDescriptor.err)"));
assertOrdered(boundary, "SHUTDOWN_ERRORS.println(", "e.printStackTrace(SHUTDOWN_ERRORS)", "return false;");
}
@Test
public void serverStop_defersRuntimeTeardownUntilPaperShutdownBoundary() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String onDisable = section(source, "public void onDisable()", "public void onPreUnload");
String quiesce = section(source, "private void quiesceRuntimeForServerShutdown", "private void startPostStopFinisher");
String shutdownHook = section(source, "private void runShutdownHook()", "private boolean awaitServerShutdownBoundary");
String finisher = section(source, "private void startPostStopFinisher()", "static boolean awaitServerThreadTermination");
String serverJoin = section(source, "static boolean awaitServerThreadTermination", "private void runShutdownHook");
String generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
String generatorQuiesce = section(generatorSource,
"public void quiesceForServerShutdown()", "public boolean isStudio()");
assertOrdered(onDisable,
"startupBoundaryRestart.get()",
"teardownRuntime(\"startup-boundary-restart\", 30L)",
"else if (serverStopping)",
"quiesceRuntimeForServerShutdown(\"onDisable\")",
"startPostStopFinisher()",
"} else {",
"teardownRuntime(\"onDisable\", 30L)");
assertOrdered(shutdownHook,
"startupBoundaryRestart.get()",
"finishDeferredRuntimeTeardown(\"startup-boundary-restart-hook\", 30L)",
"return;",
"awaitServerShutdownBoundary()",
"SHUTDOWN_ERRORS.println",
"finishDeferredRuntimeTeardown(\"shutdown-hook\", 30L)");
assertOrdered(finisher,
"finisher.setDaemon(false)",
"finisher.start()");
assertOrdered(finisher,
"awaitServerThreadTermination(activeServerThread)",
"finishDeferredRuntimeTeardown(\"post-server-stop\", 30L)");
assertOrdered(serverJoin,
"serverThread == Thread.currentThread()",
"serverThread.join()");
assertTrue("Server-stop quiescence must leave queued Paper generation admitted",
quiesce.contains("generator.quiesceForServerShutdown()"));
assertOrdered(quiesce,
"jigsawStudioService.quiesceForServerShutdown()",
"PregeneratorJob.shutdownAndWait",
"generator.quiesceForServerShutdown()");
assertOrdered(onDisable,
"quiesceRuntimeForServerShutdown(\"onDisable\")",
"super.onDisable()");
assertFalse("Server-stop quiescence must not begin generator close before Paper's boundary",
generatorQuiesce.contains("closing = true"));
assertFalse("Server-stop quiescence must not dispatch generator close before Paper's boundary",
generatorQuiesce.contains("closeAsync()"));
}
@Test
public void deferredTeardown_keepsGeneratorClosingServicesBehindGeneratorDrain() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String engineService = Files.readString(Path.of(System.getProperty("iris.engineSvcSource")));
String studioService = Files.readString(Path.of(System.getProperty("iris.studioSvcSource")));
String generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
String teardown = section(source, "private void teardownRuntime", "private void quiesceRuntimeForServerShutdown");
String engineDisable = section(engineService, "public void onDisable()", "public void engineStatus");
String studioDisable = section(studioService, "public void onDisable()", "public IrisDimension installIntoWorld");
String generatorClose = section(generatorSource,
"public void close()", "public CompletableFuture<Void> closeAsync()");
String generatorCloseAsync = section(generatorSource,
"public CompletableFuture<Void> closeAsync()", "public void quiesceForServerShutdown()");
assertOrdered(teardown,
"drainWorldGenerators(reason, timeoutSeconds)",
"service.onDisable()",
"MultiBurst.burst.close()",
"MultiBurst.ioBurst.close()");
assertTrue("Engine service must retain its generator close behind deferred service teardown",
engineDisable.contains("startClose("));
assertTrue("Studio service must retain its generator close behind deferred service teardown",
studioDisable.contains("generator.close()"));
assertTrue("Service-level generator close must delegate to the shared idempotent close future",
generatorClose.contains("closeAsync()"));
assertTrue("Repeated post-boundary closes must return the already-published close future",
generatorCloseAsync.contains("return existing;"));
assertFalse("A completed generator close must never be re-dispatched",
generatorCloseAsync.contains("!existing.isDone()"));
}
@Test
public void preUnload_doesNotDrainGeneratorsDuringServerStop() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String preUnload = section(source, "public void onPreUnload", "private void drainOnce");
assertOrdered(preUnload,
"IrisToolbelt.isServerStopping()",
"quiesceRuntimeForServerShutdown",
"startPostStopFinisher()",
"return;",
"drainOnce(");
}
@Test
public void jigsawStudio_quiescesOnceBeforeDeferredServiceTeardown() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.jigsawStudioSvcSource")));
String enable = section(source, "public void onEnable()", "public void onDisable()");
String disable = section(source, "public void onDisable()", "public void quiesceForServerShutdown()");
String quiesce = section(source, "public void quiesceForServerShutdown()", "public void register(");
String register = section(source, "public void register(", "public void activationCommitted(");
String activation = section(source, "public void activationCommitted(", "public void markChunkGenerated(");
String chunkGenerated = section(source, "public void markChunkGenerated(", "private void markChunkAvailable(");
assertOrdered(enable, "disableStarted.set(false)", "enabled = true");
assertTrue("Deferred service teardown must reuse the idempotent early disable",
disable.contains("quiesceForServerShutdown();"));
assertOrdered(quiesce,
"disableStarted.compareAndSet(false, true)",
"finalizeAllJigsawTileWatches()",
"drainAutosavesBeforeDisable()",
"enabled = false",
"activeMenuController.closeAll()",
"previewRenderer.removeAll()",
"studios.clear()");
assertTrue("Registration must reject work after shutdown begins",
occurrences(register, "!enabled || disableStarted.get()") >= 2);
assertTrue("Activation must reject work after shutdown begins",
activation.contains("!enabled || disableStarted.get()"));
assertTrue("Chunk-generation callbacks must reject work after shutdown begins",
occurrences(chunkGenerated, "!enabled || disableStarted.get()") >= 2);
}
private static String section(String source, String startMarker, String endMarker) {
int start = source.indexOf(startMarker);
int end = source.indexOf(endMarker, start);
assertTrue("Missing source section starting with " + startMarker, start >= 0);
assertTrue("Missing source section ending with " + endMarker, end > start);
return source.substring(start, end);
}
private static void assertOrdered(String source, String... markers) {
int previous = -1;
for (String marker : markers) {
int current = source.indexOf(marker);
assertTrue("Missing source marker " + marker, current >= 0);
assertTrue("Source marker is out of order: " + marker, current > previous);
previous = current;
}
}
private static int occurrences(String source, String marker) {
int count = 0;
int offset = 0;
while ((offset = source.indexOf(marker, offset)) >= 0) {
count++;
offset += marker.length();
}
return count;
}
}
@@ -15,12 +15,10 @@ import org.junit.Test;
import org.mockito.MockedStatic;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
@@ -132,125 +130,6 @@ public class PendingWorldReplacementThreadAffinityTest {
assertTrue(irisEnvironmentFailure.getMessage().contains("requires a pack environment of NETHER"));
}
@Test
public void bukkitAccessIsConfinedToTheGlobalCaptureStage() throws Exception {
String managerSource = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java")).replace("\r\n", "\n");
String irisSource = Files.readString(Path.of("src/main/java/art/arcane/iris/Iris.java")).replace("\r\n", "\n");
String startup = method(managerSource, "public void verifyLoadedPublishedWorlds()");
String worldLoad = method(managerSource, "public void onWorldLoad(WorldLoadEvent event)");
String discovery = method(managerSource, "private void discoverLoadedPublishedWorlds()");
String capture = method(managerSource,
"private void captureLoadedPublishedWorldOnGlobal(Transaction transaction)");
String snapshot = method(managerSource, "static PublishedWorldRuntimeState capturePublishedWorldRuntime(World world)");
String verification = method(managerSource,
"private void verifyPublishedWorld(PublishedWorldRuntimeState runtimeState, Transaction transaction)");
assertTrue(startup.contains("J.a(this::discoverLoadedPublishedWorlds)"));
assertTrue(worldLoad.contains("WorldIdentity.key(event.getWorld())"));
assertTrue(worldLoad.contains("J.a(() -> discoverLoadedWorldTransaction(worldKey))"));
assertTrue(capture.contains("WorldIdentity.resolve("));
assertBefore(capture, "capturePublishedWorldRuntime(world)",
"J.a(() -> runPublishedWorldVerification(runtimeState, transaction))");
assertTrue(snapshot.contains("WorldIdentity.key(requiredWorld)"));
assertTrue(snapshot.contains("IrisToolbelt.isIrisWorld(requiredWorld)"));
assertTrue(snapshot.contains("requiredWorld.getSeed()"));
assertTrue(snapshot.contains("requiredWorld.getEnvironment()"));
assertTrue(snapshot.contains("IrisToolbelt.access(requiredWorld)"));
assertNoBukkitRuntimeAccess(discovery);
assertNoBukkitRuntimeAccess(verification);
assertTrue(verification.contains("WorldReplacementFilesystem.fingerprintPack("));
assertTrue(irisSource.contains("pendingWorldReplacements.verifyLoadedPublishedWorlds();"));
assertFalse(irisSource.contains("J.a(pendingWorldReplacements::verifyLoadedPublishedWorlds)"));
}
@Test
public void paperLoginHookIsIsolatedFromAlwaysLoadedSpigotClasses() throws Exception {
String managerSource = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java")).replace("\r\n", "\n");
String irisSource = Files.readString(Path.of("src/main/java/art/arcane/iris/Iris.java")).replace("\r\n", "\n");
String listenerSource = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/PaperWorldReplacementEntryListener.java")).replace("\r\n", "\n");
String registration = method(managerSource, "public void registerPlatformEntryListener()");
assertFalse(managerSource.contains("import io.papermc.paper.event.player.AsyncPlayerSpawnLocationEvent"));
assertFalse(managerSource.contains("AsyncPlayerSpawnLocationEvent event"));
assertFalse(irisSource.contains("AsyncPlayerSpawnLocationEvent"));
assertTrue(registration.contains("Class.forName(\"io.papermc.paper.event.player.AsyncPlayerSpawnLocationEvent\""));
assertTrue(registration.contains("Class.forName("));
assertTrue(registration.contains("PaperWorldReplacementEntryListener"));
assertTrue(irisSource.contains("pendingWorldReplacements.registerPlatformEntryListener();"));
assertTrue(listenerSource.contains("onAsyncPlayerSpawnLocation(AsyncPlayerSpawnLocationEvent event)"));
}
@Test
public void redirectedPlayerReceiptSurvivesUntilTheMaterializedPositionIsSaved() throws Exception {
String managerSource = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java")).replace("\r\n", "\n");
String listenerSource = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/PaperWorldReplacementEntryListener.java")).replace("\r\n", "\n");
String preparation = method(
managerSource,
"ReplacementEntryRedirect prepareReplacementEntry(UUID playerId, Location savedLocation, boolean newPlayer)"
);
String acknowledgement = method(
managerSource,
"void expectReplacementEntryAcknowledgement(UUID playerId, UUID transactionId)"
);
String join = method(managerSource, "public void onPlayerJoin(PlayerJoinEvent event)");
String listener = method(
listenerSource,
"public void onAsyncPlayerSpawnLocation(AsyncPlayerSpawnLocationEvent event)"
);
assertTrue(preparation.contains("return new ReplacementEntryRedirect(guard.transactionId(), prepared, pendingPlayer)"));
assertFalse(preparation.substring(preparation.indexOf("CompletableFuture<Location> safeEntry"))
.contains("completeOverworldEntry("));
assertBefore(listener, "event.setSpawnLocation(location)",
"manager.expectReplacementEntryAcknowledgement(playerId, redirect.transactionId())");
assertTrue(acknowledgement.contains("pendingEntryAcknowledgements.put(playerId, transactionId)"));
assertBefore(join, "event.getPlayer().saveData()", "completeOverworldEntry(playerId, transactionId)");
}
@Test
public void replacementSpawnIsPersistedBeforeFinalMarkerRetirement() throws Exception {
String managerSource = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java")).replace("\r\n", "\n");
String listenerSource = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/PaperWorldReplacementEntryListener.java")).replace("\r\n", "\n");
String preparation = method(managerSource, "private void prepareOverworldEntry(World world)");
String persistence = method(managerSource, "public void onWorldSave(WorldSaveEvent event)");
String retirement = method(
managerSource,
"private synchronized void retireOverworldEntryIfCompleteAsync(UUID transactionId)"
);
String listener = method(
listenerSource,
"public void onAsyncPlayerSpawnLocation(AsyncPlayerSpawnLocationEvent event)"
);
String generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
assertBefore(preparation, "overworldSpawnPersistence = persistence",
"targetFuture.complete(safeEntry.clone())");
assertTrue(persistence.contains("event.getWorld() != replacementWorld"));
assertTrue(persistence.contains("persistence.complete(null)"));
assertTrue(retirement.contains("!current.pendingPlayers().isEmpty()"));
assertTrue(retirement.contains("!persistence.isDone()"));
assertTrue(retirement.contains("persistence.isCompletedExceptionally()"));
assertTrue(listener.contains("event.isNewPlayer()"));
assertTrue(generatorSource.contains("world.getHighestBlockYAt(initialSpawn) + 1"));
}
@Test
public void loginCollisionInspectionDoesNotGenerateMissingReplacementChunks() throws Exception {
String managerSource = Files.readString(Path.of(
"src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java")).replace("\r\n", "\n");
String inspection = method(managerSource, "private CompletableFuture<Boolean> inspectLoginCollision(Location location)");
assertTrue(inspection.contains("requestChunkAsync(world, chunkX, chunkZ, false, true)"));
assertBefore(inspection, "chunk == null", "inspectLoadedLoginCollision(requiredLocation)");
}
private static PendingWorldReplacementManager.PublishedWorldRuntimeState runtimeState(
WorldSlotKey worldKey,
long seed,
@@ -281,40 +160,4 @@ public class PendingWorldReplacementThreadAffinityTest {
Phase.PUBLISHED
);
}
private static void assertNoBukkitRuntimeAccess(String source) {
assertFalse(source.contains("WorldIdentity."));
assertFalse(source.contains("IrisToolbelt."));
assertFalse(source.contains("getSeed()"));
assertFalse(source.contains("getEnvironment()"));
assertFalse(source.contains("Bukkit."));
}
private static void assertBefore(String source, String first, String second) {
int firstIndex = source.indexOf(first);
int secondIndex = source.indexOf(second);
assertTrue("Missing source contract token: " + first, firstIndex >= 0);
assertTrue("Missing source contract token: " + second, secondIndex >= 0);
assertTrue(first + " must occur before " + second, firstIndex < secondIndex);
}
private static String method(String source, String signature) {
int start = source.indexOf(signature);
assertTrue("Missing source contract signature: " + signature, start >= 0);
int openBrace = source.indexOf('{', start);
assertTrue("Missing source contract method body: " + signature, openBrace >= 0);
int depth = 0;
for (int index = openBrace; index < source.length(); index++) {
char current = source.charAt(index);
if (current == '{') {
depth++;
} else if (current == '}') {
depth--;
if (depth == 0) {
return source.substring(start, index + 1);
}
}
}
throw new IllegalArgumentException("Unclosed source contract method: " + signature);
}
}
@@ -1,26 +0,0 @@
package art.arcane.iris.core.commands;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class CommandFindRiverContractTest {
@Test
public void riverLookupMergesRecordedAndEligibleActiveFeatures() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandFindSource")));
int methodStart = source.indexOf("public void river(");
int methodEnd = source.indexOf("public void structure(", methodStart);
String method = source.substring(methodStart, methodEnd);
assertTrue(method.contains("GenerationSemanticQueries.nearestRiver("));
assertTrue(method.contains("runtime == null"));
assertTrue(method.contains("feature.y()"));
assertFalse(method.contains("runtime.nearestFeature("));
assertFalse(method.contains("feature.y() + activeEngine.getDimension().getMinHeight()"));
}
}
@@ -1,27 +0,0 @@
package art.arcane.iris.core.commands;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class CommandFindStructureHistoryContractTest {
@Test
public void admitsRetainedStructuresBeforeActiveOnlyRejectionsAndUsesSemanticSearch() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandFindSource")));
int structureStart = source.indexOf("public void structure(");
int retainedAdmission = source.indexOf("GenerationFindCatalog.hasRetainedStructurePlacement(e, structureKey)", structureStart);
int unknownRejection = source.indexOf("if (route == StructureLookupRoute.UNKNOWN)", structureStart);
assertTrue(retainedAdmission > structureStart && retainedAdmission < unknownRejection);
int locateStart = source.indexOf("private void locateIrisStructure(");
int locateEnd = source.indexOf("public void object(", locateStart);
String locate = source.substring(locateStart, locateEnd);
assertTrue(locate.contains("GenerationSemanticQueries.nearestStructure("));
assertFalse(locate.contains("IrisStructureLocator.locate("));
}
}
@@ -1,35 +0,0 @@
package art.arcane.iris.core.commands;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CommandIrisFoliaCreateContractTest {
@Test
public void ordinaryFoliaCreateUsesTheSharedRuntimeCreationPath() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.commandIrisSource")));
String create = source.substring(
source.indexOf(" public void create("),
source.indexOf(" @Director(", source.indexOf(" public void create("))
);
assertTrue(create.contains("IrisToolbelt.createWorld()"));
assertTrue(create.contains(".studio(false)"));
assertTrue(create.contains(".create();"));
assertFalse(create.contains("J.isFolia()"));
assertFalse(create.contains("ServerConfigurator.restart("));
}
@Test
public void obsoleteFoliaStagingSurfaceIsRemoved() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.commandIrisSource")));
assertFalse(source.contains("stageFoliaWorldCreation"));
assertFalse(source.contains("writeCurrentPaperWorldData"));
assertFalse(source.contains("COMMAND_IRIS_RUNTIME_WORLD_CREATION_IS_DISABLED_ON_FOLIA"));
}
}
@@ -7,17 +7,13 @@ import org.junit.Test;
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CommandIrisLoadWorldContractTest {
@Test
public void commandUsesTypedAsyncReconciliationBeforeReportingSuccess() throws Exception {
public void commandUsesTypedAsyncReconciliation() throws Exception {
Method reconciliation = BukkitWorldReconciler.class.getDeclaredMethod(
"loadWorld",
File.class,
@@ -27,21 +23,5 @@ public class CommandIrisLoadWorldContractTest {
Parameter worldParameter = commandMethod.getParameters()[0];
assertEquals(CommandIris.ManagedWorldNameHandler.class,
worldParameter.getAnnotation(Param.class).customHandler());
String source = Files.readString(Path.of(System.getProperty("iris.commandIrisSource")));
String command = source.substring(
source.indexOf("public void loadWorld("),
source.indexOf("private void reportLoadWorldResult("));
String reporter = source.substring(
source.indexOf("private void reportLoadWorldResult("),
source.indexOf("@Director(description = \"Evacuate an iris world\""));
assertTrue(command.contains("IrisWorldStorage.managedKeyFromName(world)"));
assertTrue(command.contains(".loadWorld(BUKKIT_YML, worldKey.toString())"));
assertTrue(command.contains(".whenComplete((result, failure) ->"));
assertFalse(command.contains("checkForBukkitWorlds"));
assertFalse(command.contains("COMMAND_IRIS_LOADED_SUCCESSFULLY"));
assertTrue(reporter.contains("if (result.succeeded())"));
assertTrue(reporter.contains("COMMAND_IRIS_LOADED_SUCCESSFULLY"));
}
}
@@ -1,26 +0,0 @@
package art.arcane.iris.core.commands;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertTrue;
public class CommandIrisUnloadContractTest {
@Test
public void unloadAwaitsEvacuationAndHasATerminalLifecycleTimeout() throws Exception {
String source = Files.readString(Path.of(System.getProperty("iris.commandIrisSource")));
String command = source.substring(
source.indexOf("public void unloadWorld("),
source.indexOf("private void reportUnloadResult("));
assertTrue(command.contains("IrisToolbelt.evacuateAsync(world)"));
assertTrue(command.indexOf("IrisToolbelt.evacuateAsync(world)")
< command.indexOf("WorldLifecycleService.get().unloadAsync(world, true)"));
assertTrue(command.contains("guardUnloadCompletion(sequence, terminalTimeout, world.getName())"));
assertTrue(command.contains("ServerConfigurator.restart(\"World unload timed out"));
assertTrue(command.indexOf("ServerConfigurator.restart(\"World unload timed out")
< command.indexOf("guarded.completeExceptionally(timeout)"));
}
}
@@ -5,9 +5,6 @@ import art.arcane.iris.engine.object.IrisNativeStructureDecision;
import art.arcane.iris.engine.object.NativeStructureGenerationStatus;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
@@ -16,44 +13,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class IrisStructureLocateCommandContractTest {
@Test
public void findReportsDensityLimitAndUsesExactLocatedOrigin() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandFindSource")));
assertTrue(source.contains("LocateStatus.SEARCH_LIMIT_REACHED"));
assertTrue(source.contains("the density search safety limit was reached"));
assertTrue(source.contains("result.originX(), result.baseY(), result.originZ()"));
assertFalse(source.contains("at[0] + 8"));
assertFalse(source.contains("at[2] + 8"));
}
@Test
public void findRoutesOnlyActiveWorldStructures() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandFindSource")));
int methodStart = source.indexOf("public void structure(");
int methodEnd = source.indexOf("static StructureLookupRoute selectStructureLookupRoute", methodStart);
String method = source.substring(methodStart, methodEnd);
int nativeResolution = method.indexOf("resolveNativeStructure(structureKey)");
int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(", nativeResolution);
int nativeLocatableCheck = method.indexOf(
"IrisStructureLocator.hasLocatableNativePlacement(e, structureKey)", policyResolution);
int editableLocatableCheck = method.indexOf(
"IrisStructureLocator.hasLocatableEditablePlacement(e, structureKey)", nativeLocatableCheck);
int worldGenerationCheck = method.indexOf("targetWorld.canGenerateStructures()", editableLocatableCheck);
int routeResolution = method.indexOf("selectStructureLookupRoute(", editableLocatableCheck);
int nativeLocate = method.indexOf("targetWorld.locateNearestStructure(", routeResolution);
assertTrue(nativeResolution >= 0);
assertTrue(policyResolution > nativeResolution);
assertTrue(nativeLocatableCheck > policyResolution);
assertTrue(editableLocatableCheck > nativeLocatableCheck);
assertTrue(worldGenerationCheck > editableLocatableCheck);
assertTrue(routeResolution > editableLocatableCheck);
assertTrue(nativeLocate > routeResolution);
assertFalse(method.contains("IrisStructureLocator.isPlaced(e, structureKey)"));
assertFalse(method.contains("NativeStructureLocateCapability"));
}
@Test
public void findRejectsUnregisteredNativeAndDormantPlacements() {
assertEquals(CommandFind.StructureLookupRoute.UNKNOWN,
@@ -193,24 +152,6 @@ public class IrisStructureLocateCommandContractTest {
"pack:editable", Set.of(), Set.of(), true));
}
@Test
public void unregisteredDiagnosticPrintsDetailsOnlyToConsole() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandFindSource")));
int methodStart = source.indexOf("public void unregistered()");
int methodEnd = source.indexOf("private static StructureExclusionReport", methodStart);
String method = source.substring(methodStart, methodEnd);
assertTrue(methodStart >= 0);
assertTrue(source.contains("Iris.info(\"[%s] %s%s: %s\""));
assertTrue(method.contains("non-generating structure candidate(s) and their reasons to the server console"));
assertTrue(method.contains("no chunks were searched"));
assertTrue(method.indexOf("DatapackIngestService.installed()") > method.indexOf("J.a(() ->"));
assertTrue(source.contains("DatapackIngestService.configuredImports(engine.getDimension())"));
assertTrue(source.contains("snapshot.configuredImportUrls().contains(importUrl)"));
assertTrue(source.contains("engine.getData().getStructureLoader().getPossibleKeys()"));
assertFalse(method.contains("commandSender.sendMessage(exclusion"));
}
@Test
public void findNativePolicyMessagesMatchModdedDiagnostics() {
assertEquals(
@@ -227,72 +168,6 @@ public class IrisStructureLocateCommandContractTest {
"minecraft:stronghold", NativeStructureGenerationStatus.GENERATE_NATIVE));
}
@Test
public void structureVerifyReportsDensityLimitAndUsesExactLocatedOrigin() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
assertTrue(source.contains("[iris-search-limit]"));
assertTrue(source.contains("density searches safety-limited"));
assertTrue(source.contains("result.originX() + \",\" + result.baseY() + \",\" + result.originZ()"));
assertFalse(source.contains("at[0] + 8"));
assertFalse(source.contains("at[2] + 8"));
}
@Test
public void bulkStructureImportRestrictsCaptureWithoutChangingStandaloneCapture() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
int importStart = source.indexOf("public void importAll(");
int importEnd = source.indexOf("@Director(name = \"capture\"", importStart);
int captureStart = source.indexOf("public void capture(", importEnd);
int captureEnd = source.indexOf("@Director(description = \"Verify", captureStart);
assertTrue(importStart >= 0);
assertTrue(importEnd > importStart);
assertTrue(captureStart > importEnd);
assertTrue(captureEnd > captureStart);
String importMethod = source.substring(importStart, importEnd);
String captureMethod = source.substring(captureStart, captureEnd);
assertTrue(importMethod.contains("StructureCaptureImporter.importStructures("));
assertTrue(importMethod.contains("jigsaws.captureCandidates()"));
assertFalse(importMethod.contains("StructureCaptureImporter.importAllStructures("));
assertTrue(captureMethod.contains("StructureCaptureImporter.importAllStructures("));
}
@Test
public void structurePlaceSeparatesPackContentFromTargetWorldEngine() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
int methodStart = source.indexOf("public void place(");
assertTrue(methodStart >= 0);
String method = source.substring(methodStart);
assertTrue(method.contains("IrisData data = dimension.getLoader()"));
assertTrue(method.contains("PlatformChunkGenerator targetGenerator = IrisToolbelt.access(targetWorld)"));
assertTrue(method.contains("CommandObject.createPlacer(targetWorld, future, targetEngine)"));
assertTrue(method.contains("if (blockChanges == 0)"));
assertTrue(method.contains("COMMAND_STRUCTURE_PLACEMENT_CHANGED_NO_BLOCKS"));
Path structureSource = Path.of(System.getProperty("iris.commandStructureSource"));
String objectSource = Files.readString(structureSource.resolveSibling("CommandObject.java"));
assertTrue(objectSource.contains("futureBlockChanges.putIfAbsent(block, block.getBlockData())"));
assertFalse(method.contains("data.getEngine()"));
}
@Test
public void structureVerifyPartitionsPolicyBeforeNativeReachability() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
int methodStart = source.indexOf("private void runVerification(");
int methodEnd = source.indexOf("private void sendVerificationMessages(", methodStart);
String method = source.substring(methodStart, methodEnd);
int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, keyName, false)");
int nativeRequirement = method.indexOf(
"requiresNativeReachability |= !IrisStructureLocator.isPlaced", policyResolution);
int reachabilityGuard = method.indexOf("if (requiresNativeReachability)", nativeRequirement);
int reachabilityLookup = method.indexOf("StructureReachability.reachableKeys(engine)", reachabilityGuard);
assertTrue(policyResolution >= 0);
assertTrue(nativeRequirement > policyResolution);
assertTrue(reachabilityGuard > nativeRequirement);
assertTrue(reachabilityLookup > reachabilityGuard);
}
private static IrisNativeStructureDecision decision(NativeStructureGenerationStatus status) {
return new IrisNativeStructureDecision(
status, 0, null, false, null, null);
@@ -212,19 +212,6 @@ public class IrisPapiExpansionTest {
assertTrue(expansion.persist());
}
@Test
public void thePlaceholderPathNeverTouchesTheEngineOrAPluginStatic() throws Exception {
for (String file : List.of("IrisPapiExpansion.java", "IrisPapiState.java", "IrisPapiWorldView.java")) {
String source = Files.readString(Path.of("src/main/java/art/arcane/iris/core/link/" + file)).replace("\r\n", "\n");
assertFalse(file + " must not import the engine", source.contains("art.arcane.iris.engine."));
assertFalse(file + " must not reach into the toolbelt", source.contains("IrisToolbelt"));
assertFalse(file + " must not read the plugin static", source.contains("Iris.instance"));
assertFalse(file + " must not derive metadata from the description", source.contains("getDescription()"));
assertFalse(file + " must not take a lock", source.contains("synchronized"));
}
}
@Test
public void theReadmeDocumentsEveryPublishedKeyAndEveryRetiredOne() throws Exception {
String readme = Files.readString(Path.of(System.getProperty("iris.readmeSource")));
@@ -1,93 +0,0 @@
package art.arcane.iris.core.runtime;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BukkitEngineLifecycleContractTest {
@Test
public void closeFutureIsPublishedBeforeCloseWorkIsScheduled() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
String closeAsync = method(source, "public CompletableFuture<Void> closeAsync()");
assertBefore(closeAsync, "closeFuture.compareAndSet(null, future)", "withExclusiveControlFuture(");
assertTrue(closeAsync.contains("while (!closeFuture.compareAndSet(null, future))"));
assertTrue(closeAsync.contains("return existing;"));
assertTrue(closeAsync.contains("operation.whenComplete("));
assertFalse(closeAsync.contains("!existing.isDone()"));
String exclusiveFuture = method(source, "public CompletableFuture<Void> withExclusiveControlFuture(Runnable r)");
assertTrue(exclusiveFuture.contains("J.a(() -> completeExclusiveControlFuture(loadLock, r, future))"));
String exclusiveCompletion = method(source, "static void completeExclusiveControlFuture(");
assertBefore(exclusiveCompletion, "activeGate.releaseExclusive();", "outward.complete(null);");
assertBefore(exclusiveCompletion, "activeGate.releaseExclusive();", "outward.completeExceptionally(failure);");
String baseHeight = method(source, "public int getBaseHeight(");
assertTrue(baseHeight.contains("currentEngine.acquireGenerationLease(\"bukkit_base_height\")"));
assertTrue(baseHeight.contains("IrisContext.open(currentEngine, lease.sessionId(), null)"));
assertTrue(baseHeight.contains("catch (GenerationSessionException | IOException e)"));
String generation = method(source, "public void generateNoise(");
assertTrue(generation.contains("throw new IllegalStateException"));
assertTrue(generation.contains("engine.acquireGenerationLease(\"bukkit_terrain_stage\")"));
assertTrue(generation.contains("IrisContext.open(engine, lease.sessionId(), null)"));
assertBefore(generation, "engine.acquireGenerationLease(\"bukkit_terrain_stage\")", "blocks.apply()");
assertFalse(generation.contains("RED_GLAZED_TERRACOTTA"));
}
@Test
public void targetedPregeneratorShutdownChecksWorldIdentity() throws IOException {
String jobSource = Files.readString(Path.of(System.getProperty("iris.pregeneratorJobSource")));
String targetedShutdown = method(jobSource,
"public static boolean shutdownInstanceForWorld(String worldIdentity)");
assertBefore(targetedShutdown, "inst.targetsWorldIdentity(worldIdentity)",
"shutdownAndWait(inst, WORLD_SHUTDOWN_TIMEOUT_MILLIS)");
String waitedShutdown = method(jobSource,
"private static boolean shutdownAndWait(PregeneratorJob inst, long timeoutMs)");
assertBefore(waitedShutdown, "inst.requestStop()", "inst.worker.join(");
assertBefore(waitedShutdown, "inst.worker.join(", "finishShutdown(inst, timeoutMs)");
String finishedShutdown = method(jobSource,
"private static boolean finishShutdown(PregeneratorJob inst, long timeoutMs)");
assertBefore(finishedShutdown, "inst.worker.isAlive()", "instance.compareAndSet(inst, null)");
String hooksSource = Files.readString(Path.of(System.getProperty("iris.bukkitEnginePlatformHooksSource")));
String hookShutdown = method(hooksSource, "public void shutdownPregenerator(Engine engine)");
assertTrue(hookShutdown.contains("PregeneratorJob.shutdownInstanceForWorld(world.identity());"));
assertFalse(hookShutdown.contains("PregeneratorJob.shutdownInstance();"));
}
private static void assertBefore(String source, String first, String second) {
int firstIndex = source.indexOf(first);
int secondIndex = source.indexOf(second);
assertTrue("Missing source contract token: " + first, firstIndex >= 0);
assertTrue("Missing source contract token: " + second, secondIndex >= 0);
assertTrue(first + " must occur before " + second, firstIndex < secondIndex);
}
private static String method(String source, String signature) {
int start = source.indexOf(signature);
assertTrue("Missing source contract signature: " + signature, start >= 0);
int openBrace = source.indexOf('{', start);
assertTrue("Missing source contract method body: " + signature, openBrace >= 0);
int depth = 0;
for (int index = openBrace; index < source.length(); index++) {
char current = source.charAt(index);
if (current == '{') {
depth++;
} else if (current == '}') {
depth--;
if (depth == 0) {
return source.substring(start, index + 1);
}
}
}
throw new IllegalArgumentException("Unclosed source contract method: " + signature);
}
}
@@ -6,9 +6,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.world.WorldUnloadEvent;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertEquals;
@@ -45,80 +43,10 @@ public class IrisEngineLifecycleContractTest {
assertFalse(first.conflictsWith(distinct));
}
@Test
public void registrationRetryWaitsAsynchronouslyForClose() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.engineSvcSource")));
String add = method(source, "private void add(World world)");
String remove = method(source, "private boolean remove(World world, CompletionStage<Boolean> unloadBoundary)");
String completeClose = method(source, "private void completeClose(");
String retry = method(source, "private void retryRegistrationAfterClose(");
String invokeClose = method(source, "private CompletableFuture<Void> invokeGeneratorClose()");
assertBefore(add, "findClosingGenerator(registrationIdentity)", "new Registered(");
assertBefore(remove, "registered.close()", "reserveClose(registered)");
assertBefore(remove, "reserveClose(registered)", "deferCloseUntilWorldUnload(");
assertBefore(completeClose, "if (failure == null)", "closingGenerators.remove(closing)");
assertBefore(completeClose, "closingGenerators.remove(closing)", "closing.completion().complete(null)");
assertBefore(completeClose, "} else {", "closing.completion().completeExceptionally(failure)");
assertTrue(retry.contains("completion.whenComplete("));
assertTrue(retry.contains("J.s(() -> add(world), 1);"));
assertBefore(retry, "if (failure != null)", "J.s(() -> add(world), 1);");
assertFalse(retry.contains("completion.get("));
assertFalse(retry.contains("completion.join("));
assertTrue(invokeClose.contains("CompletableFuture.failedFuture("));
assertTrue(invokeClose.contains("future.whenComplete("));
}
@Test
public void worldUnloadDefersGeneratorCloseUntilTheRawBoundaryCompletesTrue() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.engineSvcSource")));
String handler = method(source, "public void onWorldUnload(WorldUnloadEvent event)");
String remove = method(source, "private boolean remove(World world, CompletionStage<Boolean> unloadBoundary)");
String defer = method(source, "private void deferCloseUntilWorldUnload(");
assertBefore(handler, "WorldUnloadBoundaryRegistry.claim(", "remove(world, unloadBoundary)");
assertBefore(remove, "registered.close()", "deferCloseUntilWorldUnload(");
assertFalse(remove.contains("startClose(registered, closing)"));
assertTrue(defer.contains("J.sfut(() -> startClose(registered, closing), 1)"));
assertTrue(defer.contains("unloadBoundary.whenComplete("));
String managedBoundary = defer.substring(defer.indexOf("unloadBoundary.whenComplete("));
assertBefore(managedBoundary, "failure == null && Boolean.TRUE.equals(unloaded)",
"startClose(registered, closing)");
assertBefore(managedBoundary, "startClose(registered, closing)", "abandonClose(world, closing)");
}
private static void assertMonitorUnloadHandler(Method method) {
EventHandler eventHandler = method.getAnnotation(EventHandler.class);
assertNotNull(eventHandler);
assertEquals(EventPriority.MONITOR, eventHandler.priority());
assertTrue(eventHandler.ignoreCancelled());
}
private static void assertBefore(String source, String first, String second) {
int firstIndex = source.indexOf(first);
int secondIndex = source.indexOf(second);
assertTrue("Missing source contract token: " + first, firstIndex >= 0);
assertTrue("Missing source contract token: " + second, secondIndex >= 0);
assertTrue(first + " must occur before " + second, firstIndex < secondIndex);
}
private static String method(String source, String signature) {
int start = source.indexOf(signature);
assertTrue("Missing source contract signature: " + signature, start >= 0);
int openBrace = source.indexOf('{', start);
assertTrue("Missing source contract method body: " + signature, openBrace >= 0);
int depth = 0;
for (int index = openBrace; index < source.length(); index++) {
char current = source.charAt(index);
if (current == '{') {
depth++;
} else if (current == '}') {
depth--;
if (depth == 0) {
return source.substring(start, index + 1);
}
}
}
throw new IllegalArgumentException("Unclosed source contract method: " + signature);
}
}
@@ -13,9 +13,6 @@ import art.arcane.iris.util.common.plugin.IrisService;
import org.bukkit.World;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
@@ -61,18 +58,6 @@ public class IrisTerrainSVCTest {
assertTrue(service.regionName(null, 0, 0).isEmpty());
}
@Test
public void theDisplayNameAccessorsReadNamesRatherThanLoadKeys() throws IOException {
String source = Files.readString(Path.of(System.getProperty("iris.terrainSvcSource")));
assertTrue("surfaceBiomeName must read the biome display name",
source.contains("return name(engine.getSurfaceBiome(blockX, blockZ));"));
assertTrue("the biome name helper must read getName()",
source.contains("String name = biome == null ? null : biome.getName();"));
assertTrue("regionName must read the region display name",
source.contains("String name = region == null ? null : region.getName();"));
}
@Test
public void theServiceExposesDisplayNamesAlongsideLoadKeys() throws NoSuchMethodException {
assertEquals(Optional.class,