Add engine-owned pack runtime scope and release probe

- Give each generation runtime a PackRuntime that pack-derived runtime objects will live in
- Give IrisData a standalone PackRuntime for engine-less tools, replaced on dump
- Add RuntimeTable for identity-keyed lazy runtime objects
- Add ThreadSlots for bounded per-thread values owned by a runtime object
- Add a real-engine probe that expects a closed engine to be collectable
- Keep scratch and static holders pending until they are reviewed
This commit is contained in:
piexel committed 2026-11-26 18:03:18 +01:00
1 parent beb665d1b7
commit 43cc702a9e
20 files changed
+624 -32

No files matched your search

@@ -85,6 +85,9 @@ import java.util.stream.Collectors;
public interface Engine extends DataProvider, Fallible, BlockUpdater, Renderer, Hotloadable {
IrisComplex getComplex();
/** The runtime objects this engine derived from its pack, or null while no runtime is active. */
PackRuntime getPackRuntime();
default BiomeEnvironment getBiomeEnvironment(int x, int y, int z) {
return new BiomeEnvironment(0L, getBiome(x, y, z), getRegion(x, y, z), getDimension(), getData());
}
@@ -76,6 +76,7 @@ final class EngineHotloader {
engine.sealForTransition("complex hotload", false);
engine.prepareRuntimeHotload();
assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
previousGeneration.target(),
previousGeneration.mantleStorageDirectory(),
@@ -94,6 +95,7 @@ final class EngineHotloader {
GenerationRuntime nextGeneration = previousGeneration.withComplex(
assembly.cacheId,
assembly.complex,
assembly.packRuntime,
assembly.upperContext,
assembly.dimensionStackContext,
biomeMaxes);
@@ -88,6 +88,7 @@ final class EngineRuntimeBuilder {
PreparedHydrologyCacheIdentity cacheIdentity
) {
RuntimeAssembly assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
runtimeTarget,
mantleStorageDirectory,
@@ -167,6 +168,7 @@ final class EngineRuntimeBuilder {
TransitionGenerationPlan transitionPlan
) {
RuntimeAssembly assembly = new RuntimeAssembly(
engine,
RuntimeAssembly.nextRuntimeId(),
runtimeTarget,
mantleStorageDirectory,
@@ -421,6 +423,7 @@ final class EngineRuntimeBuilder {
final GenerationKernelRegistry.RuntimeKernel runtimeKernel;
final SeedManager seedManager;
final TransitionGenerationPlan transitionPlan;
final PackRuntime packRuntime;
static int nextRuntimeId() {
return RUNTIME_IDS.incrementAndGet();
@@ -435,8 +438,9 @@ final class EngineRuntimeBuilder {
CompletableFuture<Long> hash32;
boolean ownsMantle;
RuntimeAssembly(int cacheId, EngineTarget target) {
RuntimeAssembly(Engine engine, int cacheId, EngineTarget target) {
this(
engine,
cacheId,
target,
null,
@@ -444,8 +448,9 @@ final class EngineRuntimeBuilder {
null);
}
RuntimeAssembly(int cacheId, EngineTarget target, Path mantleStorageDirectory) {
RuntimeAssembly(Engine engine, int cacheId, EngineTarget target, Path mantleStorageDirectory) {
this(
engine,
cacheId,
target,
mantleStorageDirectory,
@@ -454,6 +459,7 @@ final class EngineRuntimeBuilder {
}
RuntimeAssembly(
Engine engine,
int cacheId,
EngineTarget target,
Path mantleStorageDirectory,
@@ -469,6 +475,7 @@ final class EngineRuntimeBuilder {
this.seedManager = this.runtimeKernel.createSeedManager(target.getWorld().getRawWorldSeed());
this.kernelVersion = this.runtimeKernel.version();
this.transitionPlan = transitionPlan;
this.packRuntime = PackRuntime.forEngine(engine, target.getData());
}
GenerationRuntime freezeGeneration(BiomeMaxes biomeMaxes) {
@@ -485,6 +492,7 @@ final class EngineRuntimeBuilder {
seedManager,
transitionPlan,
complex,
packRuntime,
upperContext,
dimensionStackContext,
mode,
@@ -38,6 +38,7 @@ record GenerationRuntime(
SeedManager seedManager,
TransitionGenerationPlan transitionPlan,
IrisComplex complex,
PackRuntime packRuntime,
UpperDimensionContext upperContext,
DimensionStackContext dimensionStackContext,
EngineMode mode,
@@ -57,6 +58,7 @@ record GenerationRuntime(
throw new IllegalArgumentException("Generation kernel version does not match its executable runtime.");
}
Objects.requireNonNull(complex, "generation complex");
Objects.requireNonNull(packRuntime, "generation pack runtime");
Objects.requireNonNull(mode, "generation mode");
Objects.requireNonNull(mantle, "generation mantle");
mantleStorageDirectory = IrisEngineMantle.normalizeStorageDirectory(mantleStorageDirectory);
@@ -70,6 +72,7 @@ record GenerationRuntime(
GenerationRuntime withComplex(
int nextCacheId,
IrisComplex nextComplex,
PackRuntime nextPackRuntime,
UpperDimensionContext nextUpperContext,
DimensionStackContext nextDimensionStackContext,
BiomeMaxes nextBiomeMaxes
@@ -84,6 +87,7 @@ record GenerationRuntime(
seedManager,
transitionPlan,
nextComplex,
nextPackRuntime,
nextUpperContext,
nextDimensionStackContext,
mode,
@@ -1424,6 +1424,17 @@ public class IrisEngine implements Engine {
return complexIn(threadState.current());
}
@Override
public PackRuntime getPackRuntime() {
EngineThreadState.Frame frame = threadState.current();
RuntimeAssembly assembly = frame == null ? null : frame.assembly;
if (assembly != null) {
return assembly.packRuntime;
}
GenerationRuntime current = selectedGenerationRuntime(frame);
return current == null ? null : current.packRuntime();
}
private IrisComplex complexIn(EngineThreadState.Frame frame) {
RuntimeAssembly assembly = frame == null ? null : frame.assembly;
if (assembly != null && assembly.complex != null) {
@@ -0,0 +1,67 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import art.arcane.iris.pack.loading.IrisData;
import java.util.Objects;
/**
* The runtime objects one owner derives from pack objects: seeded generators, samplers and profiles. Pack objects are
* read-only configuration, so everything built for a seed, an engine or a world lives here and dies with the owner.
* An engine owns one per generation runtime; engine-less tools use the scope their {@link IrisData} owns.
*/
public final class PackRuntime {
private final Engine engine;
private final IrisData data;
private PackRuntime(Engine engine, IrisData data) {
this.engine = engine;
this.data = Objects.requireNonNull(data, "pack data");
}
static PackRuntime forEngine(Engine engine, IrisData data) {
return new PackRuntime(Objects.requireNonNull(engine, "engine"), data);
}
public static PackRuntime standalone(IrisData data) {
return new PackRuntime(null, data);
}
/**
* The runtime scope for work on this pack: the engine's while one is generating, otherwise the scope the pack
* data owns. Resolve it once per chunk or column and pass it down.
*/
public static PackRuntime of(Engine engine, IrisData data) {
PackRuntime engineRuntime = engine == null ? null : engine.getPackRuntime();
if (engineRuntime != null) {
return engineRuntime;
}
return Objects.requireNonNull(data, "pack data").standalonePackRuntime();
}
/** The owning engine, or null for an engine-less scope. */
public Engine engine() {
return engine;
}
public IrisData data() {
return data;
}
}
@@ -0,0 +1,68 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* Runtime objects of one kind keyed by the identity of the pack object they were built from. Pack types compare by
* value, so two equal configurations still get their own runtime object. A builder may resolve other runtime objects
* from the same table, so entries are built outside the map and the first one published wins.
*/
public final class RuntimeTable<C, R> {
private final ConcurrentHashMap<Identity, R> entries = new ConcurrentHashMap<>();
private final Function<C, R> builder;
public RuntimeTable(Function<C, R> builder) {
this.builder = Objects.requireNonNull(builder, "runtime builder");
}
public R get(C config) {
Identity key = new Identity(Objects.requireNonNull(config, "pack object"));
R existing = entries.get(key);
if (existing != null) {
return existing;
}
R built = Objects.requireNonNull(builder.apply(config), "runtime object");
R raced = entries.putIfAbsent(key, built);
return raced == null ? built : raced;
}
private static final class Identity {
private final Object referent;
private final int hash;
private Identity(Object referent) {
this.referent = referent;
this.hash = System.identityHashCode(referent);
}
@Override
public boolean equals(Object other) {
return other instanceof Identity identity && identity.referent == referent;
}
@Override
public int hashCode() {
return hash;
}
}
}
@@ -0,0 +1,71 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Supplier;
/**
* Per-thread values owned by the object that holds this table, typically an engine-owned runtime. Unlike a
* ThreadLocal, the values live here and not in the worker threads, so they become unreachable with their owner even
* while the pooled workers that filled them stay alive. The table has a fixed size: a slot whose thread has died is
* reused, and when every probed slot belongs to a live thread the first one is taken over, which only costs that
* thread its memo.
*/
public final class ThreadSlots<T> {
private static final int SLOT_COUNT = 256;
private static final int SLOT_MASK = SLOT_COUNT - 1;
private static final int PROBE_LIMIT = 8;
private final AtomicReferenceArray<Slot<T>> slots = new AtomicReferenceArray<>(SLOT_COUNT);
private final Supplier<T> factory;
public ThreadSlots(Supplier<T> factory) {
this.factory = Objects.requireNonNull(factory, "thread value factory");
}
public T get() {
Thread thread = Thread.currentThread();
int home = (int) thread.threadId() & SLOT_MASK;
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
Slot<T> slot = slots.getPlain((home + probe) & SLOT_MASK);
if (slot != null && slot.owner == thread) {
return slot.value;
}
}
return claim(thread, home);
}
private T claim(Thread thread, int home) {
Slot<T> created = new Slot<>(thread, factory.get());
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
int index = (home + probe) & SLOT_MASK;
Slot<T> current = slots.get(index);
if ((current == null || !current.owner.isAlive()) && slots.compareAndSet(index, current, created)) {
return created.value;
}
}
slots.set(home, created);
return created.value;
}
private record Slot<T>(Thread owner, T value) {
}
}
@@ -36,6 +36,8 @@ import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.pack.PackDirectoryResolver;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
import art.arcane.iris.world.loot.IrisBlockDrops;
@@ -168,6 +170,10 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
private transient volatile Engine soleEngine;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
private transient volatile PackRuntime standalonePackRuntime;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile Set<String> blockDropMaterials;
private IrisData(File dataFolder) {
@@ -656,6 +662,23 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
dataLoaders.remove(dataFolder, this);
}
/**
* The runtime scope for tools that work on this pack without an engine, such as studio previews and validators.
* It is replaced when the pack objects are reloaded and dropped when this data closes.
*/
public PackRuntime standalonePackRuntime() {
PackRuntime current = standalonePackRuntime;
if (current != null) {
return current;
}
synchronized (this) {
if (standalonePackRuntime == null) {
standalonePackRuntime = PackRuntime.standalone(this);
}
return standalonePackRuntime;
}
}
public IrisData copy() {
return IrisData.get(dataFolder);
}
@@ -774,6 +797,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
public void dump() {
blockDropMaterials = null;
standalonePackRuntime = null;
StructureGraphCatalog.invalidate(this);
IrisObjectScale.invalidate(this);
for (ResourceLoader<?> i : loaders.values()) {
@@ -887,7 +887,7 @@ public class EngineShutdownDrainTest {
when(generation.runtimeKernel()).thenReturn(kernel);
GenerationRuntime nextGeneration = generation(target, mantle);
when(nextGeneration.complex()).thenReturn(replacement);
when(generation.withComplex(anyInt(), same(replacement), isNull(), isNull(), any()))
when(generation.withComplex(anyInt(), same(replacement), any(), isNull(), isNull(), any()))
.thenReturn(nextGeneration);
EngineRuntimeBuilder builder = spy(new EngineRuntimeBuilder(engine));
doReturn(new GenerationRuntime.BiomeMaxes(0D, 0D, 0D)).when(builder).computeBiomeMaxes();
@@ -219,7 +219,7 @@ public class IrisCarveWallPaletteScopeTest {
doReturn(engine.getWorld()).when(assemblyTarget).getWorld();
doReturn(assemblyData).when(assemblyTarget).getData();
doReturn(mock(IrisDimension.class)).when(assemblyTarget).getDimension();
assembly = new EngineRuntimeBuilder.RuntimeAssembly(19, assemblyTarget);
assembly = new EngineRuntimeBuilder.RuntimeAssembly(engine, 19, assemblyTarget);
assembly.complex = assemblyComplex;
assembly.mantle = engineMantle;
IrisBiome biome = mock(IrisBiome.class);
@@ -816,6 +816,7 @@ public class IrisEngineGenerationRuntimeScopeTest {
RuntimeFixture active = runtime(1, 1D, 1D, 1D);
IrisEngine engine = engine(active.runtime, mock(EngineEffects.class), mock(EngineWorldManager.class));
EngineRuntimeBuilder.RuntimeAssembly assembly = new EngineRuntimeBuilder.RuntimeAssembly(
engine,
2,
active.target,
Path.of("build", "test-mantles", "assembly"));
@@ -1073,6 +1074,7 @@ public class IrisEngineGenerationRuntimeScopeTest {
mock(SeedManager.class),
null,
complex,
PackRuntime.standalone(data),
upperContext,
dimensionStackContext,
mode,
@@ -0,0 +1,59 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
public class RuntimeTableTest {
@Test
public void buildsOncePerPackObject() {
AtomicInteger builds = new AtomicInteger();
RuntimeTable<List<String>, Object> table = new RuntimeTable<>(config -> {
builds.incrementAndGet();
return new Object();
});
List<String> config = List.of("a");
assertSame(table.get(config), table.get(config));
assertEquals(1, builds.get());
}
@Test
public void equalPackObjectsGetTheirOwnRuntime() {
RuntimeTable<List<String>, Object> table = new RuntimeTable<>(config -> new Object());
assertNotSame(table.get(List.of("a")), table.get(new ArrayList<>(List.of("a"))));
}
@Test
public void builderMayResolveOtherEntriesOfTheSameTable() {
RuntimeTable<Integer, Integer>[] holder = new RuntimeTable[1];
holder[0] = new RuntimeTable<>(depth -> depth == 0 ? 0 : holder[0].get(depth - 1) + 1);
assertEquals(Integer.valueOf(3), holder[0].get(3));
}
}
@@ -0,0 +1,79 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
public class ThreadSlotsTest {
private static final int THREAD_CHURN = 2_000;
@Test
public void sameThreadGetsItsOwnValueBack() {
ThreadSlots<Object> slots = new ThreadSlots<>(Object::new);
assertSame(slots.get(), slots.get());
}
@Test
public void otherThreadsGetTheirOwnValues() throws Exception {
ThreadSlots<Object> slots = new ThreadSlots<>(Object::new);
Object callerValue = slots.get();
AtomicReference<Object> workerValue = new AtomicReference<>();
Thread worker = new Thread(() -> workerValue.set(slots.get()));
worker.start();
worker.join();
assertNotSame(callerValue, workerValue.get());
assertSame(callerValue, slots.get());
}
@Test
public void workerChurnReusesSlotsOfDeadThreads() throws Exception {
AtomicInteger created = new AtomicInteger();
ThreadSlots<Object> slots = new ThreadSlots<>(() -> {
created.incrementAndGet();
return new Object();
});
for (int index = 0; index < THREAD_CHURN; index++) {
Thread worker = new Thread(slots::get);
worker.start();
worker.join();
}
assertEquals(THREAD_CHURN, created.get());
assertEquals("The table must stay at its fixed size", 256, slotCount(slots));
}
private static int slotCount(ThreadSlots<?> slots) throws ReflectiveOperationException {
Field field = ThreadSlots.class.getDeclaredField("slots");
field.setAccessible(true);
return ((AtomicReferenceArray<?>) field.get(slots)).length();
}
}
@@ -281,7 +281,33 @@ public class PackRuntimeStateGateTest {
pending("art.arcane.iris.generation.noise.IrisNoiseGenerator$GeneratorKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.terrain.IrisMaterialPalette$LayerGeneratorKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.structure.object.IrisObjectPlacement$SurfaceWarpCacheKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpressionLoad$EngineCache", "styles", Kind.RUNTIME)
pending("art.arcane.iris.generation.noise.IrisExpressionLoad$EngineCache", "styles", Kind.RUNTIME),
pending("art.arcane.iris.generation.bake.ChunkBakeCache", "SPARSE", Kind.SCRATCH),
pending("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_DENSITY", Kind.SCRATCH),
pending("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_REJECT", Kind.SCRATCH),
pending("art.arcane.iris.generation.context.IrisContext", "OVERFLOW", Kind.SCRATCH),
pending("art.arcane.iris.generation.decoration.DecoratorCore", "SCRATCH_OPTS", Kind.SCRATCH),
pending("art.arcane.iris.generation.decoration.IrisDepositGenerator", "FOOTPRINT_CELLS", Kind.SCRATCH),
pending("art.arcane.iris.generation.mantle.CarveOrphanSweep", "SCRATCH", Kind.SCRATCH),
pending("art.arcane.iris.generation.mantle.CaveLatticeBatch", "CURRENT", Kind.SCRATCH),
pending("art.arcane.iris.generation.mantle.IrisCaveCarver3D", "carving", Kind.SCRATCH),
pending("art.arcane.iris.generation.mantle.MantleCarvingComponent", "BLEND_SCRATCH", Kind.SCRATCH),
pending("art.arcane.iris.generation.mantle.MantleWriter", "activeComponentPriority", Kind.SCRATCH),
pending("art.arcane.iris.generation.noise.IrisNoiseGenerator", "FRACTURE_SAMPLES", Kind.SCRATCH),
pending("art.arcane.iris.generation.runtime.EngineTickRegistry", "TICK_ENGINES", Kind.STATIC),
pending("art.arcane.iris.generation.runtime.IrisComplex", "BATCH_SCRATCH", Kind.SCRATCH),
pending("art.arcane.iris.generation.runtime.PaintedColumnRuns", "SCRATCH", Kind.SCRATCH),
pending("art.arcane.iris.generation.stage.IrisCarveModifier", "SCRATCH", Kind.SCRATCH),
pending("art.arcane.iris.generation.stream.ProvisionalSampling", "TRACKERS", Kind.SCRATCH),
pending("art.arcane.iris.generation.terrain.Terrain3DFragmentFilter", "TRAVERSALS", Kind.SCRATCH),
pending("art.arcane.iris.pack.loading.IrisData", "ENGINE_HOLDERS", Kind.STATIC),
pending("art.arcane.iris.pack.loading.IrisData", "dataLoaders", Kind.STATIC),
pending("art.arcane.iris.structure.object.IrisSurfaceSupport", "STENCIL", Kind.SCRATCH),
pending("art.arcane.iris.world.history.GenerationHistoryRuntimeRouter", "operationDepth", Kind.SCRATCH),
pending("art.arcane.iris.world.history.NativeTerrainReceipt", "DEFLATERS", Kind.SCRATCH),
pending("art.arcane.iris.world.history.SavedBiomeStore", "DEFLATERS", Kind.SCRATCH),
pending("art.arcane.iris.world.storage.matter.IrisMatterContext", "DATA", Kind.SCRATCH),
pending("art.arcane.iris.world.tree.TreeSVC", "REENTRANT", Kind.SCRATCH)
);
@Test
@@ -438,34 +464,8 @@ public class PackRuntimeStateGateTest {
);
private static final List<Entry> SETTLED_HOLDERS = List.of(
holder("art.arcane.iris.generation.bake.ChunkBakeCache", "SPARSE", Kind.SCRATCH, "int[] scratch, holds primitives only"),
holder("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_DENSITY", Kind.SCRATCH, "double[] scratch, holds primitives only"),
holder("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_REJECT", Kind.SCRATCH, "int[] scratch, holds primitives only"),
holder("art.arcane.iris.generation.context.IrisContext", "OVERFLOW", Kind.SCRATCH, "scoped context binding, removed when its scope closes"),
holder("art.arcane.iris.generation.decoration.DecoratorCore", "SCRATCH_OPTS", Kind.SCRATCH, "placement options reset by each placement"),
holder("art.arcane.iris.generation.decoration.IrisDepositGenerator", "FOOTPRINT_CELLS", Kind.SCRATCH, "footprint cell buffers, holds primitives only"),
holder("art.arcane.iris.generation.mantle.CarveOrphanSweep", "SCRATCH", Kind.SCRATCH, "sweep buffers, holds primitives only"),
holder("art.arcane.iris.generation.mantle.CaveLatticeBatch", "CURRENT", Kind.SCRATCH, "lattice batch buffers"),
holder("art.arcane.iris.generation.mantle.IrisCaveCarver3D", "carving", Kind.SCRATCH, "reentrancy flag, holds a Boolean only"),
holder("art.arcane.iris.generation.mantle.MantleCarvingComponent", "BLEND_SCRATCH", Kind.SCRATCH, "blend buffers, holds primitives only"),
holder("art.arcane.iris.generation.mantle.MantleWriter", "activeComponentPriority", Kind.SCRATCH, "scoped priority, holds an Integer only"),
holder("art.arcane.iris.generation.noise.IrisNoiseGenerator", "FRACTURE_SAMPLES", Kind.SCRATCH, "fracture chain buffers, nulled after each sample"),
holder("art.arcane.iris.generation.runtime.EnginePanic$Diagnostics", "current", Kind.UNRELATED, "panic diagnostics strings for crash reports"),
holder("art.arcane.iris.generation.runtime.EngineTickRegistry", "TICK_ENGINES", Kind.STATIC, "registry of ticking engines, the shutdown sequence unregisters each engine"),
holder("art.arcane.iris.generation.runtime.IrisComplex", "BATCH_SCRATCH", Kind.SCRATCH, "terrain batch buffers"),
holder("art.arcane.iris.generation.runtime.PaintedColumnRuns", "SCRATCH", Kind.SCRATCH, "column run buffers"),
holder("art.arcane.iris.generation.stage.IrisCarveModifier", "SCRATCH", Kind.SCRATCH, "carve buffers"),
holder("art.arcane.iris.generation.stream.ProvisionalSampling", "TRACKERS", Kind.SCRATCH, "provisional sampling depth tracker"),
holder("art.arcane.iris.generation.terrain.Terrain3DFragmentFilter", "TRAVERSALS", Kind.SCRATCH, "traversal buffers, holds primitives only"),
holder("art.arcane.iris.pack.IrisPackBenchmarking", "instance", Kind.UNRELATED, "benchmark command session"),
holder("art.arcane.iris.pack.loading.IrisData", "ENGINE_HOLDERS", Kind.STATIC, "loaders with registered engines, an engine unregisters itself on close"),
holder("art.arcane.iris.pack.loading.IrisData", "dataLoaders", Kind.STATIC, "pack loader cache by folder"),
holder("art.arcane.iris.structure.object.IrisSurfaceSupport", "STENCIL", Kind.SCRATCH, "support stencil buffers"),
holder("art.arcane.iris.world.history.GenerationHistoryRuntimeRouter", "operationDepth", Kind.SCRATCH, "scoped depth counter, holds an Integer only"),
holder("art.arcane.iris.world.history.NativeTerrainReceipt", "DEFLATERS", Kind.SCRATCH, "Deflater per thread, holds no references"),
holder("art.arcane.iris.world.history.SavedBiomeStore", "DEFLATERS", Kind.SCRATCH, "Deflater per thread, holds no references"),
holder("art.arcane.iris.world.storage.matter.IrisMatterContext", "DATA", Kind.SCRATCH, "scoped IrisData binding, removed when its scope closes"),
holder("art.arcane.iris.world.tree.TreeSVC", "REENTRANT", Kind.SCRATCH, "reentrancy flag, holds a Boolean only")
holder("art.arcane.iris.pack.IrisPackBenchmarking", "instance", Kind.UNRELATED, "benchmark command session")
);
private static Entry holder(String owner, String field, Kind kind, String reason) {
@@ -0,0 +1,149 @@
package art.arcane.iris.probe;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.ExpectedToFailUntilFixed;
import art.arcane.iris.testsupport.ExpectedToFailUntilFixedRule;
import art.arcane.iris.testsupport.IrisRuntimeState;
import com.sun.management.HotSpotDiagnosticMXBean;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* A closed engine must become unreachable while everything that outlives it stays alive: the pack objects it read and
* the pooled generation workers that ran it. Anything engine-derived parked on either one pins the engine and, in a
* server, the whole world it generated.
*/
public class EngineReleaseProbeTest {
private static final long SEED = 7_331L;
private static final String DIMENSION = "release";
private static final int CHUNK_SPAN = 4;
private static final int COLLECTION_ATTEMPTS = 40;
private static final long COLLECTION_PAUSE_MILLIS = 50L;
private static final long WORKER_TASK_TIMEOUT_SECONDS = 60L;
private static final String HEAP_DUMP_ENVIRONMENT = "IRIS_ENGINE_RELEASE_HEAP_DUMP";
@Rule
public final ExpectedToFailUntilFixedRule expectedFailures = new ExpectedToFailUntilFixedRule();
@After
public void resetRuntime() {
IrisRuntimeState.reset();
}
@Test(timeout = 300_000)
@ExpectedToFailUntilFixed("pack objects and worker threads still cache engine-derived state")
public void closedEngineIsCollectableWhilePackObjectsAndWorkersStayAlive() throws Exception {
List<Object> survivingPackObjects = new ArrayList<>();
WeakReference<Engine> closedEngine;
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(
fixturePack().toFile(), DIMENSION, "[engine-release]")) {
closedEngine = generateAndClose(workspace, survivingPackObjects);
}
ForkJoinPool workers = generationWorkers();
assertTrue("Generation workers must still be alive for the check to mean anything",
workers.getPoolSize() > 0);
boolean released = collected(closedEngine);
if (!released) {
dumpHeapWhenRequested();
}
assertTrue("A closed engine is still reachable from pack objects or worker threads", released);
assertTrue("Pack objects must outlive the engine", !survivingPackObjects.isEmpty());
}
private static WeakReference<Engine> generateAndClose(
RealPackProbeSupport.Workspace workspace,
List<Object> survivingPackObjects
) throws Exception {
try (RealPackProbeSupport.EngineSession session = workspace.openEngine(SEED, true, "release")) {
Engine engine = session.engine();
retainPackObjects(engine.getData(), engine.getDimension(), survivingPackObjects);
generateOnCallerAndWorkers(engine);
RealPackProbeSupport.settleAndDrain(engine);
return new WeakReference<>(engine);
}
}
private static void retainPackObjects(IrisData data, IrisDimension dimension, List<Object> survivors) {
survivors.add(dimension);
for (String regionKey : dimension.getRegions()) {
IrisRegion region = data.getRegionLoader().load(regionKey);
assertNotNull("Fixture region " + regionKey, region);
survivors.add(region);
for (String biomeKey : region.getLandBiomes()) {
IrisBiome biome = data.getBiomeLoader().load(biomeKey);
assertNotNull("Fixture biome " + biomeKey, biome);
survivors.add(biome);
}
}
IrisGenerator generator = data.getGeneratorLoader().load("terrain");
assertNotNull("Fixture generator", generator);
survivors.add(generator);
}
private static void generateOnCallerAndWorkers(Engine engine) throws Exception {
List<Future<?>> workerChunks = new ArrayList<>();
for (int chunkX = 0; chunkX < CHUNK_SPAN; chunkX++) {
for (int chunkZ = 0; chunkZ < CHUNK_SPAN; chunkZ++) {
if (((chunkX + chunkZ) & 1) == 0) {
RealPackProbeSupport.generateChunk(engine, chunkX, chunkZ);
continue;
}
int x = chunkX;
int z = chunkZ;
workerChunks.add(MultiBurst.burst.submit(() -> RealPackProbeSupport.generateChunk(engine, x, z)));
}
}
for (Future<?> chunk : workerChunks) {
chunk.get(WORKER_TASK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
}
private static ForkJoinPool generationWorkers() throws Exception {
return MultiBurst.burst.submit((Callable<ForkJoinPool>) ForkJoinTask::getPool)
.get(WORKER_TASK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
private static boolean collected(WeakReference<?> reference) throws InterruptedException {
for (int attempt = 0; attempt < COLLECTION_ATTEMPTS && reference.get() != null; attempt++) {
System.gc();
Thread.sleep(COLLECTION_PAUSE_MILLIS);
}
return reference.get() == null;
}
private static void dumpHeapWhenRequested() throws Exception {
String destination = System.getenv(HEAP_DUMP_ENVIRONMENT);
if (destination == null || destination.isBlank()) {
return;
}
ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class).dumpHeap(destination, true);
}
private static Path fixturePack() throws Exception {
URL resource = Objects.requireNonNull(EngineReleaseProbeTest.class.getResource("/engine-release"));
return Path.of(resource.toURI());
}
}
@@ -0,0 +1,23 @@
{
"name": "Terrain",
"derivative": "minecraft:plains",
"vanillaDerivative": "minecraft:plains",
"layers": [{
"minHeight": 2,
"maxHeight": 5,
"style": {"style": "SIMPLEX", "zoom": 3},
"palette": [{"block": "minecraft:stone"}, {"block": "minecraft:andesite"}]
}],
"generators": [{"generator": "terrain", "min": 20, "max": 30}],
"decorators": [{
"chance": 0.61,
"style": {"style": "SIMPLEX", "zoom": 7},
"variance": {"style": "SIMPLEX", "zoom": 4},
"heightVariance": {"style": "SIMPLEX", "zoom": 9},
"forcePlace": true,
"stackMin": 1,
"stackMax": 5,
"palette": [{"block": "minecraft:stone"}, {"block": "minecraft:dirt"}],
"topPalette": [{"block": "minecraft:granite"}, {"block": "minecraft:andesite"}]
}]
}
@@ -0,0 +1,11 @@
{
"name": "Engine release fixture",
"version": 1,
"mode": {"type": "OVERWORLD"},
"regions": ["terrain"],
"environment": "NORMAL",
"dimensionHeight": {"min": 0, "max": 64},
"logicalHeight": 64,
"fluidHeight": 10,
"caveProfile": {"enabled": false}
}
@@ -0,0 +1,5 @@
{
"seed": 310,
"interpolator": {"function": "NONE", "horizontalScale": 1},
"composite": [{"seed": 310, "style": {"style": "SIMPLEX", "zoom": 19}}]
}
@@ -0,0 +1,6 @@
{
"name": "Terrain",
"landBiomes": ["terrain"],
"seaBiomes": ["terrain"],
"shoreBiomes": ["terrain"]
}