Merge upstream port lane d

NativeStructureWorldgenAccess keeps both sides: writes are still recorded for the stale deferred-record check, and they go through the POI reconciler when one is bound.
This commit is contained in:
piexel committed 2026-11-10 01:32:04 +01:00
commit 4b1d85177f
69 files changed
+2413 -255

No files matched your search

@@ -53,6 +53,7 @@ import art.arcane.iris.core.link.IrisPapiListener;
import art.arcane.iris.core.link.IrisPapiState;
import art.arcane.iris.core.localization.IrisLanguage;
import art.arcane.iris.core.link.MultiverseCoreLink;
import art.arcane.iris.core.agent.AttachSignal;
import art.arcane.iris.core.nms.INMS;
import art.arcane.iris.core.gui.BukkitGuiHost;
import art.arcane.iris.core.gui.PregeneratorJob;
@@ -203,7 +204,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
private final PendingWorldDeleteQueue pendingWorldDeletes = new PendingWorldDeleteQueue(this);
private final PendingWorldReplacementManager pendingWorldReplacements = new PendingWorldReplacementManager(this);
private volatile SettingsHotloadWatch settingsHotloadWatch;
private volatile Thread serverLifecycleThread;
public static VolmitSender getSender() {
VolmitSender current = sender;
@@ -540,6 +540,17 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
this::getIrisVersion,
this::getMCVersion));
SlimJar.load();
restoreAttachSignal();
}
private static void restoreAttachSignal() {
try {
if (AttachSignal.restoreJvmHandler()) {
info("Restored the JVM SIGQUIT handler that the server console replaced");
}
} catch (RuntimeException failure) {
reportError("Could not restore the JVM SIGQUIT handler; the Iris agent may fail to attach.", failure);
}
}
private static void bridgeLog(LogLevel level, String message) {
@@ -746,7 +757,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
public void addShutdownHook() {
removeShutdownHook();
serverLifecycleThread = Thread.currentThread();
shutdownHook = new Thread(this::runShutdownHook, "Iris-ShutdownHook");
try {
Runtime.getRuntime().addShutdownHook(shutdownHook);
@@ -877,6 +887,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
}
public void onDisable() {
pendingWorldReplacements.awaitStagingForShutdown();
teardownPapi();
boolean serverStopping = IrisToolbelt.isServerStopping();
boolean restartingAtStartupBoundary = startupBoundaryRestart.get();
@@ -1012,7 +1023,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
if (generator == null) {
continue;
}
IrisToolbelt.beginWorldMaintenance(world, reason, true);
IrisToolbelt.beginWorldMaintenance(world, reason);
if (!deferredShutdownGenerators.contains(generator)) {
deferredShutdownGenerators.add(generator);
}
@@ -1024,51 +1035,31 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
if (!postStopFinisherStarted.compareAndSet(false, true)) {
return;
}
Thread activeServerThread = serverLifecycleThread;
if (activeServerThread == null) {
Iris.warn("Iris could not start its post-stop runtime finisher because the server lifecycle thread is unavailable.");
return;
}
Thread finisher = new Thread(() -> {
if (!awaitServerThreadTermination(activeServerThread)) {
return;
}
finishDeferredRuntimeTeardown("post-server-stop", 30L);
}, "Iris-PostStop-Finisher");
Thread finisher = new Thread(() -> finishRuntimeAfterServerShutdown("post-server-stop"),
"Iris-PostStop-Finisher");
finisher.setDaemon(false);
finisher.start();
}
static boolean awaitServerThreadTermination(Thread serverThread) {
if (serverThread == null || serverThread == Thread.currentThread()) {
return false;
}
try {
serverThread.join();
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Iris.reportError("Iris post-stop runtime finisher was interrupted.", e);
return false;
}
}
private void runShutdownHook() {
if (startupBoundaryRestart.get()) {
finishDeferredRuntimeTeardown("startup-boundary-restart-hook", 30L);
return;
}
finishRuntimeAfterServerShutdown("shutdown-hook");
}
private void finishRuntimeAfterServerShutdown(String reason) {
if (!awaitServerShutdownBoundary()) {
Iris.warn("Iris skipped JVM-hook runtime teardown because Paper did not reach its post-world-close boundary.");
Iris.warn("Iris retained its runtime and plugin class loader because the server did not reach its post-world-close boundary.");
return;
}
finishDeferredRuntimeTeardown("shutdown-hook", 30L);
finishDeferredRuntimeTeardown(reason, 30L);
}
private boolean awaitServerShutdownBoundary() {
if (!INMS.isBound()) {
return true;
return false;
}
try {
return INMS.get().awaitServerShutdownBoundary(
@@ -1281,12 +1272,15 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
public int getIrisVersion() {
String input = getDescription().getVersion();
int hyphenIndex = input.indexOf('-');
if (hyphenIndex != -1) {
String result = input.substring(0, hyphenIndex);
result = result.replaceAll("\\.", "");
return Integer.parseInt(result);
String release = hyphenIndex < 0 ? input : input.substring(0, hyphenIndex);
if (!release.matches("[0-9]+(?:\\.[0-9]+)*")) {
return -1;
}
try {
return Integer.parseInt(release.replace(".", ""));
} catch (NumberFormatException invalid) {
return -1;
}
return -1;
}
public int getMCVersion() {
@@ -55,6 +55,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@@ -73,6 +74,9 @@ public final class PendingWorldReplacementManager implements Listener {
private volatile UUID overworldEntryAwaitingVerification;
private volatile World overworldEntryWorld;
private volatile boolean paperEntryListenerRegistered;
private final Object stagingMonitor = new Object();
private boolean stagingAdmissionOpen = true;
private StagingAdmission activeStaging;
public PendingWorldReplacementManager(Iris plugin) {
this.plugin = Objects.requireNonNull(plugin, "plugin");
@@ -135,7 +139,7 @@ public final class PendingWorldReplacementManager implements Listener {
LifecycleOperationCoordinator.Domain.WORLD_MUTATION,
LifecycleOperationCoordinator.OperationKind.WORLD_REPLACE,
requiredWorldKey.toString()
)) {
); StagingAdmission stagingAdmission = admitStaging(requiredWorldKey)) {
if (findTransaction(requiredWorldSlotKey) != null) {
throw new IOException("A replacement is already pending for " + requiredWorldKey + ".");
}
@@ -251,6 +255,29 @@ public final class PendingWorldReplacementManager implements Listener {
}
}
public void awaitStagingForShutdown() {
StagingAdmission staging;
synchronized (stagingMonitor) {
stagingAdmissionOpen = false;
staging = activeStaging;
}
if (staging == null) {
return;
}
Iris.warn("Waiting for the replacement of " + staging.worldKey + " to finish staging before Iris shuts down.");
boolean interrupted = false;
while (staging.finished.getCount() > 0L) {
try {
staging.finished.await();
} catch (InterruptedException e) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
public synchronized void processPendingStartupReplacements() {
ArrayList<String> failures = new ArrayList<>();
ArrayList<String> restartBoundaries = new ArrayList<>();
@@ -993,6 +1020,17 @@ public final class PendingWorldReplacementManager implements Listener {
return plugin.getDataFolder().toPath().toAbsolutePath().normalize();
}
StagingAdmission admitStaging(NamespacedKey worldKey) throws IOException {
synchronized (stagingMonitor) {
if (!stagingAdmissionOpen) {
throw new IOException("Iris is shutting down. Run the replacement again after the server starts.");
}
StagingAdmission staging = new StagingAdmission(worldKey);
activeStaging = staging;
return staging;
}
}
private synchronized void loadOverworldEntryGuard() throws IOException {
ExactWorldSlotPathPolicy.Target target = resolveTarget(OVERWORLD_KEY);
Optional<WorldReplacementEntryGuard.Entry> loaded = WorldReplacementEntryGuard.load(target.worldDirectory());
@@ -1157,6 +1195,25 @@ public final class PendingWorldReplacementManager implements Listener {
}
}
final class StagingAdmission implements AutoCloseable {
private final NamespacedKey worldKey;
private final CountDownLatch finished = new CountDownLatch(1);
private StagingAdmission(NamespacedKey worldKey) {
this.worldKey = worldKey;
}
@Override
public void close() {
synchronized (stagingMonitor) {
if (activeStaging == this) {
activeStaging = null;
}
}
finished.countDown();
}
}
private static final class RestartBoundaryRequired extends IOException {
private RestartBoundaryRequired(String message) {
super(message);
@@ -0,0 +1,50 @@
package art.arcane.iris.core.agent;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
public final class AttachSignal {
private static final int SIGQUIT = 3;
private static final int SIGTERM = 15;
private static final long ACTION_BYTES = 256;
private static final long SIG_IGN = 1L;
private AttachSignal() {
}
public static boolean restoreJvmHandler() {
if (System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win")) {
return false;
}
Linker linker = Linker.nativeLinker();
MethodHandle sigaction = linker.downcallHandle(
linker.defaultLookup().find("sigaction")
.orElseThrow(() -> new IllegalStateException("sigaction is unavailable")),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment jvm = arena.allocate(ACTION_BYTES);
MemorySegment quit = arena.allocate(ACTION_BYTES);
if ((int) sigaction.invokeExact(SIGTERM, MemorySegment.NULL, jvm) != 0
|| (int) sigaction.invokeExact(SIGQUIT, MemorySegment.NULL, quit) != 0) {
throw new IllegalStateException("sigaction could not read the SIGTERM and SIGQUIT handlers");
}
long handler = jvm.get(ValueLayout.JAVA_LONG, 0);
if (handler == 0L || handler == SIG_IGN || quit.get(ValueLayout.JAVA_LONG, 0) == handler) {
return false;
}
if ((int) sigaction.invokeExact(SIGQUIT, jvm, MemorySegment.NULL) != 0) {
throw new IllegalStateException("sigaction could not restore the JVM SIGQUIT handler");
}
return true;
} catch (RuntimeException | Error failure) {
throw failure;
} catch (Throwable failure) {
throw new IllegalStateException("Unable to restore the JVM SIGQUIT handler", failure);
}
}
}
@@ -510,7 +510,7 @@ public class CommandIris implements DirectorExecutor {
return;
}
PlatformChunkGenerator generator = IrisToolbelt.access(world);
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
AtomicBoolean maintenanceEntered = new AtomicBoolean(false);
try {
AtomicBoolean terminalTimeout = new AtomicBoolean(false);
CompletableFuture<Boolean> sequence = IrisToolbelt.evacuateAsync(world)
@@ -522,6 +522,8 @@ public class CommandIris implements DirectorExecutor {
if (!Boolean.TRUE.equals(evacuated)) {
return CompletableFuture.completedFuture(false);
}
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
maintenanceEntered.set(true);
return WorldLifecycleService.get().unloadAsync(world, true);
})
.thenCompose(unloaded -> {
@@ -536,7 +538,9 @@ public class CommandIris implements DirectorExecutor {
});
guardUnloadCompletion(sequence, terminalTimeout, world.getName())
.whenComplete((unloaded, throwable) -> {
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
if (maintenanceEntered.get()) {
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
}
lease.close();
Runnable response = () -> reportUnloadResult(responseSender, world, unloaded, throwable);
if (responseSender.isPlayer() && J.runEntity(responseSender.player(), response)) {
@@ -545,7 +549,9 @@ public class CommandIris implements DirectorExecutor {
J.s(response);
});
} catch (Exception e) {
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
if (maintenanceEntered.get()) {
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
}
lease.close();
responseSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_FAILED_UNLOAD_WORLD_3, MessageArgument.untrusted("value", String.valueOf(e.getMessage()))));
Iris.reportError("Failed to unload world \"" + world.getName() + "\".", e);
@@ -24,9 +24,10 @@ public class IrisShutdownOrderingTest {
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 shutdownHook = section(source, "private void runShutdownHook()", "private void finishRuntimeAfterServerShutdown");
String boundaryFinish = section(source, "private void finishRuntimeAfterServerShutdown", "private boolean awaitServerShutdownBoundary");
String boundaryAwait = section(source, "private boolean awaitServerShutdownBoundary", "private void finishDeferredRuntimeTeardown");
String finisher = section(source, "private void startPostStopFinisher()", "private void runShutdownHook");
String generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
String generatorQuiesce = section(generatorSource,
"public void quiesceForServerShutdown()", "public boolean isStudio()");
@@ -43,17 +44,19 @@ public class IrisShutdownOrderingTest {
"startupBoundaryRestart.get()",
"finishDeferredRuntimeTeardown(\"startup-boundary-restart-hook\", 30L)",
"return;",
"awaitServerShutdownBoundary()",
"finishDeferredRuntimeTeardown(\"shutdown-hook\", 30L)");
"finishRuntimeAfterServerShutdown(\"shutdown-hook\")");
assertOrdered(finisher,
"finishRuntimeAfterServerShutdown(\"post-server-stop\")",
"finisher.setDaemon(false)",
"finisher.start()");
assertOrdered(finisher,
"awaitServerThreadTermination(activeServerThread)",
"finishDeferredRuntimeTeardown(\"post-server-stop\", 30L)");
assertOrdered(serverJoin,
"serverThread == Thread.currentThread()",
"serverThread.join()");
assertOrdered(boundaryFinish,
"awaitServerShutdownBoundary()",
"return;",
"finishDeferredRuntimeTeardown(reason, 30L)");
assertTrue("A missing shutdown boundary must retain the runtime",
boundaryAwait.contains("if (!INMS.isBound()) {\n return false;"));
assertFalse("Runtime cleanup must wait for the shutdown boundary, not the server thread",
source.contains("serverThread.join()") || source.contains("serverLifecycleThread"));
assertTrue("Server-stop quiescence must leave queued Paper generation admitted",
quiesce.contains("generator.quiesceForServerShutdown()"));
assertOrdered(quiesce,
@@ -63,6 +66,12 @@ public class IrisShutdownOrderingTest {
assertOrdered(onDisable,
"quiesceRuntimeForServerShutdown(\"onDisable\")",
"super.onDisable()");
assertTrue("Server-stop quiescence must keep queued generation running its mantle stages",
quiesce.contains("IrisToolbelt.beginWorldMaintenance(world, reason);"));
assertTrue("Disable must wait for a replacement that is staging before it tears anything down",
onDisable.indexOf("pendingWorldReplacements.awaitStagingForShutdown()") >= 0
&& onDisable.indexOf("pendingWorldReplacements.awaitStagingForShutdown()")
< onDisable.indexOf("teardownPapi()"));
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",
@@ -0,0 +1,48 @@
package art.arcane.iris;
import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Answers.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
public class IrisVersionNumberTest {
@Test
public void releaseAndQualifiedBuildsUseTheSameVersionNumber() {
for (String version : List.of("4.3.3", "4.3.3-SNAPSHOT", "4.3.3-test")) {
assertEquals(version, 433, plugin(version).getIrisVersion());
}
}
@Test
public void processedPluginMetadataProvidesAValidEngineVersion() throws Exception {
try (InputStream stream = getClass().getResourceAsStream("/plugin.yml")) {
assertNotNull(stream);
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
doReturn(new PluginDescriptionFile(stream)).when(plugin).getDescription();
assertNotEquals(-1, plugin.getIrisVersion());
}
}
@Test
public void malformedAndOverflowingReleaseNumbersStayInvalid() {
for (String version : List.of("development", "4..3", ".4.3.3", "4.3.3.", "4.3a.3-test",
"2147483648", "999999999999999999999-SNAPSHOT", "-SNAPSHOT")) {
assertEquals(version, -1, plugin(version).getIrisVersion());
}
}
private static Iris plugin(String version) {
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
doReturn(new PluginDescriptionFile("Iris", version, Iris.class.getName())).when(plugin).getDescription();
return plugin;
}
}
@@ -0,0 +1,70 @@
package art.arcane.iris.core;
import art.arcane.iris.Iris;
import org.bukkit.NamespacedKey;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class PendingWorldReplacementAdmissionTest {
private static final long STATE_TIMEOUT_SECONDS = 5L;
private static final long JOIN_TIMEOUT_SECONDS = 10L;
private static final long STATE_POLL_MILLIS = 5L;
private final NamespacedKey worldKey = NamespacedKey.minecraft("overworld");
@Test
public void shutdownDoesNotWaitWhenNothingIsStaging() throws Exception {
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
Thread shutdown = new Thread(manager::awaitStagingForShutdown);
shutdown.start();
shutdown.join(TimeUnit.SECONDS.toMillis(JOIN_TIMEOUT_SECONDS));
assertFalse(shutdown.isAlive());
}
@Test
public void shutdownRejectsReplacementsThatStartAfterIt() throws Exception {
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
manager.awaitStagingForShutdown();
IOException rejected = assertThrows(IOException.class, () -> manager.admitStaging(worldKey));
assertTrue(rejected.getMessage().contains("shutting down"));
}
@Test
public void shutdownWaitsForTheReplacementBeingStaged() throws Exception {
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
PendingWorldReplacementManager.StagingAdmission staging = manager.admitStaging(worldKey);
Thread shutdown = new Thread(manager::awaitStagingForShutdown);
shutdown.start();
try {
awaitState(shutdown, Thread.State.WAITING);
assertTrue(shutdown.isAlive());
} finally {
staging.close();
}
shutdown.join(TimeUnit.SECONDS.toMillis(JOIN_TIMEOUT_SECONDS));
assertFalse(shutdown.isAlive());
}
private static void awaitState(Thread thread, Thread.State state) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(STATE_TIMEOUT_SECONDS);
while (thread.getState() != state) {
if (System.nanoTime() > deadline) {
throw new AssertionError(thread.getName() + " never reached " + state + "; it is " + thread.getState());
}
Thread.sleep(STATE_POLL_MILLIS);
}
}
}
@@ -0,0 +1,57 @@
package art.arcane.iris.core.agent;
import org.junit.Test;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
public class AttachSignalTest {
private static final int SIGQUIT = 3;
private static final int SIGTERM = 15;
private static final long ACTION_BYTES = 256;
private static final MethodHandle SIGACTION = Linker.nativeLinker().downcallHandle(
Linker.nativeLinker().defaultLookup().find("sigaction").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
@Test
public void aConsoleThatResetsQuitGetsTheJvmHandlerBack() throws Throwable {
assumeFalse(System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"));
long jvmHandler = handler(SIGTERM);
assertNotEquals(0L, jvmHandler);
try (Arena arena = Arena.ofConfined()) {
MemorySegment original = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, MemorySegment.NULL, original));
try {
MemorySegment reset = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, reset, MemorySegment.NULL));
assertEquals(0L, handler(SIGQUIT));
assertTrue(AttachSignal.restoreJvmHandler());
assertEquals(jvmHandler, handler(SIGQUIT));
assertFalse(AttachSignal.restoreJvmHandler());
} finally {
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, original, MemorySegment.NULL));
}
}
}
private static long handler(int signal) throws Throwable {
try (Arena arena = Arena.ofConfined()) {
MemorySegment action = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) SIGACTION.invokeExact(signal, MemorySegment.NULL, action));
return action.get(ValueLayout.JAVA_LONG, 0);
}
}
}
@@ -85,7 +85,7 @@ public class IrisPapiLifecycleTest {
String source = source();
assertTrue("onDisable must tear the expansion down",
source.contains("public void onDisable() {\n teardownPapi();"));
source.contains("public void onDisable() {\n pendingWorldReplacements.awaitStagingForShutdown();\n teardownPapi();"));
assertTrue("the BileTools pre-unload hook must tear the expansion down",
source.contains("public void onPreUnload(ReloadAware.PreUnloadReason reason) {\n teardownPapi();"));
}