From 6a86ad4b3f8c82d6c872be6aa47992e0f6546b90 Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 11 Nov 2026 19:50:51 +0100 Subject: [PATCH] Hotload while chunks generate and keep regen off the server thread The studio hotloader skipped its folder check whenever a chunk had generated in the last two seconds, then slept four. Flying around while saving kept postponing the hotload, which v3 never did. The generation stage gate already makes a hotload wait for chunks in flight, so the holdoff is gone. Each hotload now logs its pack and duration. Regen called World#getChunkAt on the server thread, which loads or generates the chunk synchronously. Past the loaded area that stalled the tick until the watchdog killed the server. Regen now loads chunks asynchronously and skips chunks that were never generated, since their mantle is reset and they generate fresh when visited. Regen also generated outside the stage gate, so a hotload sealed the engine under it and the chunks in flight failed. It takes a stage permit now, like any chunk the server generates. --- .../iris/core/runtime/ChunkJobReporter.java | 29 ++- .../core/runtime/InPlaceChunkRegenerator.java | 172 +++++++++++++----- .../engine/platform/BukkitChunkGenerator.java | 19 +- 3 files changed, 163 insertions(+), 57 deletions(-) diff --git a/core/src/main/java/art/arcane/iris/core/runtime/ChunkJobReporter.java b/core/src/main/java/art/arcane/iris/core/runtime/ChunkJobReporter.java index 49884c194..2699d321d 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/ChunkJobReporter.java +++ b/core/src/main/java/art/arcane/iris/core/runtime/ChunkJobReporter.java @@ -56,6 +56,7 @@ public final class ChunkJobReporter { private final AtomicBoolean failed = new AtomicBoolean(false); private final AtomicInteger applied = new AtomicInteger(0); private final AtomicInteger failures = new AtomicInteger(0); + private final AtomicInteger skipped = new AtomicInteger(0); private volatile int total = 0; private volatile long startMs = 0L; @@ -89,7 +90,17 @@ public final class ChunkJobReporter { failures.incrementAndGet(); } - int finished = applied.get() + failures.get(); + updateProgress(); + } + + /** A chunk the job had nothing to do for. It leaves the total, so the summary only counts chunks the job worked on. */ + public void countSkipped() { + skipped.incrementAndGet(); + updateProgress(); + } + + private void updateProgress() { + int finished = applied.get() + failures.get() + skipped.get(); if (total > 0) { progress.set(Math.min(0.999D, (double) finished / total)); } @@ -97,10 +108,18 @@ public final class ChunkJobReporter { public void finish(boolean error) { progress.set(1.0D); - failed.set(error || (applied.get() == 0 && total > 0)); + failed.set(error || (applied.get() == 0 && workedTotal() > 0)); complete.set(true); } + public int skipped() { + return skipped.get(); + } + + private int workedTotal() { + return total - skipped.get(); + } + public int applied() { return applied.get(); } @@ -151,7 +170,7 @@ public final class ChunkJobReporter { MessageArgument.trusted("percent", percent), MessageArgument.trusted("stage", stage.get()), MessageArgument.trusted("applied", applied.get()), - MessageArgument.trusted("total", total <= 0 ? "?" : total) + MessageArgument.trusted("total", total <= 0 ? "?" : workedTotal()) )); } }, REPORT_INTERVAL_TICKS)); @@ -166,14 +185,14 @@ public final class ChunkJobReporter { ? IrisLanguage.text( RuntimeProgressMessages.CHUNK_SUMMARY_FAILED, MessageArgument.trusted("applied", applied.get()), - MessageArgument.trusted("total", total), + MessageArgument.trusted("total", workedTotal()), MessageArgument.trusted("elapsed", Form.duration(elapsed, 1)), MessageArgument.trusted("failures", failures.get()) ) : IrisLanguage.text( RuntimeProgressMessages.CHUNK_SUMMARY, MessageArgument.trusted("applied", applied.get()), - MessageArgument.trusted("total", total), + MessageArgument.trusted("total", workedTotal()), MessageArgument.trusted("elapsed", Form.duration(elapsed, 1)) ); diff --git a/core/src/main/java/art/arcane/iris/core/runtime/InPlaceChunkRegenerator.java b/core/src/main/java/art/arcane/iris/core/runtime/InPlaceChunkRegenerator.java index bc0ebabb1..d5a1721cf 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/InPlaceChunkRegenerator.java +++ b/core/src/main/java/art/arcane/iris/core/runtime/InPlaceChunkRegenerator.java @@ -23,8 +23,13 @@ import art.arcane.iris.core.localization.RuntimeProgressMessages; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.core.nms.INMS; import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.core.tools.IrisToolbelt; +import art.arcane.iris.engine.platform.BukkitChunkGenerator; +import art.arcane.iris.engine.platform.BukkitChunkGenerator.GenerationStagePermit; import art.arcane.iris.engine.platform.EngineBukkitOps; +import io.papermc.lib.PaperLib; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.WrongEngineBroException; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.spi.PlatformBiome; import art.arcane.iris.util.common.parallel.MultiBurst; @@ -41,8 +46,11 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator.ChunkData; +import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; @@ -50,6 +58,8 @@ import java.util.function.Consumer; public final class InPlaceChunkRegenerator { private static final int BIOME_STEP = 4; private static final int APPLY_AHEAD = 8; + private static final int PROBE_BATCH_CHUNKS = 256; + private static final String GENERATION_STAGE = "regen"; private final World world; private final Engine engine; @@ -84,6 +94,7 @@ public final class InPlaceChunkRegenerator { reporter.setTotal(targets.size()); reporter.setStage(IrisLanguage.text(RuntimeProgressMessages.CHUNK_STAGE_REGENERATING)); regenerate(targets); + logSkippedChunks(); } catch (Throwable e) { IrisLogging.reportError(e); error = true; @@ -92,6 +103,14 @@ public final class InPlaceChunkRegenerator { } } + private void logSkippedChunks() { + if (reporter.skipped() == 0) { + return; + } + IrisLogging.info("Regen skipped " + reporter.skipped() + " chunks in " + world.getName() + + " that were never generated; they generate fresh when visited."); + } + private void resetMantleMargin() { EngineMantle engineMantle = engine.getMantle(); Mantle mantle = engineMantle.getMantle(); @@ -105,58 +124,125 @@ public final class InPlaceChunkRegenerator { private void regenerate(List targets) throws InterruptedException { Semaphore inFlight = new Semaphore(APPLY_AHEAD); - CountDownLatch allApplied = new CountDownLatch(targets.size()); - for (int[] target : targets) { - int chunkX = target[0]; - int chunkZ = target[1]; + for (int from = 0; from < targets.size(); from += PROBE_BATCH_CHUNKS) { + List batch = targets.subList(from, Math.min(targets.size(), from + PROBE_BATCH_CHUNKS)); + for (int[] generated : generatedChunksOf(batch)) { + inFlight.acquire(); + MultiBurst.burst.lazy(() -> regenerateChunk(generated[0], generated[1], inFlight::release)); + } + } - inFlight.acquire(); - MultiBurst.burst.lazy(() -> { - // Settle exactly once no matter which path fails: an unguarded throw here - // (TerrainChunk.create, runRegion) parked the regen thread on the latch - // forever and stranded the player's boss bar. CAS is required — on Folia's - // owned-region path runRegion runs the apply inline before returning. - AtomicBoolean settled = new AtomicBoolean(); - Consumer settle = ok -> { - if (settled.compareAndSet(false, true)) { - reporter.countApplied(ok); - inFlight.release(); - allApplied.countDown(); - } - }; - try { - TerrainChunk buffer = TerrainChunk.create(world); - engine.generate(chunkX << 4, chunkZ << 4, buffer, false); + inFlight.acquire(APPLY_AHEAD); + } - boolean scheduled = J.runRegion(world, chunkX, chunkZ, () -> { - boolean ok = false; - try { - applyToLiveChunk(chunkX, chunkZ, buffer); - ok = true; - } catch (Throwable e) { - IrisLogging.reportError(e); - } finally { - settle.accept(ok); - } - }); + /** + * Chunks that were never generated are skipped: their mantle is reset, so they generate fresh when first visited. + * Regenerating them here would generate each one twice, and loading them on the server thread stalls it. + */ + private List generatedChunksOf(List batch) { + List> loads = new ArrayList<>(batch.size()); + for (int[] target : batch) { + loads.add(loadIfGenerated(target[0], target[1])); + } - if (!scheduled) { - IrisLogging.warn("Regen could not schedule chunk apply at " + chunkX + "," + chunkZ + " in " + world.getName() + "."); - settle.accept(false); - } - } catch (Throwable e) { - IrisLogging.reportError(e); + List generated = new ArrayList<>(batch.size()); + for (int index = 0; index < batch.size(); index++) { + try { + if (loads.get(index).join() == null) { + reporter.countSkipped(); + continue; + } + generated.add(batch.get(index)); + } catch (CompletionException | CancellationException e) { + IrisLogging.reportError(e); + reporter.countApplied(false); + } + } + return generated; + } + + private CompletableFuture loadIfGenerated(int chunkX, int chunkZ) { + return PaperLib.getChunkAtAsync(world, chunkX, chunkZ, false); + } + + private void regenerateChunk(int chunkX, int chunkZ, Runnable release) { + // Settle exactly once no matter which path fails: an unguarded throw stranded the regen thread and the + // player's boss bar. CAS is required because the apply can run inline, before the scheduling call returns. + AtomicBoolean settled = new AtomicBoolean(); + Consumer settle = ok -> { + if (settled.compareAndSet(false, true)) { + reporter.countApplied(ok); + release.run(); + } + }; + try { + TerrainChunk buffer = generate(chunkX, chunkZ); + loadIfGenerated(chunkX, chunkZ).whenComplete((chunk, loadFailure) -> { + if (!scheduledApply(chunk, buffer, settle)) { settle.accept(false); } }); + } catch (Throwable e) { + IrisLogging.reportError(e); + settle.accept(false); } - - allApplied.await(); } - private void applyToLiveChunk(int chunkX, int chunkZ, TerrainChunk buffer) { - Chunk chunk = world.getChunkAt(chunkX, chunkZ); + /** + * @return false when the apply could not be handed to the thread owning the chunk, so the caller settles the chunk + * as failed; true leaves settling to the apply. + */ + private boolean scheduledApply(Chunk chunk, TerrainChunk buffer, Consumer settle) { + if (chunk == null) { + IrisLogging.warn("Regen could not load a chunk it found generated in " + world.getName() + "."); + return false; + } + try { + return runOnThreadOwning(chunk, () -> settle.accept(applied(chunk, buffer))); + } catch (Throwable e) { + IrisLogging.reportError(e); + return false; + } + } + + /** Holds a generation stage like any chunk the server generates, so a hotload waits for it instead of rejecting it. */ + private TerrainChunk generate(int chunkX, int chunkZ) throws WrongEngineBroException { + TerrainChunk buffer = TerrainChunk.create(world); + try (GenerationStagePermit ignored = acquireGenerationStage()) { + engine.generate(chunkX << 4, chunkZ << 4, buffer, false); + } + return buffer; + } + + private GenerationStagePermit acquireGenerationStage() { + if (IrisToolbelt.access(world) instanceof BukkitChunkGenerator generator) { + return generator.acquireGenerationStage(GENERATION_STAGE); + } + return GenerationStagePermit.noop(); + } + + private boolean runOnThreadOwning(Chunk chunk, Runnable task) { + if (!J.isFolia() && J.isPrimaryThread()) { + task.run(); + return true; + } + return J.runRegion(world, chunk.getX(), chunk.getZ(), task); + } + + private boolean applied(Chunk chunk, TerrainChunk buffer) { + try { + applyToLiveChunk(chunk, buffer); + return true; + } catch (Throwable e) { + IrisLogging.reportError(e); + return false; + } + } + + private void applyToLiveChunk(Chunk chunk, TerrainChunk buffer) { + int chunkX = chunk.getX(); + int chunkZ = chunk.getZ(); for (Entity entity : chunk.getEntities()) { if (!(entity instanceof Player)) { entity.remove(); diff --git a/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java b/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java index 99254a73d..273bcfb01 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java @@ -124,7 +124,6 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun private final boolean studio; private final AtomicBoolean studioEntryBootstrapActive; private final AtomicInteger a = new AtomicInteger(0); - private volatile long lastChunkGenTime = 0L; private final CompletableFuture spawnChunks = new CompletableFuture<>(); private final CompletableFuture initialSpawnReady = new CompletableFuture<>(); private final AtomicCache targetCache = new AtomicCache<>(); @@ -602,14 +601,21 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun return; } - withExclusiveControl(() -> getEngine().hotload()); + withExclusiveControl(this::hotloadEngine); + } + + private void hotloadEngine() { + Engine activeEngine = getEngine(); + long started = M.ms(); + activeEngine.hotload(); + IrisLogging.info("Hotloaded " + activeEngine.getDimension().getLoadKey() + " in " + (M.ms() - started) + "ms"); } private void hotloadFromWatcher() { if (!shouldRunStudioHotload(isStudio(), closing, paintedStudioActive)) { return; } - withExclusiveControlFuture(() -> getEngine().hotload(), HOTLOAD_ACQUISITION_TIMEOUT_SECONDS, TimeUnit.SECONDS).join(); + withExclusiveControlFuture(this::hotloadEngine, HOTLOAD_ACQUISITION_TIMEOUT_SECONDS, TimeUnit.SECONDS).join(); } /** Skipped like the watcher's hotload while a pack file does not parse. */ @@ -622,7 +628,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun if (skipReason.isPresent()) { return CompletableFuture.failedFuture(new IllegalStateException(skipReason.get())); } - return withExclusiveControlFuture(() -> getEngine().hotload(), HOTLOAD_ACQUISITION_TIMEOUT_SECONDS, TimeUnit.SECONDS); + return withExclusiveControlFuture(this::hotloadEngine, HOTLOAD_ACQUISITION_TIMEOUT_SECONDS, TimeUnit.SECONDS); } @Override @@ -860,7 +866,6 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun try { Engine engine = getEngine(world); - lastChunkGenTime = System.currentTimeMillis(); computeStudioGenerator(); TerrainChunk tc = TerrainChunk.create(d); if (studioGenerator != null) { @@ -935,10 +940,6 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun return true; } - if (System.currentTimeMillis() - lastChunkGenTime < 2000L) { - return true; - } - World realWorld = BukkitWorldBinding.world(this.world); PregeneratorJob pregeneratorJob = PregeneratorJob.getInstance(); return realWorld != null && pregeneratorJob != null && pregeneratorJob.targetsWorldIdentity(WorldIdentity.serialize(realWorld));