From 5bad8c8ef61532e4c1d94f0320965caaf6d5de2f Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Thu, 19 Nov 2026 14:32:19 +0100 Subject: [PATCH 1/7] perf: let go of idle nodes' chunks and save hopper output with the chunk Every node a guild ever switched on kept its chunk force-loaded forever: Dowsing never undid setForceLoaded. A forced chunk never unloads, and Paper keeps every chunk a player loads within 13 chunks of it in memory until the restart. On Main (11-19) 82 chunks were forced, 37 of them for nodes that no longer produce or no longer exist, and 19,374 chunks sat in memory with no player near (Dev: 2). That is most of Main's heap growth over a day. - Each pass works out which node chunks are needed: an active, owned node outside a held realm. It forces those and lets go of a chunk once no node in it produces (switched off, unowned, held realm, or removed). It uses World.isChunkForceLoaded/setChunkForceLoaded, which do not load the chunk the way getChunk() did. After a restart the idle nodes' saved flags are let go on the first pass. Waits for SimpleFactions, which says who owns a node. - Node output is now put into the hopper through its snapshot and written back with update(), which marks the chunk changed. Filling the live inventory did not, so output the hopper could not pass on was lost at the next restart, and with chunks now unloading it could be lost sooner. Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 70 +++++++++++++++-- .../dowsing/utils/ItemDropper.java | 6 +- .../managers/NodeManagerCyclesTest.java | 78 ++++++++++++++++++- .../managers/NodeManagerEventsTest.java | 4 +- .../dowsing/utils/ItemDropperTest.java | 8 +- 5 files changed, 151 insertions(+), 15 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 0ffa8cd..403b414 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -4,6 +4,7 @@ import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; @@ -16,6 +17,7 @@ import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.Sound; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -277,15 +279,15 @@ public void run() { if (!DowsingMain.plugin.nodesReady()) return; validate(); + try { + holdNodeChunks(); + } catch(RuntimeException ex) { + DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to update node chunk loading", ex); + } for(Node n : nodes) { try { - if(!n.getIsActive()) continue; - if(!n.hasGuild()) continue; - // A held realm's nodes pause until it is taken on. - if(Node.held(n.getGuild())) continue; - if(n.getLoc().getChunk().isForceLoaded() == false) { - n.getLoc().getChunk().setForceLoaded(true); - } + // Switched-off and unowned nodes wait, and a held realm's nodes pause until it is taken on. + if(!producing(n)) continue; if(n.getTimeLeft() <= 0) { if(!new ItemDropper().dropItems(n)) continue; n.setTimeLeft(n.getModifiedTime()); @@ -319,6 +321,60 @@ public void run() } }.runTaskTimer(DowsingMain.plugin, 0L, 1200L); } + /** Whether a node produces this pass: switched on, owned, and not in a held realm. */ + static boolean producing(Node n) { + if(!n.getIsActive() || !n.hasGuild()) return false; + return !Node.held(n.getGuild()); + } + + /** A world chunk that holds a node. */ + record NodeChunk(World world, int x, int z) { + static NodeChunk of(Node n) { + Location loc = n.getLoc(); + if(loc == null || loc.getWorld() == null) return null; + return new NodeChunk(loc.getWorld(), loc.getBlockX() >> 4, loc.getBlockZ() >> 4); + } + boolean forced() { return world.isChunkForceLoaded(x, z); } + void force(boolean on) { world.setChunkForceLoaded(x, z, on); } + } + + /** The chunks the last pass kept loaded for producing nodes. */ + private static final Set heldChunks = new HashSet<>(); + + /** + * Keeps a producing node's chunk 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, in a held realm or removed. + * A forced chunk never unloads and keeps every chunk a player loads within 13 chunks of it in memory + * until the next restart, so an idle node's chunk must not stay forced. Waits for SimpleFactions, + * which says who owns a node. The force flag is saved with the world, so after a restart the chunks + * of the nodes that are idle by then are let go on the first pass. + */ + static void holdNodeChunks() { + if(!SimpleFactionsApi.ready()) return; + Set wanted = new HashSet<>(); + Set idle = new HashSet<>(heldChunks); + for(Node n : nodes) { + NodeChunk chunk = NodeChunk.of(n); + if(chunk == null) continue; + if(producing(n)) wanted.add(chunk); + else idle.add(chunk); + } + idle.removeAll(wanted); + for(NodeChunk chunk : wanted) { + if(!chunk.forced()) chunk.force(true); + } + for(NodeChunk chunk : idle) { + if(chunk.forced()) chunk.force(false); + } + heldChunks.clear(); + heldChunks.addAll(wanted); + } + + /** Forgets the chunks held this uptime, for tests. */ + static void forgetHeldChunks() { + heldChunks.clear(); + } + /** Every 30 s: resync node benefits when a node's guild or realm changed without a node event. */ public void realmCycle(){ new BukkitRunnable() diff --git a/src/main/java/net/tfminecraft/dowsing/utils/ItemDropper.java b/src/main/java/net/tfminecraft/dowsing/utils/ItemDropper.java index 70b26db..9be3599 100644 --- a/src/main/java/net/tfminecraft/dowsing/utils/ItemDropper.java +++ b/src/main/java/net/tfminecraft/dowsing/utils/ItemDropper.java @@ -93,7 +93,11 @@ public boolean dropItems(Node n) { Location loc = n.getLoc().clone().add(0.5, 2, 0.5); Block above = n.getLoc().clone().add(0, 1, 0).getBlock(); if(above != null && above.getType() == Material.HOPPER && above.getState() instanceof Hopper hopper) { - int spilled = deliverToHopper(hopper.getInventory(), items, result, loc); + // Filled through the snapshot and written back, which marks the chunk changed. Filling the + // live inventory did not, so output the hopper could not pass on was gone after the chunk + // unloaded or the server restarted. + int spilled = deliverToHopper(hopper.getSnapshotInventory(), items, result, loc); + hopper.update(false, false); if(spilled > 0) warnSpill(n, above, spilled); } else { for(Map.Entry entry : result.entrySet()) { diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index 88ed2a1..f19fe7f 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -13,6 +13,7 @@ import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.World; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.entity.Entity; @@ -36,6 +37,7 @@ import net.tfminecraft.dowsing.objects.NodeType; import net.tfminecraft.dowsing.utils.ItemDropper; import net.tfminecraft.dowsing.utils.NodeEngine; +import net.tfminecraft.simplefactions.api.SimpleFactionsApi; import net.tfminecraft.simplefactions.guild.Guild; import net.tfminecraft.simplefactions.managers.FactionManager; import net.tfminecraft.simplefactions.objects.Faction; @@ -159,7 +161,75 @@ void aHeldRealmsNodesPauseInsteadOfProducing() { try (Cycles cycles = new Cycles(); var droppers = mockConstruction(ItemDropper.class)) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(held, never()).tickCycle(); verify(held, never()).tick(); assertTrue(droppers.constructed().isEmpty()); - verify(f.chunk, never()).setForceLoaded(true); + verify(f.world, never()).setChunkForceLoaded(0, 0, true); + } + } + + @Test + void anIdleNodesChunkIsLetGoAndForcedAgainOnceItProduces() { + Node node = f.node; NodeManager.nodes.add(node); + // Switched off before a restart: the saved force flag is let go on the first pass. + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(false); when(node.getIsActive()).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world, times(1)).setChunkForceLoaded(0, 0, true); verify(f.world, times(1)).setChunkForceLoaded(0, 0, false); + } + + @Test + void aRemovedNodesChunkIsLetGoButAChunkAnotherNodeProducesInStaysLoaded() { + Node producing = f.nodeAt(f.location), idle = f.nodeAt(f.location); + when(producing.getIsActive()).thenReturn(true); + Node removed = f.nodeAt(new Location(f.world, 40, 64, -20)); when(removed.getIsActive()).thenReturn(true); + NodeManager.nodes.addAll(List.of(producing, idle, removed)); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); verify(f.world).setChunkForceLoaded(2, -2, true); + when(f.world.isChunkForceLoaded(anyInt(), anyInt())).thenReturn(true); + NodeManager.nodes.remove(removed); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(2, -2, false); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); + } + + @Test + void aHeldRealmsNodeAndAnUnownedNodeLetTheirChunksGo() { + World other = mock(World.class); + Node held = f.nodeAt(f.location), unowned = f.nodeAt(new Location(other, 20, 64, 20)); + when(held.getIsActive()).thenReturn(true); when(f.guild.isHeld()).thenReturn(true); + when(unowned.getIsActive()).thenReturn(true); when(unowned.hasGuild()).thenReturn(false); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); when(other.isChunkForceLoaded(1, 1)).thenReturn(true); + NodeManager.nodes.addAll(List.of(held, unowned)); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); verify(other).setChunkForceLoaded(1, 1, false); + } + + @Test + void chunkLoadingWaitsForSimpleFactionsAndSkipsNodesWithoutAWorld() { + Node noWorld = f.nodeAt(new Location(null, 1, 2, 3)), noLocation = f.nodeAt(f.location); + when(noWorld.getIsActive()).thenReturn(true); when(noLocation.getLoc()).thenReturn(null); + NodeManager.nodes.addAll(List.of(f.node, noWorld, noLocation)); + when(f.node.getIsActive()).thenReturn(true); + net.tfminecraft.dowsing.testsupport.FactionFixture.api.when(SimpleFactionsApi::ready).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world, never()).isChunkForceLoaded(anyInt(), anyInt()); + net.tfminecraft.dowsing.testsupport.FactionFixture.api.when(SimpleFactionsApi::ready).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + } + + @Test + void aChunkLoadingFailureIsLoggedAndNodesStillProduce() { + 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")); + try (Cycles cycles = new Cycles()) { + f.manager.start(); cycles.tasks.get(1200L).run(); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to update node chunk loading"), any(IllegalStateException.class)); + verify(node).tick(); } } @@ -341,7 +411,7 @@ void productionCycleCompletesRealNodeOutputThenConsumesTheNextInputBatch() { doAnswer(inv -> { node.setInputCounter(node.getInputCounter() + 1); return null; }).when(engine).takeInputs(node); })) { f.manager.start(); cycles.tasks.get(1200L).run(); - verify(f.chunk).setForceLoaded(true); verify(droppers.constructed().getFirst()).dropItems(node); + 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()); } @@ -411,8 +481,8 @@ void failedOutputKeepsTheCyclePendingAndExceptionsDoNotStopOtherNodes() { @Test void inputFailureStopsTickingAndSuccessfulTicksUpdateMatchingOpenMenusOnly() { - Node node = f.node; when(node.getIsActive()).thenReturn(true, false); when(node.getTimeLeft()).thenReturn(10); - when(node.getCycleTime()).thenReturn(60); NodeManager.nodes.add(node); when(f.chunk.isForceLoaded()).thenReturn(true); + Node node = f.node; when(node.getIsActive()).thenReturn(true, true, false); when(node.getTimeLeft()).thenReturn(10); + when(node.getCycleTime()).thenReturn(60); NodeManager.nodes.add(node); when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); try (Cycles cycles = new Cycles()) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(node).input(); verify(node, never()).tick(); when(node.getIsActive()).thenReturn(true); when(node.getCycleTime()).thenReturn(1); diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java index 487a829..bb91c36 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java @@ -525,7 +525,7 @@ static final class Fixture implements AutoCloseable { return true; }); when(DowsingMain.plugin.getName()).thenReturn("Dowsing"); when(DowsingMain.plugin.isEnabled()).thenReturn(true); - NodeManager.nodes = new ArrayList<>(); NodeManager.extraCapacityByGuild = new HashMap<>(); + NodeManager.nodes = new ArrayList<>(); NodeManager.extraCapacityByGuild = new HashMap<>(); NodeManager.forgetHeldChunks(); Cache.extraCapacity = false; Cache.naturalYieldEnabled = false; Cache.cycleLength = 60; Cache.membersPerCapacity = 2; Cache.maxMemberCapacity = 5; Cache.minMembersForNode = 1; Cache.efficiencyLossPM = 5; Cache.efficiencyLossType = 40; Cache.refundPercentage = 0.8; @@ -589,7 +589,7 @@ ItemStack item(String label) { } @Override public void close() throws Exception { inventories.close(); toggles.close(); types.close(); methods.close(); blocks.close(); factions.close(); MockBukkit.unmock(); - DowsingMain.plugin = previousPlugin; NodeManager.nodes = previousNodes; NodeManager.extraCapacityByGuild = previousCapacity; + DowsingMain.plugin = previousPlugin; NodeManager.nodes = previousNodes; NodeManager.extraCapacityByGuild = previousCapacity; NodeManager.forgetHeldChunks(); net.tfminecraft.simplefactions.Cache.maxExtraNodeCapacity = previousMaxCapacity; for (var entry : previousCache.entrySet()) entry.getKey().set(null, entry.getValue()); } diff --git a/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java b/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java index 50e9d97..54663f4 100644 --- a/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java +++ b/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java @@ -165,6 +165,8 @@ void outputGoesToTheHopperAboveTheNodeInsteadOfTheGround() { assertTrue(new ItemDropper(path -> template, message -> fail(message)).dropItems(node)); verify(delivered).setAmount(3); verify(inventory).addItem(delivered); + // Written back through the snapshot so the chunk is saved with the output in it. + verify(lastHopper).update(false, false); verify(lastHopper, never()).getInventory(); verify(world, never()).dropItem(any(Location.class), any(ItemStack.class)); verify(world).playSound(new Location(world, 4.5, 62, 7.5), Sound.ENTITY_ITEM_PICKUP, 0.5f, 1f); verify(node).setLastResult(Map.of("v.STONE", 3)); verify(node).update(); @@ -289,6 +291,8 @@ void pendingAmountsAboveOneStackAreDeliveredAsOneTransaction() { verify(node).setPendingResult(null); verify(node).setLastResult(Map.of("v.STONE", 130)); } + private Hopper lastHopper; + private Inventory hopperAbove(World world) { Block block = mock(Block.class); Hopper hopper = mock(Hopper.class); @@ -297,7 +301,9 @@ private Inventory hopperAbove(World world) { when(block.getType()).thenReturn(Material.HOPPER); when(block.getState()).thenReturn(hopper); when(block.getX()).thenReturn(4); when(block.getY()).thenReturn(61); when(block.getZ()).thenReturn(7); - when(hopper.getInventory()).thenReturn(inventory); + when(hopper.getSnapshotInventory()).thenReturn(inventory); + when(hopper.update(false, false)).thenReturn(true); + lastHopper = hopper; return inventory; } From cbe8de9a866fc4cc268af8fb3d4251b7540f9c62 Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Thu, 19 Nov 2026 14:40:34 +0100 Subject: [PATCH 2/7] Hold node chunks with Dowsing's own ticket; never load idle chunks to check them Review fixes: - Producing nodes' chunks are held with a Dowsing plugin chunk ticket instead of the shared, saved force flag. The ticket is not saved with the world and goes when the plugin stops, so a node removed just before a restart cannot leave its chunk loaded, and staff or MythicMobs force-loads are left alone. The first pass of each start clears the force flag older Dowsing versions left on node chunks. - validate() skips nodes whose chunk is not loaded: reading their block loaded the chunk on the main thread every minute. Placing a node compares chunk positions instead of loading every node's chunk. - Barrel inputs are taken through the snapshot and written back, which marks the chunk changed; changing the live stacks did not, so they were back after an unload or restart. - If the hopper went away before the write-back, its share of the output is dropped on top instead of being lost. Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 64 ++++++++++++------ .../dowsing/utils/ItemDropper.java | 14 +++- .../tfminecraft/dowsing/utils/NodeEngine.java | 5 +- .../managers/NodeManagerCyclesTest.java | 65 +++++++++++-------- .../managers/NodeManagerEventsTest.java | 2 +- .../dowsing/utils/ItemDropperTest.java | 16 +++++ .../dowsing/utils/NodeEngineTest.java | 5 +- 7 files changed, 118 insertions(+), 53 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 403b414..7482818 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -330,49 +330,68 @@ static boolean producing(Node n) { /** A world chunk that holds a node. */ record NodeChunk(World world, int x, int z) { static NodeChunk of(Node n) { - Location loc = n.getLoc(); + return at(n.getLoc()); + } + static NodeChunk at(Location loc) { if(loc == null || loc.getWorld() == null) return null; return new NodeChunk(loc.getWorld(), loc.getBlockX() >> 4, loc.getBlockZ() >> 4); } - boolean forced() { return world.isChunkForceLoaded(x, z); } - void force(boolean on) { world.setChunkForceLoaded(x, z, on); } + boolean loaded() { return world.isChunkLoaded(x, z); } + void hold() { world.addPluginChunkTicket(x, z, DowsingMain.plugin); } + void release() { world.removePluginChunkTicket(x, z, DowsingMain.plugin); } } - /** The chunks the last pass kept loaded for producing nodes. */ + /** The chunks Dowsing's ticket holds for producing nodes. */ private static final Set heldChunks = new HashSet<>(); + /** Whether this start has cleared the force flags older Dowsing versions left on node chunks. */ + private static boolean legacyFlagsCleared = false; /** - * Keeps a producing node's chunk 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, in a held realm or removed. - * A forced chunk never unloads and keeps every chunk a player loads within 13 chunks of it in memory - * until the next restart, so an idle node's chunk must not stay forced. Waits for SimpleFactions, - * which says who owns a node. The force flag is saved with the world, so after a restart the chunks - * of the nodes that are idle by then are let go on the first pass. + * Keeps a producing node's chunk loaded with Dowsing's own chunk ticket, 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, + * in a held realm or removed. A held 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 held. The ticket belongs to Dowsing + * alone, is not saved with the world and goes when the plugin stops, so a removed node's chunk cannot + * stay loaded past a restart and staff force-loads are left alone. Waits for SimpleFactions, which says + * who owns a node. */ static void holdNodeChunks() { if(!SimpleFactionsApi.ready()) return; Set wanted = new HashSet<>(); - Set idle = new HashSet<>(heldChunks); for(Node n : nodes) { NodeChunk chunk = NodeChunk.of(n); - if(chunk == null) continue; - if(producing(n)) wanted.add(chunk); - else idle.add(chunk); + if(chunk != null && producing(n)) wanted.add(chunk); } - idle.removeAll(wanted); - for(NodeChunk chunk : wanted) { - if(!chunk.forced()) chunk.force(true); + if(!legacyFlagsCleared) clearLegacyForceFlags(); + for(NodeChunk chunk : heldChunks) { + if(!wanted.contains(chunk)) chunk.release(); } - for(NodeChunk chunk : idle) { - if(chunk.forced()) chunk.force(false); + for(NodeChunk chunk : wanted) { + if(!heldChunks.contains(chunk)) chunk.hold(); } heldChunks.clear(); heldChunks.addAll(wanted); } + /** + * Dowsing 3.4 and older force-loaded every node chunk it ever used and never undid it. The flag is + * saved with the world, so the first pass of each start clears it on node chunks; the ticket above + * holds the producing ones from then on. + */ + private static void clearLegacyForceFlags() { + Set seen = new HashSet<>(); + for(Node n : nodes) { + NodeChunk chunk = NodeChunk.of(n); + if(chunk == null || !seen.add(chunk)) continue; + if(chunk.world().isChunkForceLoaded(chunk.x(), chunk.z())) chunk.world().setChunkForceLoaded(chunk.x(), chunk.z(), false); + } + legacyFlagsCleared = true; + } + /** Forgets the chunks held this uptime, for tests. */ static void forgetHeldChunks() { heldChunks.clear(); + legacyFlagsCleared = false; } /** Every 30 s: resync node benefits when a node's guild or realm changed without a node event. */ @@ -432,6 +451,10 @@ public void validate() { if (!SimpleFactionsApi.ready()) return; for(int i = 0; i delivered = new HashMap<>(); + int spilled = deliverToHopper(hopper.getSnapshotInventory(), items, result, loc, delivered); + if(!hopper.update(false, false)) { + // The hopper went away in the meantime: what was meant for it goes on top instead. + for(Map.Entry entry : delivered.entrySet()) { + dropLoose(loc, items.get(entry.getKey()), entry.getValue()); + } + } if(spilled > 0) warnSpill(n, above, spilled); } else { for(Map.Entry entry : result.entrySet()) { @@ -112,7 +118,8 @@ public boolean dropItems(Node n) { * Fills the hopper with what fits and spills the rest on top of it, where the hopper * can still pull it in as it drains. Returns how many items spilled. */ - private int deliverToHopper(Inventory inventory, Map items, Map result, Location loc) { + private int deliverToHopper(Inventory inventory, Map items, Map result, Location loc, + Map deliveredByKey) { int delivered = 0; int spilled = 0; for(Map.Entry entry : result.entrySet()) { @@ -124,6 +131,7 @@ private int deliverToHopper(Inventory inventory, Map items, M } dropLoose(loc, items.get(entry.getKey()), left); delivered += entry.getValue() - left; + if(entry.getValue() > left) deliveredByKey.put(entry.getKey(), entry.getValue() - left); spilled += left; } if(delivered > 0) loc.getWorld().playSound(loc, Sound.ENTITY_ITEM_PICKUP, 0.5f, 1f); diff --git a/src/main/java/net/tfminecraft/dowsing/utils/NodeEngine.java b/src/main/java/net/tfminecraft/dowsing/utils/NodeEngine.java index ed1c53f..a11601f 100644 --- a/src/main/java/net/tfminecraft/dowsing/utils/NodeEngine.java +++ b/src/main/java/net/tfminecraft/dowsing/utils/NodeEngine.java @@ -127,7 +127,9 @@ public void takeInputs(Node n) { l.add(0,-1,0); Block block = l.getBlock(); Barrel b = (Barrel) block.getState(); - Inventory i = b.getInventory(); + // Taken from the snapshot and written back, which marks the chunk changed. Changing the live + // stacks did not, so the inputs were back in the barrel after the chunk unloaded or a restart. + Inventory i = b.getSnapshotInventory(); HashMap inputs = new HashMap<>(); for(NodeSlot slot : n.getCurrentType().getSlots()) { for(String s : slot.getActivePm().getInputs()) { @@ -148,6 +150,7 @@ public void takeInputs(Node n) { for(String key : inputs.keySet()) { take(n, key, inputs.get(key), i); } + b.update(false, false); } public void take(Node n, String path, Integer amount, Inventory i) { for(ItemStack item : i.getContents()) { diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index f19fe7f..d0f01f4 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -161,71 +161,71 @@ void aHeldRealmsNodesPauseInsteadOfProducing() { try (Cycles cycles = new Cycles(); var droppers = mockConstruction(ItemDropper.class)) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(held, never()).tickCycle(); verify(held, never()).tick(); assertTrue(droppers.constructed().isEmpty()); - verify(f.world, never()).setChunkForceLoaded(0, 0, true); + verify(f.world, never()).addPluginChunkTicket(eq(0), eq(0), any()); } } @Test - void anIdleNodesChunkIsLetGoAndForcedAgainOnceItProduces() { + void anIdleNodesChunkIsLetGoAndHeldAgainOnceItProduces() { Node node = f.node; NodeManager.nodes.add(node); - // Switched off before a restart: the saved force flag is let go on the first pass. - when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); NodeManager.holdNodeChunks(); - verify(f.world).setChunkForceLoaded(0, 0, false); - when(f.world.isChunkForceLoaded(0, 0)).thenReturn(false); when(node.getIsActive()).thenReturn(true); + verify(f.world, never()).addPluginChunkTicket(anyInt(), anyInt(), any()); + when(node.getIsActive()).thenReturn(true); + NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); + verify(f.world, times(1)).addPluginChunkTicket(0, 0, DowsingMain.plugin); + when(node.getIsActive()).thenReturn(false); NodeManager.holdNodeChunks(); - verify(f.world).setChunkForceLoaded(0, 0, true); - when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); - NodeManager.holdNodeChunks(); - verify(f.world, times(1)).setChunkForceLoaded(0, 0, true); verify(f.world, times(1)).setChunkForceLoaded(0, 0, false); + verify(f.world).removePluginChunkTicket(0, 0, DowsingMain.plugin); } @Test - void aRemovedNodesChunkIsLetGoButAChunkAnotherNodeProducesInStaysLoaded() { + void aRemovedNodesChunkIsLetGoButAChunkAnotherNodeProducesInStaysHeld() { Node producing = f.nodeAt(f.location), idle = f.nodeAt(f.location); when(producing.getIsActive()).thenReturn(true); Node removed = f.nodeAt(new Location(f.world, 40, 64, -20)); when(removed.getIsActive()).thenReturn(true); NodeManager.nodes.addAll(List.of(producing, idle, removed)); NodeManager.holdNodeChunks(); - verify(f.world).setChunkForceLoaded(0, 0, true); verify(f.world).setChunkForceLoaded(2, -2, true); - when(f.world.isChunkForceLoaded(anyInt(), anyInt())).thenReturn(true); + verify(f.world).addPluginChunkTicket(0, 0, DowsingMain.plugin); verify(f.world).addPluginChunkTicket(2, -2, DowsingMain.plugin); NodeManager.nodes.remove(removed); NodeManager.holdNodeChunks(); - verify(f.world).setChunkForceLoaded(2, -2, false); - verify(f.world, never()).setChunkForceLoaded(0, 0, false); + verify(f.world).removePluginChunkTicket(2, -2, DowsingMain.plugin); + verify(f.world, never()).removePluginChunkTicket(0, 0, DowsingMain.plugin); } @Test - void aHeldRealmsNodeAndAnUnownedNodeLetTheirChunksGo() { + void heldRealmAndUnownedNodesAreNotHeldAndOldForceFlagsGoOncePerStart() { World other = mock(World.class); - Node held = f.nodeAt(f.location), unowned = f.nodeAt(new Location(other, 20, 64, 20)); + Node held = f.nodeAt(f.location), unowned = f.nodeAt(new Location(other, 20, 64, 20)), twin = f.nodeAt(f.location); when(held.getIsActive()).thenReturn(true); when(f.guild.isHeld()).thenReturn(true); when(unowned.getIsActive()).thenReturn(true); when(unowned.hasGuild()).thenReturn(false); when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); when(other.isChunkForceLoaded(1, 1)).thenReturn(true); - NodeManager.nodes.addAll(List.of(held, unowned)); - NodeManager.holdNodeChunks(); - verify(f.world).setChunkForceLoaded(0, 0, false); verify(other).setChunkForceLoaded(1, 1, false); + NodeManager.nodes.addAll(List.of(held, unowned, twin)); + NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); + verify(f.world, never()).addPluginChunkTicket(anyInt(), anyInt(), any()); verify(other, never()).addPluginChunkTicket(anyInt(), anyInt(), any()); + // A flag an older Dowsing left is cleared on the first pass of a start, once per chunk. + verify(f.world, times(1)).setChunkForceLoaded(0, 0, false); verify(other, times(1)).setChunkForceLoaded(1, 1, false); + verify(f.world, times(1)).isChunkForceLoaded(0, 0); } @Test - void chunkLoadingWaitsForSimpleFactionsAndSkipsNodesWithoutAWorld() { + void chunkHoldingWaitsForSimpleFactionsAndSkipsNodesWithoutAWorld() { Node noWorld = f.nodeAt(new Location(null, 1, 2, 3)), noLocation = f.nodeAt(f.location); when(noWorld.getIsActive()).thenReturn(true); when(noLocation.getLoc()).thenReturn(null); NodeManager.nodes.addAll(List.of(f.node, noWorld, noLocation)); when(f.node.getIsActive()).thenReturn(true); net.tfminecraft.dowsing.testsupport.FactionFixture.api.when(SimpleFactionsApi::ready).thenReturn(false); NodeManager.holdNodeChunks(); - verify(f.world, never()).isChunkForceLoaded(anyInt(), anyInt()); + verify(f.world, never()).addPluginChunkTicket(anyInt(), anyInt(), any()); verify(f.world, never()).isChunkForceLoaded(anyInt(), anyInt()); net.tfminecraft.dowsing.testsupport.FactionFixture.api.when(SimpleFactionsApi::ready).thenReturn(true); NodeManager.holdNodeChunks(); - verify(f.world).setChunkForceLoaded(0, 0, true); + verify(f.world).addPluginChunkTicket(0, 0, DowsingMain.plugin); } @Test - void aChunkLoadingFailureIsLoggedAndNodesStillProduce() { + void aChunkHoldingFailureIsLoggedAndNodesStillProduce() { 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")); + when(f.world.addPluginChunkTicket(0, 0, DowsingMain.plugin)).thenThrow(new IllegalStateException("world gone")); try (Cycles cycles = new Cycles()) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to update node chunk loading"), any(IllegalStateException.class)); @@ -233,6 +233,17 @@ void aChunkLoadingFailureIsLoggedAndNodesStillProduce() { } } + @Test + void aPassNeverLoadsAnIdleNodesChunkToValidateIt() { + Node node = f.node; NodeManager.nodes.add(node); + when(f.world.isChunkLoaded(0, 0)).thenReturn(false); + try (Cycles cycles = new Cycles()) { + f.manager.start(); cycles.tasks.get(1200L).run(); + verify(f.world, never()).getBlockAt(any(Location.class)); verify(node, never()).breakNode(); + assertTrue(NodeManager.nodes.contains(node)); + } + } + @Test void validationRemovesEveryAdjacentInvalidNodeInTheSamePass() { NodeManager.nodes.addAll(List.of(f.node, f.nodeAt(f.location))); @@ -411,7 +422,7 @@ void productionCycleCompletesRealNodeOutputThenConsumesTheNextInputBatch() { doAnswer(inv -> { node.setInputCounter(node.getInputCounter() + 1); return null; }).when(engine).takeInputs(node); })) { f.manager.start(); cycles.tasks.get(1200L).run(); - verify(f.world).setChunkForceLoaded(0, 0, true); verify(droppers.constructed().getFirst()).dropItems(node); + verify(f.world).addPluginChunkTicket(0, 0, DowsingMain.plugin); 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()); } @@ -482,7 +493,7 @@ void failedOutputKeepsTheCyclePendingAndExceptionsDoNotStopOtherNodes() { @Test void inputFailureStopsTickingAndSuccessfulTicksUpdateMatchingOpenMenusOnly() { Node node = f.node; when(node.getIsActive()).thenReturn(true, true, false); when(node.getTimeLeft()).thenReturn(10); - when(node.getCycleTime()).thenReturn(60); NodeManager.nodes.add(node); when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + 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(); when(node.getIsActive()).thenReturn(true); when(node.getCycleTime()).thenReturn(1); diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java index bb91c36..8aa59f2 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java @@ -533,7 +533,7 @@ static final class Fixture implements AutoCloseable { when(guild.getId()).thenReturn("guild"); when(guild.getLeader()).thenReturn("Leader"); when(guild.getMembers()).thenReturn(List.of("Leader", "Member")); when(guild.getBank()).thenReturn(bank); when(bank.getWealth()).thenReturn(1000.0); when(player.getName()).thenReturn("Leader"); when(player.getLocation()).thenReturn(location); - when(world.getChunkAt(any(Location.class))).thenReturn(chunk); + when(world.getChunkAt(any(Location.class))).thenReturn(chunk); when(world.isChunkLoaded(anyInt(), anyInt())).thenReturn(true); when(world.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(worldBlock); when(world.getBlockAt(any(Location.class))).thenReturn(worldBlock); when(worldBlock.getLocation()).thenReturn(location); when(worldBlock.getWorld()).thenReturn(world); when(worldBlock.getType()).thenReturn(Material.BARRIER); Biome biome = mock(Biome.class); when(biome.toString()).thenReturn("PLAINS"); when(worldBlock.getBiome()).thenReturn(biome); diff --git a/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java b/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java index 54663f4..92286fe 100644 --- a/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java +++ b/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java @@ -291,6 +291,22 @@ void pendingAmountsAboveOneStackAreDeliveredAsOneTransaction() { verify(node).setPendingResult(null); verify(node).setLastResult(Map.of("v.STONE", 130)); } + @Test + void outputMeantForAHopperThatWentAwayIsDroppedOnTopInstead() { + World world = mock(World.class); + Node node = nodeAt(new Location(world, 4, 60, 7), Map.of("v.STONE", 1.0), 3); + Inventory inventory = hopperAbove(world); + when(inventory.addItem(any(ItemStack.class))).thenReturn(new HashMap<>()); + when(lastHopper.update(false, false)).thenReturn(false); + ItemStack template = mock(ItemStack.class); when(template.getMaxStackSize()).thenReturn(64); + ItemStack delivered = mock(ItemStack.class); when(template.clone()).thenReturn(delivered); + Item dropped = mock(Item.class); when(world.dropItem(any(Location.class), any(ItemStack.class))).thenReturn(dropped); + assertTrue(new ItemDropper(path -> template, message -> fail(message)).dropItems(node)); + verify(world).dropItem(new Location(world, 4.5, 62, 7.5), delivered); + verify(delivered, atLeastOnce()).setAmount(3); + verify(node).setLastResult(Map.of("v.STONE", 3)); + } + private Hopper lastHopper; private Inventory hopperAbove(World world) { diff --git a/src/test/java/net/tfminecraft/dowsing/utils/NodeEngineTest.java b/src/test/java/net/tfminecraft/dowsing/utils/NodeEngineTest.java index dfa4a3f..05283af 100644 --- a/src/test/java/net/tfminecraft/dowsing/utils/NodeEngineTest.java +++ b/src/test/java/net/tfminecraft/dowsing/utils/NodeEngineTest.java @@ -39,6 +39,7 @@ class NodeEngineTest { World world; Block below, above; Inventory inventory; + Barrel barrel; AtomicInteger inputs; @BeforeEach void setUp() { @@ -49,7 +50,7 @@ class NodeEngineTest { when(node.getMultiplier()).thenReturn(2); inputs = new AtomicInteger(2); when(node.getInputCounter()).thenAnswer(inv -> inputs.get()); doAnswer(inv -> { inputs.set(inv.getArgument(0)); return null; }).when(node).setInputCounter(anyInt()); when(world.getBlockAt(any(Location.class))).thenAnswer(inv -> ((Location) inv.getArgument(0)).getBlockY() == 63 ? below : above); - when(below.getType()).thenReturn(Material.BARREL); when(below.getState()).thenReturn(barrel); when(barrel.getInventory()).thenReturn(inventory); + when(below.getType()).thenReturn(Material.BARREL); when(below.getState()).thenReturn(barrel); when(barrel.getInventory()).thenReturn(inventory); when(barrel.getSnapshotInventory()).thenReturn(inventory); this.barrel = barrel; when(above.getType()).thenReturn(Material.HOPPER); tlibs = mockStatic(TLibs.class); ItemAPI api = mock(ItemAPI.class); ItemChecker checker = mock(ItemChecker.class); tlibs.when(TLibs::getItemAPI).thenReturn(api); when(api.getChecker()).thenReturn(checker); @@ -89,6 +90,8 @@ void takingInputsConsumesExactlyOneAggregatedBatchAndLeavesUnrelatedItems() { inventory.setItem(2, new ItemStack(Material.COAL, 3)); inventory.setItem(3, new ItemStack(Material.DIAMOND, 4)); engine.takeInputs(node); assertEquals(3, inputs.get()); assertEquals(3, count(Material.STONE)); assertEquals(1, count(Material.COAL)); assertEquals(4, count(Material.DIAMOND)); + // Taken from the snapshot and written back, so the chunk is saved without the inputs. + verify(barrel).getSnapshotInventory(); verify(barrel).update(false, false); engine.take(node, "v.EMERALD", 1, inventory); assertEquals(4, count(Material.DIAMOND)); engine.take(node, "v.STONE", 100, inventory); assertEquals(0, count(Material.STONE)); } From 330c757450c8ada6bd9d7999e679c487813b2e37 Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Thu, 19 Nov 2026 14:45:40 +0100 Subject: [PATCH 3/7] Keep the force flag for producing nodes; let go of a node's chunk when it breaks Plugin chunk tickets (flags 6 in Paper 1.21.10) do not keep a world active the way the forced ticket (flags 15) does. With no forced chunk left, a world with nobody online stops ticking entities and block entities after 15 s, so node hoppers (and other machinery) would pause whenever the server is empty. Back to the force flag, which keeps that behaviour as before: - Producing nodes' chunks are force-loaded; a chunk is let go once no node in it produces. The first pass of each start lets go of every idle node's chunk (including those Dowsing 3.4 and older left); later passes only touch chunks this start forced, so staff force-loads made later are left alone. - A removed node's chunk is let go when the node breaks, unless another producing node is in it, so the saved flag cannot outlive the node when the server stops before the next pass. Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 62 ++++++++-------- .../net/tfminecraft/dowsing/objects/Node.java | 1 + .../managers/NodeManagerCyclesTest.java | 73 +++++++++++-------- 3 files changed, 77 insertions(+), 59 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 7482818..6a5826b 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -337,61 +337,65 @@ static NodeChunk at(Location loc) { return new NodeChunk(loc.getWorld(), loc.getBlockX() >> 4, loc.getBlockZ() >> 4); } boolean loaded() { return world.isChunkLoaded(x, z); } - void hold() { world.addPluginChunkTicket(x, z, DowsingMain.plugin); } - void release() { world.removePluginChunkTicket(x, z, DowsingMain.plugin); } + boolean forced() { return world.isChunkForceLoaded(x, z); } + void force(boolean on) { world.setChunkForceLoaded(x, z, on); } } - /** The chunks Dowsing's ticket holds for producing nodes. */ + /** The chunks the passes of this start force-loaded for producing nodes. */ private static final Set heldChunks = new HashSet<>(); - /** Whether this start has cleared the force flags older Dowsing versions left on node chunks. */ - private static boolean legacyFlagsCleared = false; + /** Whether this start has let go of the idle node chunks an earlier start left force-loaded. */ + private static boolean startCleared = false; /** - * Keeps a producing node's chunk loaded with Dowsing's own chunk ticket, 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, - * in a held realm or removed. A held 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 held. The ticket belongs to Dowsing - * alone, is not saved with the world and goes when the plugin stops, so a removed node's chunk cannot - * stay loaded past a restart and staff force-loads are left alone. Waits for SimpleFactions, which says - * who owns a node. + * 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 + * 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 + * world ticking hoppers while nobody is online. It is saved with the world, so the first pass of each + * start lets go of every idle node's chunk, including those Dowsing 3.4 and older never let go; later + * passes only touch chunks this start forced. Waits for SimpleFactions, which says who owns a node. */ static void holdNodeChunks() { if(!SimpleFactionsApi.ready()) return; Set wanted = new HashSet<>(); + Set idle = new HashSet<>(heldChunks); for(Node n : nodes) { NodeChunk chunk = NodeChunk.of(n); - if(chunk != null && producing(n)) wanted.add(chunk); - } - if(!legacyFlagsCleared) clearLegacyForceFlags(); - for(NodeChunk chunk : heldChunks) { - if(!wanted.contains(chunk)) chunk.release(); + if(chunk == null) continue; + if(producing(n)) wanted.add(chunk); + else if(!startCleared) idle.add(chunk); } + idle.removeAll(wanted); for(NodeChunk chunk : wanted) { - if(!heldChunks.contains(chunk)) chunk.hold(); + if(!chunk.forced()) chunk.force(true); + } + for(NodeChunk chunk : idle) { + if(chunk.forced()) chunk.force(false); } heldChunks.clear(); heldChunks.addAll(wanted); + startCleared = true; } /** - * Dowsing 3.4 and older force-loaded every node chunk it ever used and never undid it. The flag is - * saved with the world, so the first pass of each start clears it on node chunks; the ticket above - * holds the producing ones from then on. + * Lets go of a removed node's chunk right away, unless another producing node is in it, so the saved + * force flag cannot outlive the node when the server stops before the next pass. */ - private static void clearLegacyForceFlags() { - Set seen = new HashSet<>(); + public static void releaseChunkOf(Node removed) { + NodeChunk chunk = NodeChunk.of(removed); + if(chunk == null) return; for(Node n : nodes) { - NodeChunk chunk = NodeChunk.of(n); - if(chunk == null || !seen.add(chunk)) continue; - if(chunk.world().isChunkForceLoaded(chunk.x(), chunk.z())) chunk.world().setChunkForceLoaded(chunk.x(), chunk.z(), false); + if(n != removed && chunk.equals(NodeChunk.of(n)) && producing(n)) return; } - legacyFlagsCleared = true; + heldChunks.remove(chunk); + if(chunk.forced()) chunk.force(false); } - /** Forgets the chunks held this uptime, for tests. */ + /** Forgets what this start held and cleared, for tests. */ static void forgetHeldChunks() { heldChunks.clear(); - legacyFlagsCleared = false; + startCleared = false; } /** Every 30 s: resync node benefits when a node's guild or realm changed without a node event. */ diff --git a/src/main/java/net/tfminecraft/dowsing/objects/Node.java b/src/main/java/net/tfminecraft/dowsing/objects/Node.java index fd2ceea..b8c1d23 100644 --- a/src/main/java/net/tfminecraft/dowsing/objects/Node.java +++ b/src/main/java/net/tfminecraft/dowsing/objects/Node.java @@ -759,6 +759,7 @@ public void breakNode() { // Stale menus can repeat removal; the node item and held output must drop only once. if(this.broken) return; this.broken = true; + NodeManager.releaseChunkOf(this); String path = this.getBlock().getBlock(); String type = path.split("\\.")[0]; if(type.equalsIgnoreCase("v")) { diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index d0f01f4..c015404 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -161,71 +161,84 @@ void aHeldRealmsNodesPauseInsteadOfProducing() { try (Cycles cycles = new Cycles(); var droppers = mockConstruction(ItemDropper.class)) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(held, never()).tickCycle(); verify(held, never()).tick(); assertTrue(droppers.constructed().isEmpty()); - verify(f.world, never()).addPluginChunkTicket(eq(0), eq(0), any()); + verify(f.world, never()).setChunkForceLoaded(0, 0, true); } } @Test - void anIdleNodesChunkIsLetGoAndHeldAgainOnceItProduces() { + void anIdleNodesChunkIsLetGoAndForcedAgainOnceItProduces() { Node node = f.node; NodeManager.nodes.add(node); + // Switched off before a restart: the saved force flag is let go on the first pass. + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); NodeManager.holdNodeChunks(); - verify(f.world, never()).addPluginChunkTicket(anyInt(), anyInt(), any()); - when(node.getIsActive()).thenReturn(true); - NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); - verify(f.world, times(1)).addPluginChunkTicket(0, 0, DowsingMain.plugin); + verify(f.world).setChunkForceLoaded(0, 0, false); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(false); when(node.getIsActive()).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world, times(1)).setChunkForceLoaded(0, 0, true); when(node.getIsActive()).thenReturn(false); NodeManager.holdNodeChunks(); - verify(f.world).removePluginChunkTicket(0, 0, DowsingMain.plugin); + verify(f.world, times(2)).setChunkForceLoaded(0, 0, false); } @Test - void aRemovedNodesChunkIsLetGoButAChunkAnotherNodeProducesInStaysHeld() { - Node producing = f.nodeAt(f.location), idle = f.nodeAt(f.location); - when(producing.getIsActive()).thenReturn(true); - Node removed = f.nodeAt(new Location(f.world, 40, 64, -20)); when(removed.getIsActive()).thenReturn(true); - NodeManager.nodes.addAll(List.of(producing, idle, removed)); + void afterTheFirstPassOnlyChunksThisStartForcedAreLetGo() { + Node idle = f.nodeAt(new Location(f.world, 40, 64, -20)); NodeManager.nodes.add(idle); NodeManager.holdNodeChunks(); - verify(f.world).addPluginChunkTicket(0, 0, DowsingMain.plugin); verify(f.world).addPluginChunkTicket(2, -2, DowsingMain.plugin); - NodeManager.nodes.remove(removed); + // Forced later by someone else, such as staff: Dowsing leaves it alone. + when(f.world.isChunkForceLoaded(2, -2)).thenReturn(true); NodeManager.holdNodeChunks(); - verify(f.world).removePluginChunkTicket(2, -2, DowsingMain.plugin); - verify(f.world, never()).removePluginChunkTicket(0, 0, DowsingMain.plugin); + verify(f.world, never()).setChunkForceLoaded(2, -2, false); + } + + @Test + void aBrokenNodesChunkIsLetGoAtOnceUnlessAnotherProducingNodeIsInIt() { + Node producing = f.nodeAt(f.location), removed = f.nodeAt(f.location); + when(producing.getIsActive()).thenReturn(true); when(removed.getIsActive()).thenReturn(true); + Node alone = f.nodeAt(new Location(f.world, 40, 64, -20)); when(alone.getIsActive()).thenReturn(true); + NodeManager.nodes.addAll(List.of(producing, removed, alone)); + when(f.world.isChunkForceLoaded(anyInt(), anyInt())).thenReturn(true); + NodeManager.releaseChunkOf(removed); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); + NodeManager.releaseChunkOf(alone); + verify(f.world).setChunkForceLoaded(2, -2, false); + NodeManager.releaseChunkOf(f.nodeAt(new Location(null, 1, 2, 3))); } @Test - void heldRealmAndUnownedNodesAreNotHeldAndOldForceFlagsGoOncePerStart() { + void heldRealmAndUnownedNodesLetTheirChunksGo() { World other = mock(World.class); - Node held = f.nodeAt(f.location), unowned = f.nodeAt(new Location(other, 20, 64, 20)), twin = f.nodeAt(f.location); + Node held = f.nodeAt(f.location), unowned = f.nodeAt(new Location(other, 20, 64, 20)); when(held.getIsActive()).thenReturn(true); when(f.guild.isHeld()).thenReturn(true); when(unowned.getIsActive()).thenReturn(true); when(unowned.hasGuild()).thenReturn(false); when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); when(other.isChunkForceLoaded(1, 1)).thenReturn(true); - NodeManager.nodes.addAll(List.of(held, unowned, twin)); - NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); - verify(f.world, never()).addPluginChunkTicket(anyInt(), anyInt(), any()); verify(other, never()).addPluginChunkTicket(anyInt(), anyInt(), any()); - // A flag an older Dowsing left is cleared on the first pass of a start, once per chunk. - verify(f.world, times(1)).setChunkForceLoaded(0, 0, false); verify(other, times(1)).setChunkForceLoaded(1, 1, false); - verify(f.world, times(1)).isChunkForceLoaded(0, 0); + NodeManager.nodes.addAll(List.of(held, unowned)); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); verify(other).setChunkForceLoaded(1, 1, false); + verify(f.world, never()).setChunkForceLoaded(0, 0, true); } @Test - void chunkHoldingWaitsForSimpleFactionsAndSkipsNodesWithoutAWorld() { + void chunkLoadingWaitsForSimpleFactionsAndSkipsNodesWithoutAWorld() { Node noWorld = f.nodeAt(new Location(null, 1, 2, 3)), noLocation = f.nodeAt(f.location); when(noWorld.getIsActive()).thenReturn(true); when(noLocation.getLoc()).thenReturn(null); NodeManager.nodes.addAll(List.of(f.node, noWorld, noLocation)); when(f.node.getIsActive()).thenReturn(true); net.tfminecraft.dowsing.testsupport.FactionFixture.api.when(SimpleFactionsApi::ready).thenReturn(false); NodeManager.holdNodeChunks(); - verify(f.world, never()).addPluginChunkTicket(anyInt(), anyInt(), any()); verify(f.world, never()).isChunkForceLoaded(anyInt(), anyInt()); + verify(f.world, never()).isChunkForceLoaded(anyInt(), anyInt()); net.tfminecraft.dowsing.testsupport.FactionFixture.api.when(SimpleFactionsApi::ready).thenReturn(true); NodeManager.holdNodeChunks(); - verify(f.world).addPluginChunkTicket(0, 0, DowsingMain.plugin); + verify(f.world).setChunkForceLoaded(0, 0, true); } @Test - void aChunkHoldingFailureIsLoggedAndNodesStillProduce() { + void aChunkLoadingFailureIsLoggedAndNodesStillProduce() { 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.addPluginChunkTicket(0, 0, DowsingMain.plugin)).thenThrow(new IllegalStateException("world gone")); + when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("world gone")); try (Cycles cycles = new Cycles()) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to update node chunk loading"), any(IllegalStateException.class)); @@ -422,7 +435,7 @@ void productionCycleCompletesRealNodeOutputThenConsumesTheNextInputBatch() { doAnswer(inv -> { node.setInputCounter(node.getInputCounter() + 1); return null; }).when(engine).takeInputs(node); })) { f.manager.start(); cycles.tasks.get(1200L).run(); - verify(f.world).addPluginChunkTicket(0, 0, DowsingMain.plugin); verify(droppers.constructed().getFirst()).dropItems(node); + 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()); } From eece1e33463cbc487c906b1c63865c351396aa30 Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Thu, 19 Nov 2026 14:51:17 +0100 Subject: [PATCH 4/7] Guard chunk release so a failure cannot cost node items or block other chunks Review nits: - breakNode lets go of the chunk last, in a try/catch, so a failure there cannot skip the node item and held output. - A broken node only lets go of a chunk Dowsing holds (or any node chunk before the first pass), so a later staff force-load is left alone. - Each chunk's force flag is set in its own try/catch: one failing chunk is logged and retried next pass instead of stopping every other release. - Javadoc no longer claims spots of nodes removed before this version are cleared. Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 29 +++++++++++--- .../net/tfminecraft/dowsing/objects/Node.java | 8 +++- .../managers/NodeManagerCyclesTest.java | 40 ++++++++++++++++++- .../dowsing/objects/NodeProductionTest.java | 13 ++++++ 4 files changed, 82 insertions(+), 8 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 6a5826b..256d3ef 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -353,8 +353,9 @@ static NodeChunk at(Location loc) { * 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 * world ticking hoppers while nobody is online. It is saved with the world, so the first pass of each - * start lets go of every idle node's chunk, including those Dowsing 3.4 and older never let go; later - * passes only touch chunks this start forced. Waits for SimpleFactions, which says who owns a node. + * start lets go of the chunk of every idle node Dowsing loaded, including those Dowsing 3.4 and older + * never let go; spots of nodes removed before this version are not known and need a manual check. + * Later passes only touch chunks this start forced. Waits for SimpleFactions, which says who owns a node. */ static void holdNodeChunks() { if(!SimpleFactionsApi.ready()) return; @@ -367,17 +368,32 @@ static void holdNodeChunks() { else if(!startCleared) idle.add(chunk); } idle.removeAll(wanted); + Set failed = new HashSet<>(); for(NodeChunk chunk : wanted) { - if(!chunk.forced()) chunk.force(true); + if(!setForced(chunk, true)) failed.add(chunk); } for(NodeChunk chunk : idle) { - if(chunk.forced()) chunk.force(false); + // Kept in the set when it could not be let go, so the next pass tries again. + if(!setForced(chunk, false)) wanted.add(chunk); } + wanted.removeAll(failed); heldChunks.clear(); heldChunks.addAll(wanted); startCleared = true; } + /** 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 { + if(chunk.forced() != on) chunk.force(on); + return true; + } catch(RuntimeException ex) { + DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, + "Failed to " + (on ? "hold" : "let go of") + " node chunk " + chunk.x() + ", " + chunk.z(), ex); + return false; + } + } + /** * Lets go of a removed node's chunk right away, unless another producing node is in it, so the saved * force flag cannot outlive the node when the server stops before the next pass. @@ -388,8 +404,9 @@ public static void releaseChunkOf(Node removed) { for(Node n : nodes) { if(n != removed && chunk.equals(NodeChunk.of(n)) && producing(n)) return; } - heldChunks.remove(chunk); - if(chunk.forced()) chunk.force(false); + // Only a chunk Dowsing holds, or any node chunk before the first pass has cleared them; a staff + // force-load made later on an idle node's chunk is left alone. + if(heldChunks.remove(chunk) || !startCleared) setForced(chunk, false); } /** Forgets what this start held and cleared, for tests. */ diff --git a/src/main/java/net/tfminecraft/dowsing/objects/Node.java b/src/main/java/net/tfminecraft/dowsing/objects/Node.java index b8c1d23..0cdd59b 100644 --- a/src/main/java/net/tfminecraft/dowsing/objects/Node.java +++ b/src/main/java/net/tfminecraft/dowsing/objects/Node.java @@ -24,6 +24,7 @@ import dev.lone.itemsadder.api.CustomFurniture; import net.tfminecraft.dowsing.Cache; +import net.tfminecraft.dowsing.DowsingMain; import net.tfminecraft.dowsing.managers.NodeManager; import net.tfminecraft.dowsing.utils.Database; import net.tfminecraft.dowsing.utils.DropPaths; @@ -759,7 +760,6 @@ public void breakNode() { // Stale menus can repeat removal; the node item and held output must drop only once. if(this.broken) return; this.broken = true; - NodeManager.releaseChunkOf(this); String path = this.getBlock().getBlock(); String type = path.split("\\.")[0]; if(type.equalsIgnoreCase("v")) { @@ -786,6 +786,12 @@ public void breakNode() { dropper.dropItem(loc, path, false); loc.getWorld().playSound(loc, Sound.ENTITY_GLOW_ITEM_FRAME_REMOVE_ITEM, 0.5f, 1f); NodeManager.requestNodeBenefitSync(); + // Last, so a failure here cannot cost the node item or its held output. + try { + NodeManager.releaseChunkOf(this); + } catch(RuntimeException ex) { + DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to let go of node " + id + "'s chunk", ex); + } } private void removeNearbyFurniture() { diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index c015404..37e42ee 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -241,11 +241,49 @@ void aChunkLoadingFailureIsLoggedAndNodesStillProduce() { when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("world gone")); try (Cycles cycles = new Cycles()) { f.manager.start(); cycles.tasks.get(1200L).run(); - verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to update node chunk loading"), any(IllegalStateException.class)); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to hold node chunk 0, 0"), any(IllegalStateException.class)); verify(node).tick(); } } + @Test + void aFailureOutsideOneChunkIsLoggedAndThePassGoesOn() { + Node node = f.node; when(node.hasGuild()).thenThrow(new IllegalStateException("guild lookup failed")); + when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + try (Cycles cycles = new Cycles()) { + f.manager.start(); cycles.tasks.get(1200L).run(); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to update node chunk loading"), any(IllegalStateException.class)); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to process node"), any(IllegalStateException.class)); + } + } + + @Test + void aChunkThatFailsIsRetriedAndDoesNotStopTheOthers() { + Node first = f.nodeAt(f.location), second = f.nodeAt(new Location(f.world, 40, 64, -20)); + when(first.getIsActive()).thenReturn(true); when(second.getIsActive()).thenReturn(true); + NodeManager.nodes.addAll(List.of(first, second)); + when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("bad chunk")); + NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); + verify(f.world, atLeastOnce()).setChunkForceLoaded(2, -2, true); + verify(f.world, times(2)).isChunkForceLoaded(0, 0); + // A chunk that cannot be let go stays known and is tried again. + clearInvocations(f.world); + when(f.world.isChunkForceLoaded(2, -2)).thenThrow(new IllegalStateException("bad chunk")); + when(second.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); + verify(f.world, times(2)).isChunkForceLoaded(2, -2); + verify(f.logger, atLeastOnce()).log(eq(java.util.logging.Level.SEVERE), contains("Failed to let go of node chunk 2, -2"), any(IllegalStateException.class)); + } + + @Test + void aBrokenIdleNodeLeavesAStaffForceLoadAloneAfterTheFirstPass() { + Node idle = f.nodeAt(new Location(f.world, 40, 64, -20)); NodeManager.nodes.add(idle); + NodeManager.holdNodeChunks(); + when(f.world.isChunkForceLoaded(2, -2)).thenReturn(true); + NodeManager.releaseChunkOf(idle); + verify(f.world, never()).setChunkForceLoaded(2, -2, false); + } + @Test void aPassNeverLoadsAnIdleNodesChunkToValidateIt() { Node node = f.node; NodeManager.nodes.add(node); diff --git a/src/test/java/net/tfminecraft/dowsing/objects/NodeProductionTest.java b/src/test/java/net/tfminecraft/dowsing/objects/NodeProductionTest.java index 843b71d..7a91c91 100644 --- a/src/test/java/net/tfminecraft/dowsing/objects/NodeProductionTest.java +++ b/src/test/java/net/tfminecraft/dowsing/objects/NodeProductionTest.java @@ -210,6 +210,19 @@ void breakingAVanillaNodeClearsTheBlockAndReturnsItsItemAtTheBlockCenter() { } } + @Test + void breakingANodeStillReturnsItsItemWhenLettingGoOfItsChunkFails() { + Node node = f.node(); + Node neighbour = mock(Node.class); when(neighbour.getLoc()).thenReturn(f.location); + when(neighbour.getIsActive()).thenThrow(new IllegalStateException("guild lookup failed")); + net.tfminecraft.dowsing.managers.NodeManager.nodes.add(neighbour); + try (var droppers = mockConstruction(ItemDropper.class)) { + assertDoesNotThrow(node::breakNode); + verify(f.worldBlock).setType(Material.AIR); + verify(droppers.constructed().getFirst()).dropItem(new Location(f.world, 2.5, 64, 3.5), "v.IRON_BLOCK", false); + } + } + @Test void breakingANodeReturnsItsHeldOutputItemsOnlyOnce() { Node node = f.node(); node.setPendingResult(Map.of("v.STONE", 2)); From 474fa3ababae22e8a5c32830fb406257e82baec6 Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Thu, 19 Nov 2026 16:13:48 +0100 Subject: [PATCH 5/7] Keep a chunk tracked when its node or its flag cannot be checked CodeRabbit findings: - A node whose ownership check throws no longer stops the pass for every other node: it is logged, and its chunk keeps what it had (held stays held, never treated as idle). - A held chunk whose flag check fails stays tracked, so it is still let go once its node goes idle. - A broken node's chunk stays tracked until it is actually let go, so a failed release is retried by the next pass. - With every failure handled inside, the outer catch in the minute pass is gone. Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 51 +++++++++++++------ .../managers/NodeManagerCyclesTest.java | 46 +++++++++++++++-- 2 files changed, 77 insertions(+), 20 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 256d3ef..84fbee8 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -279,11 +279,8 @@ public void run() { if (!DowsingMain.plugin.nodesReady()) return; validate(); - try { - holdNodeChunks(); - } catch(RuntimeException ex) { - DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, "Failed to update node chunk loading", ex); - } + // Failures are handled per node and per chunk inside, so production below always runs. + holdNodeChunks(); for(Node n : nodes) { try { // Switched-off and unowned nodes wait, and a held realm's nodes pause until it is taken on. @@ -360,28 +357,49 @@ static NodeChunk at(Location loc) { static void holdNodeChunks() { if(!SimpleFactionsApi.ready()) return; Set wanted = new HashSet<>(); + Set unknown = new HashSet<>(); Set idle = new HashSet<>(heldChunks); for(Node n : nodes) { - NodeChunk chunk = NodeChunk.of(n); + NodeChunk chunk; + try { + chunk = NodeChunk.of(n); + } catch(RuntimeException ex) { + logChunkFailure("Failed to find node " + n.getId() + "'s chunk", ex); + continue; + } if(chunk == null) continue; - if(producing(n)) wanted.add(chunk); - else if(!startCleared) idle.add(chunk); + try { + if(producing(n)) wanted.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. + logChunkFailure("Failed to check node " + n.getId() + " for chunk loading", ex); + unknown.add(chunk); + } } idle.removeAll(wanted); - Set failed = new HashSet<>(); + idle.removeAll(unknown); + Set next = new HashSet<>(); for(NodeChunk chunk : wanted) { - if(!setForced(chunk, true)) failed.add(chunk); + // A held chunk that could not be checked stays held, so it is still let go once idle. + if(setForced(chunk, true) || heldChunks.contains(chunk)) next.add(chunk); } for(NodeChunk chunk : idle) { - // Kept in the set when it could not be let go, so the next pass tries again. - if(!setForced(chunk, false)) wanted.add(chunk); + // Kept when it could not be let go, so the next pass tries again. + if(!setForced(chunk, false)) next.add(chunk); + } + for(NodeChunk chunk : unknown) { + if(heldChunks.contains(chunk)) next.add(chunk); } - wanted.removeAll(failed); heldChunks.clear(); - heldChunks.addAll(wanted); + heldChunks.addAll(next); startCleared = true; } + private static void logChunkFailure(String message, RuntimeException ex) { + DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, message, ex); + } + /** 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 { @@ -406,7 +424,10 @@ public static void releaseChunkOf(Node removed) { } // Only a chunk Dowsing holds, or any node chunk before the first pass has cleared them; a staff // force-load made later on an idle node's chunk is left alone. - if(heldChunks.remove(chunk) || !startCleared) setForced(chunk, false); + if(!heldChunks.contains(chunk) && startCleared) return; + // Tracked until it is let go, so a failed release is tried again by the next pass. + if(setForced(chunk, false)) heldChunks.remove(chunk); + else heldChunks.add(chunk); } /** Forgets what this start held and cleared, for tests. */ diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index 37e42ee..fea8358 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -247,14 +247,50 @@ void aChunkLoadingFailureIsLoggedAndNodesStillProduce() { } @Test - void aFailureOutsideOneChunkIsLoggedAndThePassGoesOn() { - Node node = f.node; when(node.hasGuild()).thenThrow(new IllegalStateException("guild lookup failed")); - when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + void aNodeThatCannotBeCheckedKeepsItsChunkAndTheOthersGoOn() { + Node broken = f.nodeAt(f.location), other = f.nodeAt(new Location(f.world, 40, 64, -20)); + when(broken.getIsActive()).thenReturn(true); NodeManager.nodes.add(broken); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + when(broken.hasGuild()).thenThrow(new IllegalStateException("guild lookup failed")); + when(other.getIsActive()).thenReturn(true); NodeManager.nodes.add(other); try (Cycles cycles = new Cycles()) { f.manager.start(); cycles.tasks.get(1200L).run(); - verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to update node chunk loading"), any(IllegalStateException.class)); - verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to process node"), any(IllegalStateException.class)); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("for chunk loading"), any(IllegalStateException.class)); + verify(f.world).setChunkForceLoaded(2, -2, true); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); } + // A node whose location cannot be read is skipped and logged. + Node lost = f.nodeAt(f.location); when(lost.getLoc()).thenThrow(new IllegalStateException("no location")); NodeManager.nodes.add(lost); + NodeManager.holdNodeChunks(); NodeManager.nodes.remove(lost); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to find node"), any(IllegalStateException.class)); + // Still tracked: once it can be checked again and is idle, it is let go. + doReturn(true).when(broken).hasGuild(); when(broken.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + + @Test + void aHeldChunkWhoseCheckFailsStaysTrackedAndIsLetGoLater() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + NodeManager.holdNodeChunks(); + when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("bad chunk")); + NodeManager.holdNodeChunks(); + doReturn(true).when(f.world).isChunkForceLoaded(0, 0); when(node.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + + @Test + void aFailedReleaseOfABrokenNodesChunkIsRetriedByTheNextPass() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + NodeManager.holdNodeChunks(); + when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("bad chunk")); + NodeManager.releaseChunkOf(node); NodeManager.nodes.remove(node); + doReturn(true).when(f.world).isChunkForceLoaded(0, 0); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); } @Test From eb904240efd668d0ee8f84cbefafe455481a3103 Mon Sep 17 00:00:00 2001 From: XxFran10xX Date: Thu, 19 Nov 2026 16:19:29 +0100 Subject: [PATCH 6/7] Track first-pass failures and keep held chunks when a location cannot be read CodeRabbit follow-up on the classification thread: - On the first pass of a start, a chunk whose node cannot be checked, or whose flag could not be set, is tracked anyway, so a later pass can still let go of a flag an earlier start left on it. - In a pass where a node's location cannot be read, no held chunk is let go (that node may be in any of them); they stay tracked for the next pass. - validate() handles each node on its own, so one node that cannot be checked does not stop the others or the minute pass. Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 34 ++++++++++++----- .../managers/NodeManagerCyclesTest.java | 37 +++++++++++++++++++ 2 files changed, 62 insertions(+), 9 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 84fbee8..2644b49 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -359,12 +359,14 @@ static void holdNodeChunks() { Set wanted = new HashSet<>(); Set unknown = new HashSet<>(); Set idle = new HashSet<>(heldChunks); + boolean lookupFailed = false; for(Node n : nodes) { NodeChunk chunk; try { chunk = NodeChunk.of(n); } catch(RuntimeException ex) { logChunkFailure("Failed to find node " + n.getId() + "'s chunk", ex); + lookupFailed = true; continue; } if(chunk == null) continue; @@ -380,16 +382,25 @@ static void holdNodeChunks() { idle.removeAll(wanted); idle.removeAll(unknown); Set next = new HashSet<>(); + if(lookupFailed) { + // A node whose chunk is unknown may be in any held chunk: none is let go this pass. + for(NodeChunk chunk : heldChunks) { + if(idle.remove(chunk)) next.add(chunk); + } + } + // On the first pass a chunk that could not be handled is tracked anyway, so a later pass can still + // let go of a flag an earlier start left on it. + boolean keepAll = !startCleared; for(NodeChunk chunk : wanted) { // A held chunk that could not be checked stays held, so it is still let go once idle. - if(setForced(chunk, true) || heldChunks.contains(chunk)) next.add(chunk); + if(setForced(chunk, true) || keepAll || heldChunks.contains(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); } for(NodeChunk chunk : unknown) { - if(heldChunks.contains(chunk)) next.add(chunk); + if(keepAll || heldChunks.contains(chunk)) next.add(chunk); } heldChunks.clear(); heldChunks.addAll(next); @@ -493,13 +504,18 @@ public void validate() { if (!SimpleFactionsApi.ready()) return; for(int i = 0; i Date: Thu, 19 Nov 2026 16:24:23 +0100 Subject: [PATCH 7/7] Let nothing go in a pass where a node's location cannot be read CodeRabbit follow-up: in a pass where a node's location lookup fails, no chunk is let go at all (that node may share any of them, including first-pass idle candidates), held chunks stay tracked, and the first pass's clean-up of old force flags waits for a pass that knows every node's chunk. Co-Authored-By: Claude Opus 5.5 --- .../dowsing/managers/NodeManager.java | 10 ++++++---- .../dowsing/managers/NodeManagerCyclesTest.java | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 2644b49..d4aae5a 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -383,10 +383,12 @@ static void holdNodeChunks() { idle.removeAll(unknown); Set next = new HashSet<>(); if(lookupFailed) { - // A node whose chunk is unknown may be in any held chunk: none is let go this pass. - for(NodeChunk chunk : heldChunks) { - if(idle.remove(chunk)) next.add(chunk); + // A node whose chunk is unknown may be in any of them: nothing is let go this pass. Held + // chunks stay tracked, and the first pass's clean-up waits for a pass that knows every chunk. + for(NodeChunk chunk : idle) { + if(heldChunks.contains(chunk)) next.add(chunk); } + idle.clear(); } // On the first pass a chunk that could not be handled is tracked anyway, so a later pass can still // let go of a flag an earlier start left on it. @@ -404,7 +406,7 @@ static void holdNodeChunks() { } heldChunks.clear(); heldChunks.addAll(next); - startCleared = true; + if(!lookupFailed) startCleared = true; } private static void logChunkFailure(String message, RuntimeException ex) { diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index 1712377..6cf1b29 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -297,6 +297,22 @@ void noHeldChunkIsLetGoInAPassWhereANodesLocationCannotBeRead() { verify(f.world).setChunkForceLoaded(0, 0, false); } + @Test + void aFirstPassWithAnUnreadableLocationLetsNothingGoAndCleansUpLater() { + Node producing = f.nodeAt(f.location), idle = f.nodeAt(f.location); + when(producing.getIsActive()).thenReturn(true); + when(producing.getLoc()).thenThrow(new IllegalStateException("no location")); + NodeManager.nodes.addAll(List.of(producing, idle)); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + // The idle node shares the chunk of the node whose location cannot be read: not let go. + NodeManager.holdNodeChunks(); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); + // The first-pass clean-up still runs once every location reads. + doReturn(f.location).when(producing).getLoc(); when(producing.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + @Test void aNodeThatFailsValidationDoesNotStopTheOthers() { Node lost = f.nodeAt(f.location), invalid = f.nodeAt(f.location);