From 0db9fc64d8401c9c6ae7a3099f342262c0e3e1b2 Mon Sep 17 00:00:00 2001 From: XxFran10xX <318299142+XxFran10xX@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:23:26 +0100 Subject: [PATCH 1/2] perf: guild menu previews no longer read tax contributors Income previews captured every guild's held-tax contributors, which the ledger answers from each tax credit since the last settlement, though no income reads them. An idle guild's menu open and its repaint now also share the background flood's reads instead of capturing up to three times. Co-Authored-By: Claude Opus 5.5 --- .../simplefactions/economy/FrozenReads.java | 34 ++++--- .../guild/income/BranchIncomePreview.java | 14 +-- .../managers/ProvinceManager.java | 5 ++ .../managers/inventory/GuildView.java | 51 ++++++++--- .../economy/FrozenReadsTest.java | 21 +++-- .../guild/income/BranchIncomePreviewTest.java | 21 +++++ .../ProvinceManagerHubTransportTest.java | 1 + .../inventory/GuildMenusCoverageTest.java | 89 ++++++++++++++++++- 8 files changed, 196 insertions(+), 40 deletions(-) diff --git a/src/main/java/net/tfminecraft/simplefactions/economy/FrozenReads.java b/src/main/java/net/tfminecraft/simplefactions/economy/FrozenReads.java index 3a6653f9..3a28b288 100644 --- a/src/main/java/net/tfminecraft/simplefactions/economy/FrozenReads.java +++ b/src/main/java/net/tfminecraft/simplefactions/economy/FrozenReads.java @@ -21,25 +21,27 @@ * Guild treasuries, held tax, node upkeep, espionage stability and inactive members read once * on the main thread. DenarEconomy, Dowsing and TLibs character identity refuse reads from * other threads, so income previews that run async read these instead. + * + *

