From ccd942a59f2546fcc813495eec178718d2c89edc Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Mon, 23 Nov 2026 11:38:23 +0100 Subject: [PATCH 1/3] perf: load producing nodes' chunks only around drops and inputs Co-Authored-By: Claude Opus 5.5 --- .../java/net/tfminecraft/dowsing/Cache.java | 13 ++ .../dowsing/loaders/ConfigLoader.java | 7 + .../dowsing/managers/NodeManager.java | 130 +++++++++++++++++- src/main/resources/config.yml | 19 ++- .../dowsing/loaders/DowsingLoadersTest.java | 15 ++ .../managers/NodeManagerCyclesTest.java | 121 ++++++++++++++++ 6 files changed, 300 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/Cache.java b/src/main/java/net/tfminecraft/dowsing/Cache.java index dc9e451..b098867 100644 --- a/src/main/java/net/tfminecraft/dowsing/Cache.java +++ b/src/main/java/net/tfminecraft/dowsing/Cache.java @@ -19,4 +19,17 @@ public class Cache { public static double efficiencyLossType; public static double efficiencyLossPM; + + /** Producing nodes' chunks are loaded only around drops and inputs; false keeps them loaded all the time. */ + public static boolean timedNodeChunks = true; + /** Minutes before a drop that a node's chunk starts loading in the background. */ + public static int nodeChunkLeadMinutes = 1; + /** Minutes before an input that a node's chunk is loaded, so hoppers can fill the barrel first. */ + public static int nodeChunkInputLeadMinutes = 5; + /** Minutes a node's chunk stays loaded after a drop or an input, so hoppers can move the output. */ + public static int nodeChunkDrainMinutes = 5; + /** How often the drain window is extended while the node's hopper still holds items. */ + public static int nodeChunkMaxExtensions = 3; + /** Chunks kept force-loaded all the time ("world x z" in block coordinates), so a world keeps ticking. */ + public static java.util.List keepActiveChunks = java.util.List.of(); } diff --git a/src/main/java/net/tfminecraft/dowsing/loaders/ConfigLoader.java b/src/main/java/net/tfminecraft/dowsing/loaders/ConfigLoader.java index 8454771..c363915 100644 --- a/src/main/java/net/tfminecraft/dowsing/loaders/ConfigLoader.java +++ b/src/main/java/net/tfminecraft/dowsing/loaders/ConfigLoader.java @@ -48,5 +48,12 @@ public void loadConfig(File configFile) { Cache.maxEfficiencyPerMember = config.getDouble("max-efficiency-per-member", 25.0); Cache.efficiencyLossType = config.getDouble("efficiency-loss-type", 40.0); Cache.efficiencyLossPM = config.getDouble("efficiency-loss-pm", 5.0); + + Cache.timedNodeChunks = !"always".equalsIgnoreCase(config.getString("node-chunks.mode", "timed")); + Cache.nodeChunkLeadMinutes = Math.max(0, config.getInt("node-chunks.lead-minutes", 1)); + Cache.nodeChunkInputLeadMinutes = Math.max(0, config.getInt("node-chunks.input-lead-minutes", 5)); + Cache.nodeChunkDrainMinutes = Math.max(1, config.getInt("node-chunks.drain-minutes", 5)); + Cache.nodeChunkMaxExtensions = Math.max(0, config.getInt("node-chunks.max-drain-extensions", 3)); + Cache.keepActiveChunks = java.util.List.copyOf(config.getStringList("node-chunks.keep-active")); } } diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index d4aae5a..372ba46 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -289,11 +289,13 @@ public void run() if(!new ItemDropper().dropItems(n)) continue; n.setTimeLeft(n.getModifiedTime()); n.setInputCounter(0); + startDrain(n); } n.tickCycle(); if(n.getCycleTime().equals(Cache.cycleLength)) { n.setCycleTime(0); n.input(); + startDrain(n); } if(!n.getIsActive()) continue; n.tick(); @@ -344,8 +346,12 @@ static NodeChunk at(Location loc) { private static boolean startCleared = false; /** - * Keeps a producing node's chunk force-loaded, so it produces and its hopper runs with nobody near, - * and lets go of the chunk once no node in it produces: switched off, unowned or in a held realm. A + * Keeps a producing node's chunk force-loaded while it works, so it produces and its hopper runs with + * nobody near. With timed chunks (the default) that is only around its drops and inputs: the chunk loads + * in the background a little before, and stays for the drain time after (longer while the node's hopper + * still holds items); "always" keeps it the whole time. Configured keep-active chunks stay forced so their + * world keeps ticking while nobody is online. Lets go of the chunk once no node in it needs it: switched + * off, unowned, in a held realm, or between a timed node's events. A * removed node's chunk is let go when it breaks ({@link #releaseChunkOf}). A forced chunk never unloads * and keeps every chunk a player loads within 13 chunks of it in memory, so an idle node's chunk must * not stay forced. The force flag (not a plugin ticket) is kept on purpose: like before, it keeps the @@ -356,9 +362,12 @@ static NodeChunk at(Location loc) { */ static void holdNodeChunks() { if(!SimpleFactionsApi.ready()) return; + advanceDrains(); Set wanted = new HashSet<>(); + Set soon = new HashSet<>(); Set unknown = new HashSet<>(); Set idle = new HashSet<>(heldChunks); + wanted.addAll(keepActiveChunks()); boolean lookupFailed = false; for(Node n : nodes) { NodeChunk chunk; @@ -371,7 +380,9 @@ static void holdNodeChunks() { } if(chunk == null) continue; try { - if(producing(n)) wanted.add(chunk); + // With timed chunks a producing node needs its chunk only around a drop or an input. + if(producing(n) && needsChunkNow(n)) wanted.add(chunk); + else if(producing(n) && needsChunkSoon(n)) soon.add(chunk); else if(!startCleared) idle.add(chunk); } catch(RuntimeException ex) { // Not known whether it produces: its chunk keeps what it had and is not let go. @@ -379,8 +390,13 @@ static void holdNodeChunks() { unknown.add(chunk); } } + soon.removeAll(wanted); idle.removeAll(wanted); + idle.removeAll(soon); idle.removeAll(unknown); + upcoming.clear(); + upcoming.addAll(wanted); + upcoming.addAll(soon); Set next = new HashSet<>(); if(lookupFailed) { // A node whose chunk is unknown may be in any of them: nothing is let go this pass. Held @@ -397,6 +413,12 @@ static void holdNodeChunks() { // A held chunk that could not be checked stays held, so it is still let go once idle. if(setForced(chunk, true) || keepAll || heldChunks.contains(chunk)) next.add(chunk); } + for(NodeChunk chunk : soon) { + // Loaded in the background ahead of a drop or input, so the pass never waits for the disk. + if(chunk.loaded()) setForced(chunk, true); + else preload(chunk); + next.add(chunk); + } for(NodeChunk chunk : idle) { // Kept when it could not be let go, so the next pass tries again. if(!setForced(chunk, false)) next.add(chunk); @@ -409,10 +431,107 @@ static void holdNodeChunks() { if(!lookupFailed) startCleared = true; } - private static void logChunkFailure(String message, RuntimeException ex) { + private static void logChunkFailure(String message, Throwable ex) { DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, message, ex); } + /** Chunks wanted or about to be wanted this pass; a background load finishing later only holds these. */ + private static final Set upcoming = new HashSet<>(); + /** Chunks with a background load still running. */ + private static final Set loading = new HashSet<>(); + /** Per node: minutes its chunk stays held after a drop or input, and the extensions used. */ + private static final Map drains = new HashMap<>(); + + /** True when the node drops, takes inputs or is draining this pass, or chunks are not timed. */ + static boolean needsChunkNow(Node n) { + if(!Cache.timedNodeChunks) return true; + if(n.getTimeLeft() <= 0 || drains.containsKey(n.getId())) return true; + return Cache.cycleLength != null && n.getCycleTime() + 1 >= Cache.cycleLength; + } + + /** True when a drop or an input comes within its lead time, so the chunk loads in the background. */ + static boolean needsChunkSoon(Node n) { + if(n.getTimeLeft() <= Cache.nodeChunkLeadMinutes) return true; + return Cache.cycleLength != null && Cache.cycleLength - n.getCycleTime() <= Cache.nodeChunkInputLeadMinutes + 1; + } + + /** Keeps a node's chunk held for the drain time after it dropped items or took inputs. */ + static void startDrain(Node n) { + if(Cache.timedNodeChunks) drains.put(n.getId(), new int[] {Cache.nodeChunkDrainMinutes, 0}); + } + + /** + * Counts down each node's drain time, once per pass. When it runs out while the node's hopper still + * holds items it is extended, up to the configured number of times; removed nodes are forgotten. + */ + static void advanceDrains() { + Set present = new HashSet<>(); + Map byId = new HashMap<>(); + for(Node n : nodes) { + present.add(n.getId()); + byId.put(n.getId(), n); + } + drains.keySet().retainAll(present); + java.util.Iterator> it = drains.entrySet().iterator(); + while(it.hasNext()) { + Map.Entry e = it.next(); + int[] d = e.getValue(); + if(--d[0] > 0) continue; + if(d[1] < Cache.nodeChunkMaxExtensions && hopperHoldsItems(byId.get(e.getKey()))) { + d[0] = Cache.nodeChunkDrainMinutes; + d[1]++; + } else { + it.remove(); + } + } + } + + /** Whether the hopper on top of the node still holds items; false when its chunk is not loaded. */ + static boolean hopperHoldsItems(Node n) { + try { + NodeChunk chunk = NodeChunk.of(n); + if(chunk == null || !chunk.loaded()) return false; + Block block = n.getLoc().clone().add(0, 1, 0).getBlock(); + if(block.getType() != Material.HOPPER) return false; + return !((org.bukkit.block.Hopper) block.getState(false)).getInventory().isEmpty(); + } catch(RuntimeException ex) { + logChunkFailure("Failed to check node " + n.getId() + "'s hopper", ex); + return false; + } + } + + /** Loads a chunk without blocking the server thread and holds it once loaded, if still needed then. */ + static void preload(NodeChunk chunk) { + if(!loading.add(chunk)) return; + try { + chunk.world().getChunkAtAsync(chunk.x(), chunk.z()).whenComplete((loaded, ex) -> + Bukkit.getScheduler().runTask(DowsingMain.plugin, () -> { + loading.remove(chunk); + if(ex != null) logChunkFailure("Failed to load node chunk " + chunk.x() + ", " + chunk.z(), ex); + else if(upcoming.contains(chunk)) setForced(chunk, true); + })); + } catch(RuntimeException ex) { + loading.remove(chunk); + logChunkFailure("Failed to load node chunk " + chunk.x() + ", " + chunk.z(), ex); + } + } + + /** The configured always-loaded chunks whose world exists; a malformed entry is skipped. */ + static Set keepActiveChunks() { + Set chunks = new HashSet<>(); + for(String entry : Cache.keepActiveChunks) { + String[] p = entry.trim().split("\\s+"); + World w = p.length == 3 ? Bukkit.getWorld(p[0]) : null; + if(w == null) continue; + try { + chunks.add(new NodeChunk(w, Integer.parseInt(p[1]) >> 4, Integer.parseInt(p[2]) >> 4)); + } catch(NumberFormatException ex) { + // Skipped like an unknown world. + } + } + return chunks; + } + /** Sets one chunk's force flag; a failing chunk is logged and does not stop the others. */ private static boolean setForced(NodeChunk chunk, boolean on) { try { @@ -447,6 +566,9 @@ public static void releaseChunkOf(Node removed) { static void forgetHeldChunks() { heldChunks.clear(); startCleared = false; + upcoming.clear(); + loading.clear(); + drains.clear(); } /** Every 30 s: resync node benefits when a node's guild or realm changed without a node event. */ diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 38be743..a01d60d 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -12,4 +12,21 @@ min-members-for-node: 1 efficiency-growth-per-member: 0.1 max-efficiency-per-member: 25.0 efficiency-loss-type: 40.0 -efficiency-loss-pm: 0.0 \ No newline at end of file +efficiency-loss-pm: 0.0 + +# How a producing node's chunk is kept loaded. +# timed: only around its drops and inputs. It loads in the background lead-minutes before a drop +# (input-lead-minutes before an input, so hoppers can fill the barrel), and stays drain-minutes +# after, extended up to max-drain-extensions times while the node's hopper still holds items. +# always: every producing node's chunk stays loaded (Dowsing 3.4 behaviour). A loaded chunk keeps every +# chunk a player loads within 13 chunks of it in memory until the restart. +node-chunks: + mode: timed + lead-minutes: 1 + input-lead-minutes: 5 + drain-minutes: 5 + max-drain-extensions: 3 + # Chunks kept force-loaded all the time, "world x z" in block coordinates, so the world keeps ticking + # while nobody is online (pick a spot no player goes). After removing an entry, unload it with + # /forceload remove. + keep-active: [] diff --git a/src/test/java/net/tfminecraft/dowsing/loaders/DowsingLoadersTest.java b/src/test/java/net/tfminecraft/dowsing/loaders/DowsingLoadersTest.java index 8edb064..2036b6c 100644 --- a/src/test/java/net/tfminecraft/dowsing/loaders/DowsingLoadersTest.java +++ b/src/test/java/net/tfminecraft/dowsing/loaders/DowsingLoadersTest.java @@ -109,6 +109,21 @@ void configurationLoadsAllRuntimeSettings() throws Exception { assertEquals(0.6, Cache.refundPercentage); assertEquals(4, Cache.minMembersForNode); assertEquals(0.2, Cache.efficiencyGrowthPerMember); assertEquals(30, Cache.maxEfficiencyPerMember); assertEquals(25, Cache.efficiencyLossType); assertEquals(3, Cache.efficiencyLossPM); + assertTrue(Cache.timedNodeChunks); assertEquals(1, Cache.nodeChunkLeadMinutes); + assertEquals(5, Cache.nodeChunkInputLeadMinutes); assertEquals(5, Cache.nodeChunkDrainMinutes); + assertEquals(3, Cache.nodeChunkMaxExtensions); assertTrue(Cache.keepActiveChunks.isEmpty()); + new ConfigLoader().loadConfig(file("chunks.yml", """ + node-chunks: + mode: ALWAYS + lead-minutes: -2 + input-lead-minutes: 8 + drain-minutes: 0 + max-drain-extensions: -1 + keep-active: ["TFMC_Map 6000 6000"] + """)); + assertFalse(Cache.timedNodeChunks); assertEquals(0, Cache.nodeChunkLeadMinutes); + assertEquals(8, Cache.nodeChunkInputLeadMinutes); assertEquals(1, Cache.nodeChunkDrainMinutes); + assertEquals(0, Cache.nodeChunkMaxExtensions); assertEquals(List.of("TFMC_Map 6000 6000"), Cache.keepActiveChunks); } @Test diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index 6cf1b29..b34de67 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -236,6 +236,7 @@ void chunkLoadingWaitsForSimpleFactionsAndSkipsNodesWithoutAWorld() { @Test void aChunkLoadingFailureIsLoggedAndNodesStillProduce() { + Cache.timedNodeChunks = false; Node node = f.node; when(node.getIsActive()).thenReturn(true); when(node.getTimeLeft()).thenReturn(10); when(node.getCycleTime()).thenReturn(1); NodeManager.nodes.add(node); when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("world gone")); @@ -565,6 +566,8 @@ void productionCycleCompletesRealNodeOutputThenConsumesTheNextInputBatch() { verify(f.world).setChunkForceLoaded(0, 0, true); verify(droppers.constructed().getFirst()).dropItems(node); assertEquals(29, node.getTimeLeft()); assertEquals(0, node.getCycleTime()); assertEquals(1, node.getInputCounter()); verify(engines.constructed().getFirst()).takeInputs(node); assertTrue(node.getIsActive()); + // Neither a drop nor an input is due now; the chunk stays held only for the drain time after them. + assertTrue(NodeManager.needsChunkNow(node)); } } @@ -651,6 +654,121 @@ void inputFailureStopsTickingAndSuccessfulTicksUpdateMatchingOpenMenusOnly() { } } + @Test + void timedChunksAreHeldOnlyAroundDropsAndInputs() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + Cache.cycleLength = 60; Cache.nodeChunkLeadMinutes = 1; Cache.nodeChunkInputLeadMinutes = 5; + when(node.getTimeLeft()).thenReturn(100); when(node.getCycleTime()).thenReturn(10); + NodeManager.holdNodeChunks(); + verify(f.world, never()).setChunkForceLoaded(0, 0, true); + // A drop next pass: held now (already loaded, so no background load is needed). + when(node.getTimeLeft()).thenReturn(1); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + // Nothing due for a while: let go. + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); when(node.getTimeLeft()).thenReturn(50); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + // An input within the input lead time, and one due this pass. + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(false); when(node.getCycleTime()).thenReturn(54); + NodeManager.holdNodeChunks(); + verify(f.world, times(2)).setChunkForceLoaded(0, 0, true); + when(node.getCycleTime()).thenReturn(59); + assertTrue(NodeManager.needsChunkNow(node)); + Cache.cycleLength = null; + assertFalse(NodeManager.needsChunkNow(node)); assertFalse(NodeManager.needsChunkSoon(node)); + // "always" keeps a producing node's chunk the whole time. + Cache.timedNodeChunks = false; + assertTrue(NodeManager.needsChunkNow(node)); + NodeManager.startDrain(node); Cache.timedNodeChunks = true; + assertFalse(NodeManager.needsChunkNow(node)); + } + + @Test + void aDrainKeepsTheChunkAndIsExtendedWhileTheHopperHoldsItems() { + Node node = f.nodeAt(f.location); when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + Cache.cycleLength = 60; Cache.nodeChunkDrainMinutes = 2; Cache.nodeChunkMaxExtensions = 1; + when(node.getTimeLeft()).thenReturn(100); when(node.getCycleTime()).thenReturn(10); + NodeManager.startDrain(node); + assertTrue(NodeManager.needsChunkNow(node)); + NodeManager.advanceDrains(); + assertTrue(NodeManager.needsChunkNow(node)); + // Out of time with an empty hopper (no hopper block at all): the drain ends. + NodeManager.advanceDrains(); + assertFalse(NodeManager.needsChunkNow(node)); + // A hopper that still holds items extends it once, then it ends. + org.bukkit.block.Hopper hopper = mock(org.bukkit.block.Hopper.class); + org.bukkit.inventory.Inventory held = mock(org.bukkit.inventory.Inventory.class); + when(hopper.getInventory()).thenReturn(held); when(held.isEmpty()).thenReturn(false); + when(f.worldBlock.getType()).thenReturn(Material.HOPPER); when(f.worldBlock.getState(false)).thenReturn(hopper); + NodeManager.startDrain(node); + NodeManager.advanceDrains(); NodeManager.advanceDrains(); + assertTrue(NodeManager.needsChunkNow(node)); + NodeManager.advanceDrains(); NodeManager.advanceDrains(); + assertFalse(NodeManager.needsChunkNow(node)); + // An unloaded chunk or a failing check counts as an empty hopper. + when(f.world.isChunkLoaded(0, 0)).thenReturn(false); + assertFalse(NodeManager.hopperHoldsItems(node)); + when(f.world.isChunkLoaded(0, 0)).thenReturn(true); + assertTrue(NodeManager.hopperHoldsItems(node)); + when(f.worldBlock.getState(false)).thenThrow(new IllegalStateException("no state")); + assertFalse(NodeManager.hopperHoldsItems(node)); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("hopper"), any(IllegalStateException.class)); + assertFalse(NodeManager.hopperHoldsItems(f.nodeAt(new Location(null, 1, 2, 3)))); + // A removed node's drain is forgotten. + NodeManager.startDrain(node); NodeManager.nodes.remove(node); + NodeManager.advanceDrains(); NodeManager.nodes.add(node); + assertFalse(NodeManager.needsChunkNow(node)); + } + + @Test + void aChunkThatIsNotLoadedYetLoadsInTheBackgroundAndIsHeldOnlyIfStillNeeded() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + Cache.cycleLength = 60; when(node.getTimeLeft()).thenReturn(1); when(node.getCycleTime()).thenReturn(10); + when(f.world.isChunkLoaded(0, 0)).thenReturn(false); + java.util.concurrent.CompletableFuture load = new java.util.concurrent.CompletableFuture<>(); + when(f.world.getChunkAtAsync(0, 0)).thenReturn(load); + try (Cycles cycles = new Cycles()) { + NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); + verify(f.world, times(1)).getChunkAtAsync(0, 0); + verify(f.world, never()).setChunkForceLoaded(0, 0, true); + load.complete(f.chunk); + verify(f.world).setChunkForceLoaded(0, 0, true); + // Finished after the node stopped needing it: not held. + java.util.concurrent.CompletableFuture late = new java.util.concurrent.CompletableFuture<>(); + when(f.world.getChunkAtAsync(0, 0)).thenReturn(late); + NodeManager.holdNodeChunks(); + when(node.getTimeLeft()).thenReturn(50); + NodeManager.holdNodeChunks(); + late.complete(f.chunk); + verify(f.world, times(1)).setChunkForceLoaded(0, 0, true); + // A failed load is logged, and so is one that cannot even start. + when(node.getTimeLeft()).thenReturn(1); + java.util.concurrent.CompletableFuture failed = new java.util.concurrent.CompletableFuture<>(); + when(f.world.getChunkAtAsync(0, 0)).thenReturn(failed); + NodeManager.holdNodeChunks(); + failed.completeExceptionally(new IllegalStateException("disk")); + when(f.world.getChunkAtAsync(0, 0)).thenThrow(new IllegalStateException("closed")); + NodeManager.holdNodeChunks(); + verify(f.logger, times(2)).log(eq(java.util.logging.Level.SEVERE), contains("Failed to load node chunk 0, 0"), any(IllegalStateException.class)); + } + } + + @Test + void keepActiveChunksStayForcedAndBadEntriesAreSkipped() { + Cache.keepActiveChunks = List.of("TFMC_Map 100 -40", "bad", "TFMC_Map x 3", "nowhere 1 2"); + try (Cycles cycles = new Cycles()) { + cycles.bukkit.when(() -> Bukkit.getWorld("TFMC_Map")).thenReturn(f.world); + cycles.bukkit.when(() -> Bukkit.getWorld("nowhere")).thenReturn(null); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(6, -3, true); + when(f.world.isChunkForceLoaded(6, -3)).thenReturn(true); + Cache.keepActiveChunks = List.of(); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(6, -3, false); + } + } + private static final class Cycles implements AutoCloseable { final Map tasks = new HashMap<>(); final MockedStatic bukkit = mockStatic(Bukkit.class, CALLS_REAL_METHODS); @@ -660,6 +778,9 @@ private static final class Cycles implements AutoCloseable { when(scheduler.runTaskTimer(eq(DowsingMain.plugin), any(Runnable.class), eq(0L), anyLong())).thenAnswer(inv -> { tasks.put(inv.getArgument(3), inv.getArgument(1)); return mock(BukkitTask.class); }); + when(scheduler.runTask(eq(DowsingMain.plugin), any(Runnable.class))).thenAnswer(inv -> { + inv.getArgument(1).run(); return mock(BukkitTask.class); + }); } @Override public void close() { bukkit.close(); } } From 7cbf7f8c2831d55b2f2492fa5a1f19ae1d616dfc Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Mon, 23 Nov 2026 11:51:18 +0100 Subject: [PATCH 2/3] Timed node chunks: a late background load never holds a released chunk; a failing loaded check is isolated Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 11 +++++++--- .../managers/NodeManagerCyclesTest.java | 21 +++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 372ba46..cd0ca33 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -415,8 +415,12 @@ static void holdNodeChunks() { } for(NodeChunk chunk : soon) { // Loaded in the background ahead of a drop or input, so the pass never waits for the disk. - if(chunk.loaded()) setForced(chunk, true); - else preload(chunk); + try { + if(chunk.loaded()) setForced(chunk, true); + else preload(chunk); + } catch(RuntimeException ex) { + logChunkFailure("Failed to load node chunk " + chunk.x() + ", " + chunk.z(), ex); + } next.add(chunk); } for(NodeChunk chunk : idle) { @@ -508,7 +512,8 @@ static void preload(NodeChunk chunk) { Bukkit.getScheduler().runTask(DowsingMain.plugin, () -> { loading.remove(chunk); if(ex != null) logChunkFailure("Failed to load node chunk " + chunk.x() + ", " + chunk.z(), ex); - else if(upcoming.contains(chunk)) setForced(chunk, true); + // Not held when no node needs it any more, or a removed node's chunk was let go meanwhile. + else if(upcoming.contains(chunk) && heldChunks.contains(chunk)) setForced(chunk, true); })); } catch(RuntimeException ex) { loading.remove(chunk); diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index b34de67..15b2641 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -754,6 +754,27 @@ void aChunkThatIsNotLoadedYetLoadsInTheBackgroundAndIsHeldOnlyIfStillNeeded() { } } + @Test + void aBackgroundLoadForARemovedNodeOrAFailingChunkCheckHoldsNothing() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + Cache.cycleLength = 60; when(node.getTimeLeft()).thenReturn(1); when(node.getCycleTime()).thenReturn(10); + when(f.world.isChunkLoaded(0, 0)).thenReturn(false); + java.util.concurrent.CompletableFuture load = new java.util.concurrent.CompletableFuture<>(); + when(f.world.getChunkAtAsync(0, 0)).thenReturn(load); + try (Cycles cycles = new Cycles()) { + NodeManager.holdNodeChunks(); + // The node breaks before the load finishes: its chunk was let go, so the late load holds nothing. + NodeManager.nodes.remove(node); NodeManager.releaseChunkOf(node); + load.complete(f.chunk); + verify(f.world, never()).setChunkForceLoaded(0, 0, true); + // A chunk whose loaded state cannot be read is logged; the pass goes on and still produces. + NodeManager.nodes.add(node); + when(f.world.isChunkLoaded(0, 0)).thenThrow(new IllegalStateException("world gone")); + NodeManager.holdNodeChunks(); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to load node chunk 0, 0"), any(IllegalStateException.class)); + } + } + @Test void keepActiveChunksStayForcedAndBadEntriesAreSkipped() { Cache.keepActiveChunks = List.of("TFMC_Map 100 -40", "bad", "TFMC_Map x 3", "nowhere 1 2"); From f7fb8fe8ba5b3d07ad516da853e42f884edc50ce Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Mon, 23 Nov 2026 12:28:20 +0100 Subject: [PATCH 3/3] Timed node chunks: every producing node gets one drain window after a start, so output a restart left in its hopper still moves Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 11 +++++++++ .../managers/NodeManagerCyclesTest.java | 23 ++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index cd0ca33..756d96c 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -363,6 +363,17 @@ static NodeChunk at(Location loc) { static void holdNodeChunks() { if(!SimpleFactionsApi.ready()) return; advanceDrains(); + if(!startCleared) { + // Drain windows do not survive a restart: every producing node gets one on the first pass, so + // output a restart left in its hopper is still moved (and the window extends while it is not). + for(Node n : nodes) { + try { + if(producing(n)) startDrain(n); + } catch(RuntimeException ex) { + // Handled like any node that cannot be checked, in the loop below. + } + } + } Set wanted = new HashSet<>(); Set soon = new HashSet<>(); Set unknown = new HashSet<>(); diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index 15b2641..33cde4b 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -635,7 +635,7 @@ void failedOutputKeepsTheCyclePendingAndExceptionsDoNotStopOtherNodes() { @Test void inputFailureStopsTickingAndSuccessfulTicksUpdateMatchingOpenMenusOnly() { - Node node = f.node; when(node.getIsActive()).thenReturn(true, true, false); when(node.getTimeLeft()).thenReturn(10); + Node node = f.node; when(node.getIsActive()).thenReturn(true, true, true, false); when(node.getTimeLeft()).thenReturn(10); when(node.getCycleTime()).thenReturn(60); NodeManager.nodes.add(node); try (Cycles cycles = new Cycles()) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(node).input(); verify(node, never()).tick(); @@ -656,6 +656,7 @@ void inputFailureStopsTickingAndSuccessfulTicksUpdateMatchingOpenMenusOnly() { @Test void timedChunksAreHeldOnlyAroundDropsAndInputs() { + NodeManager.holdNodeChunks(); // the start's first pass, before this node exists Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); Cache.cycleLength = 60; Cache.nodeChunkLeadMinutes = 1; Cache.nodeChunkInputLeadMinutes = 5; when(node.getTimeLeft()).thenReturn(100); when(node.getCycleTime()).thenReturn(10); @@ -684,6 +685,24 @@ void timedChunksAreHeldOnlyAroundDropsAndInputs() { assertFalse(NodeManager.needsChunkNow(node)); } + @Test + void theFirstPassAfterAStartGivesEveryProducingNodeADrainWindow() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); + Node broken = f.nodeAt(new Location(f.world, 40, 64, -20)); when(broken.getIsActive()).thenThrow(new IllegalStateException("broken")); + NodeManager.nodes.addAll(List.of(node, broken)); + Cache.cycleLength = 60; Cache.nodeChunkDrainMinutes = 1; + when(node.getTimeLeft()).thenReturn(100); when(node.getCycleTime()).thenReturn(10); + // Not due, but a restart may have left output in its hopper: held for one drain window. + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + // The window ends with an empty hopper: let go, and later passes give no new window. + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + doReturn(true).when(broken).getIsActive(); when(broken.hasGuild()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + assertFalse(NodeManager.needsChunkNow(node)); + } + @Test void aDrainKeepsTheChunkAndIsExtendedWhileTheHopperHoldsItems() { Node node = f.nodeAt(f.location); when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); @@ -723,6 +742,7 @@ void aDrainKeepsTheChunkAndIsExtendedWhileTheHopperHoldsItems() { @Test void aChunkThatIsNotLoadedYetLoadsInTheBackgroundAndIsHeldOnlyIfStillNeeded() { + NodeManager.holdNodeChunks(); Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); Cache.cycleLength = 60; when(node.getTimeLeft()).thenReturn(1); when(node.getCycleTime()).thenReturn(10); when(f.world.isChunkLoaded(0, 0)).thenReturn(false); @@ -756,6 +776,7 @@ void aChunkThatIsNotLoadedYetLoadsInTheBackgroundAndIsHeldOnlyIfStillNeeded() { @Test void aBackgroundLoadForARemovedNodeOrAFailingChunkCheckHoldsNothing() { + NodeManager.holdNodeChunks(); Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); Cache.cycleLength = 60; when(node.getTimeLeft()).thenReturn(1); when(node.getCycleTime()).thenReturn(10); when(f.world.isChunkLoaded(0, 0)).thenReturn(false);