Whose earnings the held tax came from is not captured: no income reads it, and the ledger + * answers it from every tax credit since the last settlement (about 0.65 s a minute on Main). */ public final class FrozenReads { private static final ThreadLocal CURRENT = new ThreadLocal<>(); private final Map cents; - private final Map> taxContributors; private final Map nodeUpkeep; private final Map> espionage; private final Set inactive; + private final long capturedAt; private FrozenReads( - Map cents, Map> taxContributors, - Map nodeUpkeep, Map> espionage, - Set inactive) { + Map cents, Map nodeUpkeep, + Map> espionage, Set inactive, long capturedAt) { this.cents = Map.copyOf(cents); - this.taxContributors = Map.copyOf(taxContributors); this.nodeUpkeep = Map.copyOf(nodeUpkeep); this.espionage = Map.copyOf(espionage); this.inactive = Set.copyOf(inactive); + this.capturedAt = capturedAt; } /** @@ -60,7 +62,6 @@ public static FrozenReads capture() { } } Map cents = new HashMap<>(); - Map> taxContributors = new HashMap<>(); Map nodeUpkeep = new HashMap<>(); for (Guild guild : FactionManager.getAllGuilds()) { Bank bank = guild == null ? null : guild.getBank(); @@ -72,13 +73,17 @@ public static FrozenReads capture() { if (incarnation != null) { String taxAccount = Denars.guildTax(incarnation); cents.put(taxAccount, Denars.balance(taxAccount)); - taxContributors.put(incarnation, Map.copyOf(Denars.taxContributors(incarnation))); nodeUpkeep.put(incarnation, Ledger.liveNodeUpkeep(guild)); } } // Member shares (stability, upkeep) skip inactive members; whether one is online asks TLibs. Set inactive = InactivityService.captureInactiveMembers(); - return new FrozenReads(cents, taxContributors, nodeUpkeep, espionage, inactive); + return new FrozenReads(cents, nodeUpkeep, espionage, inactive, now); + } + + /** When these reads were taken, in epoch milliseconds. */ + public long capturedAt() { + return capturedAt; } /** Runs the work with these reads standing in for the live state on this thread. */ @@ -105,12 +110,17 @@ public static long balance(String account) { return Denars.balance(account); } - /** Held tax by earning character, frozen with the balance for async previews and settlement. */ + /** + * Held tax by earning character, for the ledger menu and settlement. Always live. + * + * @throws IllegalStateException inside {@link #read}, which does not capture it + */ public static Map taxContributors(UUID incarnation) { if (incarnation == null) return Map.of(); - FrozenReads current = CURRENT.get(); - return current == null ? Denars.taxContributors(incarnation) - : current.taxContributors.getOrDefault(incarnation, Map.of()); + if (CURRENT.get() != null) { + throw new IllegalStateException("Tax contributors are not captured for previews"); + } + return Denars.taxContributors(incarnation); } /** The frozen node upkeep inside {@link #read}, otherwise the live upkeep. */ diff --git a/src/main/java/net/tfminecraft/simplefactions/guild/income/BranchIncomePreview.java b/src/main/java/net/tfminecraft/simplefactions/guild/income/BranchIncomePreview.java index 78a0f1a7..bcc4bc09 100644 --- a/src/main/java/net/tfminecraft/simplefactions/guild/income/BranchIncomePreview.java +++ b/src/main/java/net/tfminecraft/simplefactions/guild/income/BranchIncomePreview.java @@ -32,12 +32,13 @@ private BranchIncomePreview() {} public static final class Prepared { private final ProvinceManager snapshot; - private final FrozenReads reads = FrozenReads.capture(); + private final FrozenReads reads; private final long inputs = TradeInputs.fingerprint(); private final Map estimates = new ConcurrentHashMap<>(); - private Prepared(ProvinceManager snapshot) { + private Prepared(ProvinceManager snapshot, FrozenReads reads) { this.snapshot = snapshot; + this.reads = reads; } /** Main-thread state as it was when this copy was made, for work off the main thread. */ @@ -96,9 +97,12 @@ public static boolean current(Prepared prepared) { /** Copy province trade data once. Later estimates only read this copy. */ public static Prepared prepare(ProvinceManager live) { - ProvinceManager snapshot = live.createSnapshotShell(); - snapshot.copyAllDataFrom(live); - return new Prepared(snapshot); + return prepare(live, FrozenReads.capture()); + } + + /** As {@link #prepare(ProvinceManager)}, with reads a flood of the same trade already captured. */ + public static Prepared prepare(ProvinceManager live, FrozenReads reads) { + return new Prepared(copy(live), reads); } public static double estimate(ProvinceManager live, Guild guild, Branch branch, int levelDelta) { diff --git a/src/main/java/net/tfminecraft/simplefactions/managers/ProvinceManager.java b/src/main/java/net/tfminecraft/simplefactions/managers/ProvinceManager.java index 9df498ec..32d59cc8 100644 --- a/src/main/java/net/tfminecraft/simplefactions/managers/ProvinceManager.java +++ b/src/main/java/net/tfminecraft/simplefactions/managers/ProvinceManager.java @@ -228,6 +228,11 @@ private BackgroundFlood(ProvinceManager live) { version = live.stateVersion; } + /** Main-thread state as it was when this flood was prepared; its trade comes from it. */ + public FrozenReads reads() { + return reads; + } + /** Stops a run that is no longer wanted at the next guild; it then never adopts. */ public void cancel() { cancelled = true; diff --git a/src/main/java/net/tfminecraft/simplefactions/managers/inventory/GuildView.java b/src/main/java/net/tfminecraft/simplefactions/managers/inventory/GuildView.java index e9510c91..d193a6b1 100644 --- a/src/main/java/net/tfminecraft/simplefactions/managers/inventory/GuildView.java +++ b/src/main/java/net/tfminecraft/simplefactions/managers/inventory/GuildView.java @@ -19,6 +19,7 @@ import org.bukkit.persistence.PersistentDataType; import net.tfminecraft.simplefactions.Cache; +import net.tfminecraft.simplefactions.economy.FrozenReads; import net.tfminecraft.simplefactions.guild.branch.Branch; import net.tfminecraft.simplefactions.guild.income.BranchIncomePreview; import net.tfminecraft.simplefactions.guild.Guild; @@ -51,6 +52,8 @@ private record SharedPreview(ProvinceManager manager, BranchIncomePreview.Prepar private static final long PREVIEW_TTL_MS = 30_000; private static final long RECALC_DELAY_TICKS = 20; private SharedPreview preview; + /** Reads of the flood this paint started or installed, for a preview copy made in the same paint. */ + private FrozenReads floodReads; private org.bukkit.scheduler.BukkitTask pendingRecalc; private long recalcRuns; /** The run whose background flood is in flight, or 0. */ @@ -138,7 +141,10 @@ private BranchIncomePreview.Prepared tradePreview() { long now = System.currentTimeMillis(); if (preview == null || preview.manager() != manager || now - preview.at() > PREVIEW_TTL_MS || !BranchIncomePreview.current(preview.prepared())) { - preview = new SharedPreview(manager, BranchIncomePreview.prepare(manager), now); + // Reads a flood took stand in for a second capture; the copy ages from when they were taken. + preview = floodReads == null + ? new SharedPreview(manager, BranchIncomePreview.prepare(manager), now) + : new SharedPreview(manager, BranchIncomePreview.prepare(manager, floodReads), floodReads.capturedAt()); } return preview.prepared(); } @@ -164,11 +170,14 @@ private void recalculateAfterClicks(Guild guild) { /** * One full recalculation off the server thread for a menu just opened, then menus showing the * guild repaint. Joins a recalculation that is already waiting or running. + * + * @return the reads of the flood started now, or null when none was */ - private void refreshInBackground(Guild guild) { + private FrozenReads refreshInBackground(Guild guild) { pendingRepaint.add(guild.getId()); - if (pendingRecalc != null || (floodingRun != 0 && floodingRun == recalcRuns)) return; + if (pendingRecalc != null || (floodingRun != 0 && floodingRun == recalcRuns)) return null; floodInBackground(++recalcRuns, true); + return flooding == null ? null : flooding.reads(); } /** @@ -186,7 +195,7 @@ private void floodInBackground(long run, boolean retry) { floodingRun = 0; flooding = null; live.recalculate(); - repaintAfterRecalc(); + repaintAfterRecalc(null); return; } floodingRun = run; @@ -215,16 +224,33 @@ private void floodInBackground(long run, boolean retry) { return; } live.recalculate(); + repaintAfterRecalc(null); + return; } - repaintAfterRecalc(); + repaintAfterRecalc(flood.reads()); }); }); } - private void repaintAfterRecalc() { + /** {@code reads} are those the installed trade was computed from, or null to capture them again. */ + private void repaintAfterRecalc(FrozenReads reads) { java.util.Set guilds = new java.util.HashSet<>(pendingRepaint); pendingRepaint.clear(); preview = null; + paintWith(reads, () -> repaint(guilds)); + } + + private void paintWith(FrozenReads reads, Runnable paint) { + FrozenReads outer = floodReads; + floodReads = reads; + try { + paint.run(); + } finally { + floodReads = outer; + } + } + + private void repaint(java.util.Set guilds) { for (Player viewer : org.bukkit.Bukkit.getOnlinePlayers()) { Inventory top = viewer.getOpenInventory().getTopInventory(); if (!(top.getHolder(false) instanceof SFInventoryHolder holder) || holder.getType() != SFGUI.GUILD_VIEW) continue; @@ -353,18 +379,17 @@ public void guildView(Player player, Guild guild, Inventory i, boolean refreshId return; } if(manager == null) setProvinceManager(SimpleFactions.getInstance().getProvinceManager()); - if(guild.hasCapital()) { - // Trade a guild with no income may be stale, and movement power, civil war and pillage - // read it too. Refresh it off the server thread; the menus repaint when it lands. - if(refreshIdleTrade && guild.getTradeBreakdown().getIncome() == 0) refreshInBackground(guild); - manager.getIncome(guild); - } + // Trade a guild with no income may be stale, and movement power, civil war and pillage + // read it too. Refresh it off the server thread; the menus repaint when it lands. + boolean idle = refreshIdleTrade && guild.hasCapital() && guild.getTradeBreakdown().getIncome() == 0; + FrozenReads reads = idle ? refreshInBackground(guild) : floodReads; + if(guild.hasCapital()) manager.getIncome(guild); manager.recalculateIfNeeded(); // The menu only reads, but its items ask every guild's net income (the trade breakdown // ranks all guilds), and each answer read treasuries from SQLite many times over: about // 185 ms per redraw on Dev. One answer per treasury and one stability report per faction // hold for one render, as for the chronicle export. - withReadMemos(() -> render(player, guild, i)); + paintWith(reads, () -> withReadMemos(() -> render(player, guild, i))); } private static void withReadMemos(Runnable reads) { diff --git a/src/test/java/net/tfminecraft/simplefactions/economy/FrozenReadsTest.java b/src/test/java/net/tfminecraft/simplefactions/economy/FrozenReadsTest.java index 6bdea968..592731f6 100644 --- a/src/test/java/net/tfminecraft/simplefactions/economy/FrozenReadsTest.java +++ b/src/test/java/net/tfminecraft/simplefactions/economy/FrozenReadsTest.java @@ -3,11 +3,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import java.time.Instant; @@ -52,9 +54,7 @@ class FrozenReadsTest { private Guild guild; private org.mockito.MockedStatic mockDenars() { - var denars = mockStatic(Denars.class, CALLS_REAL_METHODS); - denars.when(() -> Denars.taxContributors(any())).thenReturn(Map.of()); - return denars; + return mockStatic(Denars.class, CALLS_REAL_METHODS); } @BeforeEach @@ -89,7 +89,6 @@ void asyncReadsUseBalancesCapturedOnTheMainThread() throws Exception { // Static mocks stay on the test thread, so only the frozen balance can give the worker 12.34. assertEquals(12.34, CompletableFuture.supplyAsync(() -> frozen.read(() -> guild.getBank().getWealth())).get()); assertEquals(0L, frozen.read(() -> FrozenReads.balance("unknown"))); - assertEquals(Map.of(), frozen.read(() -> FrozenReads.taxContributors(UUID.randomUUID()))); assertEquals(Map.of(), FrozenReads.taxContributors(null)); } @@ -101,21 +100,25 @@ void asyncCitizenTaxUsesTheHoldingBalanceCapturedOnTheMainThread() throws Except String holding = Denars.guildTax(guild.getIncarnationId()); FrozenReads frozen; UUID contributor = UUID.randomUUID(); - var contributors = new java.util.HashMap<>(Map.of(contributor, 1000L)); + long before = System.currentTimeMillis(); try (var denars = mockDenars()) { denars.when(() -> Denars.balance(anyString())).thenReturn(0L); denars.when(() -> Denars.balance(holding)).thenReturn(1234L); - denars.when(() -> Denars.taxContributors(guild.getIncarnationId())).thenReturn(contributors); + denars.when(() -> Denars.taxContributors(guild.getIncarnationId())).thenReturn(Map.of(contributor, 2000L)); frozen = FrozenReads.capture(); + // No income reads the names, and each guild's cost a scan of its held tax credits. + denars.verify(() -> Denars.taxContributors(any()), never()); denars.when(() -> Denars.balance(holding)).thenReturn(5000L); - contributors.put(contributor, 2000L); assertEquals(50.0, ledger.getIncome(Cashflow.CITIZENS)); assertEquals(Map.of(contributor.toString(), 20.0, "Other citizen taxes", 30.0), ledger.getCitizenTaxBreakdown()); } assertEquals(12.34, CompletableFuture.supplyAsync(() -> frozen.read(() -> ledger.getIncome(Cashflow.CITIZENS))).get()); - assertEquals(Map.of(contributor.toString(), 10.0, "Other citizen taxes", 2.34), CompletableFuture - .supplyAsync(() -> frozen.read(ledger::getCitizenTaxBreakdown)).get()); + // The names stay live-only: a preview asking for them fails instead of reading the ledger off-thread. + ExecutionException names = assertThrows(ExecutionException.class, + () -> CompletableFuture.supplyAsync(() -> frozen.read(ledger::getCitizenTaxBreakdown)).get()); + assertInstanceOf(IllegalStateException.class, names.getCause()); + assertTrue(frozen.capturedAt() >= before); } @Test diff --git a/src/test/java/net/tfminecraft/simplefactions/guild/income/BranchIncomePreviewTest.java b/src/test/java/net/tfminecraft/simplefactions/guild/income/BranchIncomePreviewTest.java index c172f77d..fc6942d8 100644 --- a/src/test/java/net/tfminecraft/simplefactions/guild/income/BranchIncomePreviewTest.java +++ b/src/test/java/net/tfminecraft/simplefactions/guild/income/BranchIncomePreviewTest.java @@ -1,6 +1,7 @@ package net.tfminecraft.simplefactions.guild.income; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -23,6 +24,7 @@ import org.junit.jupiter.api.Test; import net.tfminecraft.simplefactions.Cache; +import net.tfminecraft.simplefactions.economy.FrozenReads; import net.tfminecraft.simplefactions.enums.GuildModifier; import net.tfminecraft.simplefactions.enums.Terrain; import net.tfminecraft.simplefactions.government.proposal.TaxTarget; @@ -113,6 +115,25 @@ void upgradeAndDowngradeKeepLiveStateAndMoveIncome() { verify(guild, never()).getTradeBreakdown(); } + @Test + void aCopyMadeWithAFloodsReadsGivesTheSameEstimates() { + FrozenReads reads = FrozenReads.capture(); + BranchIncomePreview.Prepared shared = BranchIncomePreview.prepare(live, reads); + BranchIncomePreview.Prepared own = BranchIncomePreview.prepare(live); + Map current = BranchIncomePreview.modifiers(guild); + + assertSame(reads, shared.reads()); + assertTrue(BranchIncomePreview.current(shared)); + for (int delta : new int[] {1, -1}) { + Map changed = BranchIncomePreview.adjust(current, branch, branch.getLevel(), delta); + BranchIncomePreview.Estimate expected = own.reads().read( + () -> BranchIncomePreview.estimate(own, guild, current, changed)); + assertTrue(expected.own() != 0); + assertEquals(expected, shared.reads().read( + () -> BranchIncomePreview.estimate(shared, guild, current, changed))); + } + } + @Test void guildTaxMovesIncomeToTheTreasuryWithoutChangingTheRealmTotal() { BranchIncomePreview.Prepared prepared = BranchIncomePreview.prepare(live); diff --git a/src/test/java/net/tfminecraft/simplefactions/managers/ProvinceManagerHubTransportTest.java b/src/test/java/net/tfminecraft/simplefactions/managers/ProvinceManagerHubTransportTest.java index 94201cb0..d5590a6d 100644 --- a/src/test/java/net/tfminecraft/simplefactions/managers/ProvinceManagerHubTransportTest.java +++ b/src/test/java/net/tfminecraft/simplefactions/managers/ProvinceManagerHubTransportTest.java @@ -178,6 +178,7 @@ void backgroundFloodInstallsTheSameTradeAsTheServerThreadFlood() { ProvinceManager.BackgroundFlood flood = provinces.prepareBackgroundFlood(); flood.run(); + org.junit.jupiter.api.Assertions.assertNotNull(flood.reads()); assertEquals(0, trade(22)); assertTrue(provinces.adopt(flood)); assertEquals(8, trade(22), 1e-9); diff --git a/src/test/java/net/tfminecraft/simplefactions/managers/inventory/GuildMenusCoverageTest.java b/src/test/java/net/tfminecraft/simplefactions/managers/inventory/GuildMenusCoverageTest.java index ff00f3b7..3aad13f4 100644 --- a/src/test/java/net/tfminecraft/simplefactions/managers/inventory/GuildMenusCoverageTest.java +++ b/src/test/java/net/tfminecraft/simplefactions/managers/inventory/GuildMenusCoverageTest.java @@ -99,6 +99,7 @@ class GuildMenusCoverageTest { private MockedStatic intelligence; private MockedStatic access; private MockedStatic reported; + private MockedStatic previews; private MockedStatic previewTasks; private final List> scopes = new ArrayList<>(); private HashMap oldRanking; @@ -167,7 +168,7 @@ void setUp() { creator = view.creator; ranker = mock(FactionRanker.class); creator.r = ranker; - scoped(BranchIncomePreview.class); + previews = scoped(BranchIncomePreview.class); previewTasks = scoped(BranchIncomePreviewService.class); } @@ -303,6 +304,92 @@ void aBackgroundFloodOutdatedOnArrivalFloodsOnceMoreThenRepaintsOnlyThatGuildsMe verify(view, never()).guildView(eq(lister), any(), any(Inventory.class), anyBoolean()); } + @Test + void anIdleOpenAndItsRepaintShareTheFloodsReads() { + Guild display = idleMenu(); + var reads = floodReads(System.currentTimeMillis()); + var flood = flood(reads); + when(fixture.provinces.adopt(flood)).thenReturn(true); + stubPreviews(reads); + + view.guildView(fixture.player, display); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces, reads), times(1)); + fixture.ui.runAsyncTasks(); + fixture.ui.runTasks(); + // The trade changed, so it is copied again, but nothing is captured again. + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces, reads), times(2)); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces), never()); + verify(fixture.provinces, times(1)).prepareBackgroundFlood(); + + Inventory menu = fixture.player.getOpenInventory().getTopInventory(); + view.guildView(fixture.player, display, menu, false); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces, reads), times(2)); + // Changed trade inputs outside a flood still capture afresh. + when(BranchIncomePreview.current(any())).thenReturn(false); + view.guildView(fixture.player, display, menu, false); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces), times(1)); + } + + @Test + void aRefusedFloodsReadsAreNotUsedForTheRepaint() { + Guild display = idleMenu(); + var reads = floodReads(System.currentTimeMillis()); + flood(reads); + stubPreviews(reads); + + view.guildView(fixture.player, display); + for (int i = 0; i < 2; i++) { + fixture.ui.runAsyncTasks(); + fixture.ui.runTasks(); + } + verify(fixture.provinces).recalculate(); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces, reads), times(1)); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces), times(1)); + } + + @Test + void aCopyMadeWithAFloodsReadsExpiresFromWhenTheyWereTaken() { + Guild display = idleMenu(); + var reads = floodReads(System.currentTimeMillis() - 31_000); + flood(reads); + stubPreviews(reads); + + view.guildView(fixture.player, display); + view.guildView(fixture.player, display, fixture.player.getOpenInventory().getTopInventory(), false); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces, reads), times(1)); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces), times(1)); + } + + private Guild idleMenu() { + Guild display = displayGuild(guild); + fixture.factions.when(() -> FactionManager.getGuildByString("merchants")).thenReturn(display); + fixture.ui.online(fixture.player); + when(fixture.ui.plugin.isEnabled()).thenReturn(true); + return display; + } + + private net.tfminecraft.simplefactions.economy.FrozenReads floodReads(long at) { + var reads = mock(net.tfminecraft.simplefactions.economy.FrozenReads.class); + when(reads.capturedAt()).thenReturn(at); + return reads; + } + + private net.tfminecraft.simplefactions.managers.ProvinceManager.BackgroundFlood flood( + net.tfminecraft.simplefactions.economy.FrozenReads reads) { + var flood = mock(net.tfminecraft.simplefactions.managers.ProvinceManager.BackgroundFlood.class); + when(flood.reads()).thenReturn(reads); + when(fixture.provinces.prepareBackgroundFlood()).thenReturn(flood); + return flood; + } + + private void stubPreviews(net.tfminecraft.simplefactions.economy.FrozenReads reads) { + var prepared = mock(BranchIncomePreview.Prepared.class); + when(BranchIncomePreview.prepare(fixture.provinces, reads)).thenReturn(prepared); + when(BranchIncomePreview.prepare(fixture.provinces)).thenReturn(prepared); + when(BranchIncomePreview.current(prepared)).thenReturn(true); + previews.clearInvocations(); + } + @Test void aNewerClickCancelsTheFloodStillRunning() { net.tfminecraft.simplefactions.managers.ProvinceManager.BackgroundFlood flood = mock(net.tfminecraft.simplefactions.managers.ProvinceManager.BackgroundFlood.class); From 3e11c7971d3554438faa1792046644be3b14321f Mon Sep 17 00:00:00 2001 From: XxFran10xX <318299142+XxFran10xX@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:08:40 +0100 Subject: [PATCH 2/2] fix: capture afresh when a flood outlasts the guild menu preview Co-Authored-By: Claude Opus 5.5 --- .../managers/inventory/GuildView.java | 9 +++-- .../inventory/GuildMenusCoverageTest.java | 35 +++++++++++++++++-- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/tfminecraft/simplefactions/managers/inventory/GuildView.java b/src/main/java/net/tfminecraft/simplefactions/managers/inventory/GuildView.java index d193a6b1..231f27be 100644 --- a/src/main/java/net/tfminecraft/simplefactions/managers/inventory/GuildView.java +++ b/src/main/java/net/tfminecraft/simplefactions/managers/inventory/GuildView.java @@ -54,6 +54,8 @@ private record SharedPreview(ProvinceManager manager, BranchIncomePreview.Prepar private SharedPreview preview; /** Reads of the flood this paint started or installed, for a preview copy made in the same paint. */ private FrozenReads floodReads; + /** Replaced by tests that outlast a preview. */ + java.util.function.LongSupplier clock = System::currentTimeMillis; private org.bukkit.scheduler.BukkitTask pendingRecalc; private long recalcRuns; /** The run whose background flood is in flight, or 0. */ @@ -138,11 +140,12 @@ private void paintBranches(Player player, Guild guild, Inventory i) { /** Province copy shared by branch previews until the next full recalculation, or for a short while. */ private BranchIncomePreview.Prepared tradePreview() { - long now = System.currentTimeMillis(); + long now = clock.getAsLong(); if (preview == null || preview.manager() != manager || now - preview.at() > PREVIEW_TTL_MS || !BranchIncomePreview.current(preview.prepared())) { - // Reads a flood took stand in for a second capture; the copy ages from when they were taken. - preview = floodReads == null + // Reads a flood took stand in for a second capture while they are still fresh; the copy + // ages from when they were taken. + preview = floodReads == null || now - floodReads.capturedAt() > PREVIEW_TTL_MS ? new SharedPreview(manager, BranchIncomePreview.prepare(manager), now) : new SharedPreview(manager, BranchIncomePreview.prepare(manager, floodReads), floodReads.capturedAt()); } diff --git a/src/test/java/net/tfminecraft/simplefactions/managers/inventory/GuildMenusCoverageTest.java b/src/test/java/net/tfminecraft/simplefactions/managers/inventory/GuildMenusCoverageTest.java index 3aad13f4..9d00a867 100644 --- a/src/test/java/net/tfminecraft/simplefactions/managers/inventory/GuildMenusCoverageTest.java +++ b/src/test/java/net/tfminecraft/simplefactions/managers/inventory/GuildMenusCoverageTest.java @@ -350,16 +350,47 @@ void aRefusedFloodsReadsAreNotUsedForTheRepaint() { @Test void aCopyMadeWithAFloodsReadsExpiresFromWhenTheyWereTaken() { Guild display = idleMenu(); - var reads = floodReads(System.currentTimeMillis() - 31_000); + long[] now = {1_000_000}; + view.clock = () -> now[0]; + var reads = floodReads(now[0] - 10_000); flood(reads); stubPreviews(reads); view.guildView(fixture.player, display); - view.guildView(fixture.player, display, fixture.player.getOpenInventory().getTopInventory(), false); + Inventory menu = fixture.player.getOpenInventory().getTopInventory(); + now[0] += 20_000; + view.guildView(fixture.player, display, menu, false); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces), never()); + now[0] += 1; + view.guildView(fixture.player, display, menu, false); previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces, reads), times(1)); previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces), times(1)); } + @ParameterizedTest + @ValueSource(longs = {30_000, 30_001}) + void aDelayedFloodsReadsPaintOnlyWhileTheyAreFresh(long delay) { + Guild display = idleMenu(); + long[] now = {1_000_000}; + view.clock = () -> now[0]; + var reads = floodReads(now[0]); + var flood = flood(reads); + when(fixture.provinces.adopt(flood)).thenReturn(true); + stubPreviews(reads); + + view.guildView(fixture.player, display); + now[0] += delay; + fixture.ui.runAsyncTasks(); + fixture.ui.runTasks(); + boolean fresh = delay == 30_000; + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces, reads), times(fresh ? 2 : 1)); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces), times(fresh ? 0 : 1)); + // A capture made in place of expired reads starts its own 30 s, so the next paint reuses it. + Inventory menu = fixture.player.getOpenInventory().getTopInventory(); + view.guildView(fixture.player, display, menu, false); + previews.verify(() -> BranchIncomePreview.prepare(fixture.provinces), times(fresh ? 0 : 1)); + } + private Guild idleMenu() { Guild display = displayGuild(guild); fixture.factions.when(() -> FactionManager.getGuildByString("merchants")).thenReturn(display);