Fix deferred player lookups retaining disconnected sessions (#265)

This commit is contained in:
RonanCraft authored and GitHub committed 2026-11-18 16:37:14 -05:00
1 parent 04309fba14
commit 76fc1ffe9b
15 files changed
+392 -97

No files matched your search

+4 -1
View File
@@ -7,7 +7,7 @@
<groupId>me.SuperRonanCraft</groupId>
<artifactId>BetterRTP</artifactId>
<packaging>jar</packaging>
<version>3.6.13</version>
<version>3.6.14</version>
<!-- Upload patches to https://repo.ronanplugins.com/#/ -->
@@ -212,6 +212,9 @@
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope>
</dependency>
<!-- Download the tagged GitHub library through JitPack; bundled by Shade. -->
<dependency>
<groupId>com.github.RonanPlugins</groupId>
@@ -76,6 +76,7 @@ public class BetterRTP extends JavaPlugin {
@Override
public void onDisable() {
playerDataManager.clear();
if (editorBridge != null) editorBridge.close();
invs.closeAll();
queue.unload();
@@ -112,6 +113,8 @@ public class BetterRTP extends JavaPlugin {
private void loadAll() {
foliaHandler.load();
playerDataManager.clear();
for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers())
playerDataManager.startSession(player);
files.loadAll();
settings.load();
cooldowns.load();
@@ -21,6 +21,7 @@ public class Click {
try {
Player p = (Player) e.getWhoClicked();
PlayerData data = HelperPlayer.getData(p);
if (data == null) return;
RTPInventories menu = BetterRTP.getInstance().getInvs();
menu.getInv(data.getMenu().getInvType()).clickEvent(e);
} catch (NullPointerException ex) {
@@ -38,6 +39,7 @@ public class Click {
else if (e.getWhoClicked() instanceof Player) {
// Clicks the inventory
PlayerData data = HelperPlayer.getData((Player) e.getWhoClicked());
if (data == null) return false;
if (!e.getInventory().equals(data.getMenu().getInv()))
return false;
// Clicks their own inventory
@@ -1,6 +1,7 @@
package me.SuperRonanCraft.BetterRTP.player.events;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent;
@@ -11,7 +12,8 @@ public class Damage {
}
static boolean isInInvincibleMode(Player player) {
return HelperPlayer.getData(player).getInvincibleEndTime() > System.currentTimeMillis();
PlayerData data = HelperPlayer.getData(player);
return data != null && data.getInvincibleEndTime() > System.currentTimeMillis();
}
static void onEntityDamage(EntityDamageEvent event) {
@@ -8,7 +8,6 @@ import me.SuperRonanCraft.BetterRTP.references.messages.Message_RTP;
import me.SuperRonanCraft.BetterRTP.references.messages.MessagesCore;
import me.SuperRonanCraft.BetterRTP.references.web.Updater;
import me.SuperRonanCraft.BetterRTP.references.helpers.HelperRTP;
import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent;
@@ -19,8 +18,9 @@ public class Join {
static void event(PlayerJoinEvent e) {
Player p = e.getPlayer();
getPl().getPlayerDataManager().startSession(p);
updater(p);
AsyncHandler.async(() -> getPl().getCooldowns().loadPlayer(p));
getPl().getCooldowns().loadPlayer(p);
rtpOnFirstJoin(p);
}
@@ -3,6 +3,7 @@ package me.SuperRonanCraft.BetterRTP.player.rtp.effects;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.references.file.FileOther;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
import me.SuperRonanCraft.BetterRTP.versions.AsyncHandler;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
@@ -52,8 +53,10 @@ public class RTPEffect_Potions { //Potions AND Invincibility
public void giveEffects(Player p) {
AsyncHandler.syncAtEntity(p, () -> {
PlayerData data = HelperPlayer.getData(p);
if (data == null) return;
if (invincibleEnabled)
HelperPlayer.getData(p).setInvincibleEndTime(System.currentTimeMillis() + (invincibleTime * 1000L));
data.setInvincibleEndTime(System.currentTimeMillis() + (invincibleTime * 1000L));
if (potionEnabled) {
List<PotionEffect> effects = new ArrayList<>();
for (PotionEffectType e : potionEffects.keySet()) {
@@ -6,7 +6,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.UUID;
import java.util.logging.Level;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
@@ -41,56 +41,68 @@ public class DatabasePlayers extends SQLite {
}
}
public void setupData(PlayerData data) {
if (data == null || data.player == null) {
return;
}
try {
Future<?> task = SQLiteExecutor.EXECUTOR.submit(() -> {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getSQLConnection();
ps = conn.prepareStatement("SELECT * FROM " + tables.get(0) + " WHERE " + COLUMNS.UUID.name + " = ?");
ps.setString(1, data.player.getUniqueId().toString());
/** Immutable persistence values; never retains a Bukkit player/session. */
public static final class Snapshot {
public final UUID uuid;
public final int count;
public final long cooldown;
rs = ps.executeQuery();
if (rs.next()) {
long count = rs.getLong(COLUMNS.COUNT.name);
long time = rs.getLong(COLUMNS.LAST_COOLDOWN_DATE.name);
data.setRtpCount(Math.toIntExact(count));
data.setGlobalCooldown(time);
public Snapshot(UUID uuid, int count, long cooldown) {
this.uuid = uuid;
this.count = count;
this.cooldown = cooldown;
}
public static Snapshot capture(PlayerData data) {
return new Snapshot(data.player.getUniqueId(), data.getRtpCount(), data.getGlobalCooldown());
}
}
/** Existing API: load into this session only while it is still current. */
public void setupData(PlayerData data) {
if (data == null) return;
Snapshot stored = loadData(data.player.getUniqueId());
if (stored != null)
BetterRTP.getInstance().getPlayerDataManager().applyIfCurrent(data, current -> {
current.setRtpCount(stored.count);
current.setGlobalCooldown(stored.cooldown);
});
}
public Snapshot loadData(UUID uuid) {
try {
return SQLiteExecutor.EXECUTOR.submit(() -> {
try (Connection conn = getSQLConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM " + tables.get(0) + " WHERE " + COLUMNS.UUID.name + " = ?")) {
ps.setString(1, uuid.toString());
try (ResultSet rs = ps.executeQuery()) {
if (rs.next())
return new Snapshot(uuid, Math.toIntExact(rs.getLong(COLUMNS.COUNT.name)),
rs.getLong(COLUMNS.LAST_COOLDOWN_DATE.name));
}
} catch (SQLException ex) {
BetterRTP.getInstance().getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex);
} finally {
close(ps, rs, conn);
}
});
task.get();
return null;
}).get();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
//Set a player Cooldown
/** Compatibility entry point: capture before deferring database work. */
public void setData(PlayerData data) {
try {
SQLiteExecutor.EXECUTOR.submit(() -> {
String sql = "INSERT OR REPLACE INTO " + tables.get(0) + " ("
+ COLUMNS.UUID.name + ", "
+ COLUMNS.COUNT.name + ", "
if (data != null) setData(Snapshot.capture(data));
}
public void setData(Snapshot data) {
SQLiteExecutor.EXECUTOR.submit(() -> {
String sql = "INSERT OR REPLACE INTO " + tables.get(0) + " ("
+ COLUMNS.UUID.name + ", " + COLUMNS.COUNT.name + ", "
+ COLUMNS.LAST_COOLDOWN_DATE.name + ") VALUES(?, ?, ?)";
List<Object> params = new ArrayList<Object>() {{
add(data.player.getUniqueId().toString());
add(data.getRtpCount());
add(data.getGlobalCooldown());
}};
sqlUpdate(sql, params);
});
} catch (Exception ex) {
ex.printStackTrace();
}
List<Object> params = java.util.Arrays.asList(data.uuid.toString(), data.count, data.cooldown);
sqlUpdate(sql, params);
});
}
}
@@ -39,6 +39,7 @@ public class DepPlaceholderAPI extends PlaceholderExpansion {
@Override
public String onPlaceholderRequest(Player player, String request) {
PlayerData data = HelperPlayer.getData(player);
if (data == null) return null;
if (request.equalsIgnoreCase("count")) {
return String.valueOf(data.getRtpCount());
} else if (request.startsWith("cooldown")) {
@@ -37,6 +37,7 @@ public interface RTPInventory_Defaults {
default void cacheInv(Player p, Inventory inv, RTP_INV_SETTINGS type) {
PlayerData info = HelperPlayer.getData(p);
if (info == null) return;
info.getMenu().setInv(inv);
info.getMenu().setInvType(type);
}
@@ -6,6 +6,7 @@ import org.bukkit.entity.Player;
public class HelperPlayer {
@org.jetbrains.annotations.Nullable
public static PlayerData getData(Player p) {
return getPl().getPlayerDataManager().getData(p);
}
@@ -12,7 +12,8 @@ import me.SuperRonanCraft.BetterRTP.references.rtpinfo.CooldownData;
public class PlayerData {
public boolean loading; //Is this players data loading?
public volatile boolean cooldownsLoaded;
public volatile boolean loading; //Is this players data loading?
public final Player player;
//Menus
@Getter final PlayerData_Menus menu = new PlayerData_Menus();
@@ -6,14 +6,33 @@ import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.ConcurrentHashMap;
public class PlayerDataManager {
private final Map<UUID, PlayerData> playerData = new ConcurrentHashMap<>();
public PlayerData getData(@NonNull Player p) {
return playerData.computeIfAbsent(p.getUniqueId(), uuid -> new PlayerData(p));
/** Called only by join/enable/reload lifecycle handling. */
public PlayerData startSession(@NonNull Player p) {
PlayerData data = new PlayerData(p);
playerData.put(p.getUniqueId(), data);
return data;
}
/** Lookup only: a departed or replaced session must never be recreated. */
@Nullable
public PlayerData getData(Player p) {
if (p == null) return null;
PlayerData data = playerData.get(p.getUniqueId());
return data != null && data.player == p ? data : null;
}
public void applyIfCurrent(PlayerData session, Consumer<PlayerData> update) {
playerData.computeIfPresent(session.player.getUniqueId(), (id, current) -> {
if (current == session) update.accept(current);
return current;
});
}
@Nullable
@@ -26,6 +45,6 @@ public class PlayerDataManager {
}
public void clear(Player p) {
playerData.remove(p.getUniqueId());
playerData.computeIfPresent(p.getUniqueId(), (id, data) -> data.player == p ? null : data);
}
}
@@ -2,7 +2,8 @@ package me.SuperRonanCraft.BetterRTP.references.rtpinfo;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.HashMap;
import java.util.UUID;
import javax.annotation.Nullable;
@@ -15,6 +16,7 @@ import lombok.Getter;
import me.SuperRonanCraft.BetterRTP.BetterRTP;
import me.SuperRonanCraft.BetterRTP.references.database.DatabaseCooldowns;
import me.SuperRonanCraft.BetterRTP.references.database.DatabaseHandler;
import me.SuperRonanCraft.BetterRTP.references.database.DatabasePlayers;
import me.SuperRonanCraft.BetterRTP.references.file.FileOther;
import me.SuperRonanCraft.BetterRTP.references.player.HelperPlayer;
import me.SuperRonanCraft.BetterRTP.references.player.playerdata.PlayerData;
@@ -26,12 +28,11 @@ public class CooldownHandler {
@Getter boolean enabled, loaded, cooldownByWorld;
@Getter private int defaultCooldownTime; //Global Cooldown timer
private int lockedAfter; //Rtp's before being locked
private final List<Player> downloading = new CopyOnWriteArrayList<>();
public void load() {
FileOther.FILETYPE config = FileOther.FILETYPE.CONFIG;
enabled = config.getBoolean("Settings.Cooldown.Enabled");
downloading.clear();
loaded = false;
if (enabled) {
defaultCooldownTime = config.getInt("Settings.Cooldown.Time");
@@ -62,6 +63,7 @@ public class CooldownHandler {
public void add(Player player, World world) {
if (!enabled) return;
PlayerData playerData = getData(player);
if (playerData == null) return;
if (cooldownByWorld) {
Map<World, CooldownData> cooldowns = playerData.getCooldowns();
CooldownData data = cooldowns.getOrDefault(world, new CooldownData(player.getUniqueId(), 0L));
@@ -69,7 +71,7 @@ public class CooldownHandler {
data.setTime(System.currentTimeMillis());
playerData.setGlobalCooldown(data.getTime());
cooldowns.put(world, data);
savePlayer(player, world, data, false);
savePlayer(playerData, world, data, false);
} else
add(player);
}
@@ -77,18 +79,19 @@ public class CooldownHandler {
private void add(Player player) {
if (!enabled) return;
PlayerData playerData = getData(player);
if (playerData == null) return;
playerData.setRtpCount(playerData.getRtpCount() + 1);
playerData.setGlobalCooldown(System.currentTimeMillis());
savePlayer(player, null, null, false);
savePlayer(playerData, null, null, false);
}
@Nullable
public CooldownData get(Player p, World world) {
PlayerData data = getData(p);
if (data == null) return null;
if (cooldownByWorld) {
Map<World, CooldownData> cooldownData = getData(p).getCooldowns();
if (data != null)
return cooldownData.getOrDefault(world, null);
Map<World, CooldownData> cooldownData = data.getCooldowns();
return cooldownData.getOrDefault(world, null);
} else if (data.getGlobalCooldown() > 0) {
return new CooldownData(p.getUniqueId(), data.getGlobalCooldown());
}
@@ -102,73 +105,87 @@ public class CooldownHandler {
}
public boolean locked(Player player) {
return lockedAfter > 0 && getData(player).getRtpCount() >= lockedAfter;
PlayerData data = getData(player);
return lockedAfter > 0 && data != null && data.getRtpCount() >= lockedAfter;
}
public void removeCooldown(Player player, World world) {
if (!enabled) return;
PlayerData playerData = getData(player);
if (playerData == null) return;
CooldownData cooldownData = playerData.getCooldowns().getOrDefault(world, null);
if (cooldownData != null) {
if (lockedAfter > 0) {
if (playerData.getRtpCount() <= 0) { //Remove from file as well
savePlayer(player, world, cooldownData, true);
getData(player).getCooldowns().put(world, null);
savePlayer(playerData, world, cooldownData, true);
playerData.getCooldowns().remove(world);
} else { //Keep the player cached
savePlayer(player, world, cooldownData, false);
savePlayer(playerData, world, cooldownData, false);
}
} else { //Remove completely
getData(player).getCooldowns().remove(world);
savePlayer(player, world, cooldownData, true);
playerData.getCooldowns().remove(world);
savePlayer(playerData, world, cooldownData, true);
}
} else if (!cooldownByWorld) {
getData(player).setGlobalCooldown(0);
savePlayer(player, null, null, true);
playerData.setGlobalCooldown(0);
savePlayer(playerData, null, null, true);
}
}
private void savePlayer(Player player, @Nullable World world, @Nullable CooldownData data, boolean remove) {
AsyncHandler.async(() -> {
if (world != null && data != null && getDatabaseWorlds() != null) { //Per World enabled?
if (!remove)
getDatabaseWorlds().setCooldown(world, data);
else
getDatabaseWorlds().removePlayer(data.getUuid(), world);
}
DatabaseHandler.getPlayers().setData(getData(player));
private void savePlayer(PlayerData session, @Nullable World world, @Nullable CooldownData data, boolean remove) {
DatabasePlayers.Snapshot snapshot = DatabasePlayers.Snapshot.capture(session);
CooldownData cooldown = data == null ? null : new CooldownData(data.getUuid(), data.getTime());
DatabaseCooldowns worlds = getDatabaseWorlds();
// Submit player values now, preserving submission order and avoiding a later lookup.
DatabaseHandler.getPlayers().setData(snapshot);
if (world != null && cooldown != null && worlds != null) {
AsyncHandler.async(() -> {
if (remove) worlds.removePlayer(cooldown.getUuid(), world);
else worlds.setCooldown(world, cooldown);
});
}
}
/** Capture the session before scheduling; completion cannot affect a reconnect. */
public void loadPlayer(Player player) {
if (!isEnabled()) {
return;
if (!isEnabled()) return;
PlayerData session = getData(player);
if (session == null) return;
synchronized (session) {
if (session.loading || session.cooldownsLoaded) return;
session.loading = true;
}
PlayerData playerData = getData(player);
if (playerData == null) {
return;
}
downloading.add(player);
try {
if (getDatabaseWorlds() != null) { //Per World enabled?
for (World world : Bukkit.getWorlds()) {
//Cooldowns
CooldownData cooldown = getDatabaseWorlds().getCooldown(player.getUniqueId(), world);
if (cooldown != null)
playerData.getCooldowns().put(world, cooldown);
UUID uuid = player.getUniqueId();
List<World> worlds = Bukkit.getWorlds();
DatabaseCooldowns databaseWorlds = getDatabaseWorlds();
AsyncHandler.async(() -> {
try {
if (getData(player) != session) return;
Map<World, CooldownData> cooldowns = new HashMap<>();
if (databaseWorlds != null) {
for (World world : worlds) {
CooldownData cooldown = databaseWorlds.getCooldown(uuid, world);
if (cooldown != null) cooldowns.put(world, cooldown);
}
}
DatabasePlayers.Snapshot stored = DatabaseHandler.getPlayers().loadData(uuid);
BetterRTP.getInstance().getPlayerDataManager().applyIfCurrent(session, current -> {
current.getCooldowns().putAll(cooldowns);
if (stored != null) {
current.setRtpCount(stored.count);
current.setGlobalCooldown(stored.cooldown);
}
current.cooldownsLoaded = true;
});
} finally {
session.loading = false;
}
//Player Data
DatabaseHandler.getPlayers().setupData(playerData);
} finally {
downloading.remove(player);
}
});
}
public boolean loadedPlayer(Player player) {
return !downloading.contains(player);
PlayerData data = getData(player);
return data != null && !data.loading;
}
@Nullable
@@ -0,0 +1,116 @@
package me.SuperRonanCraft.BetterRTP.references.player.playerdata;
import me.SuperRonanCraft.BetterRTP.references.database.DatabasePlayers;
import org.bukkit.entity.Player;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.UUID;
import static org.junit.Assert.*;
public class PlayerSessionTest {
private Player player(UUID id) {
return (Player) Proxy.newProxyInstance(Player.class.getClassLoader(), new Class<?>[]{Player.class},
(proxy, method, args) -> {
if (method.getName().equals("getUniqueId")) return id;
if (method.getName().equals("hashCode")) return System.identityHashCode(proxy);
if (method.getName().equals("equals")) return proxy == args[0];
throw new UnsupportedOperationException(method.getName());
});
}
@Test public void deferredLookupAndLoadCannotRestoreDepartedSession() {
PlayerDataManager manager = new PlayerDataManager();
Player player = player(UUID.randomUUID());
PlayerData session = manager.startSession(player);
manager.clear(player);
assertNull(manager.getData(player));
manager.applyIfCurrent(session, data -> fail("Departed session was updated"));
assertNull(manager.getData(player.getUniqueId()));
}
@Test public void oldCallbacksAndQuitCannotAffectReconnect() {
PlayerDataManager manager = new PlayerDataManager();
UUID id = UUID.randomUUID();
Player oldPlayer = player(id), newPlayer = player(id);
PlayerData old = manager.startSession(oldPlayer);
manager.clear(oldPlayer);
PlayerData current = manager.startSession(newPlayer);
manager.applyIfCurrent(old, data -> data.setRtpCount(99));
manager.clear(oldPlayer);
assertNull(manager.getData(oldPlayer));
assertSame(current, manager.getData(newPlayer));
assertSame(newPlayer, current.player);
assertEquals(0, current.getRtpCount());
}
@Test public void reloadInvalidatesOldLoadEvenForSamePlayerObject() {
PlayerDataManager manager = new PlayerDataManager();
Player player = player(UUID.randomUUID());
PlayerData old = manager.startSession(player);
manager.clear();
PlayerData current = manager.startSession(player);
manager.applyIfCurrent(old, data -> fail("Old reload generation was updated"));
manager.applyIfCurrent(current, data -> data.setRtpCount(7));
assertEquals(7, current.getRtpCount());
}
@Test public void pendingSaveKeepsCapturedValuesAfterMutationAndQuit() {
PlayerDataManager manager = new PlayerDataManager();
Player player = player(UUID.randomUUID());
PlayerData data = manager.startSession(player);
data.setRtpCount(12);
data.setGlobalCooldown(123456L);
DatabasePlayers.Snapshot pending = DatabasePlayers.Snapshot.capture(data);
data.setRtpCount(0);
data.setGlobalCooldown(0);
manager.clear(player);
assertEquals(player.getUniqueId(), pending.uuid);
assertEquals(12, pending.count);
assertEquals(123456L, pending.cooldown);
assertNull(manager.getData(player));
}
@Test public void deferredDatabaseWriterUsesSnapshotAfterQuit() throws Exception {
PlayerDataManager manager = new PlayerDataManager();
Player player = player(UUID.randomUUID());
PlayerData data = manager.startSession(player);
data.setRtpCount(23);
data.setGlobalCooldown(987654L);
java.util.concurrent.CountDownLatch release = new java.util.concurrent.CountDownLatch(1);
java.util.concurrent.atomic.AtomicReference<java.util.List<Object>> written =
new java.util.concurrent.atomic.AtomicReference<>();
DatabasePlayers database = new DatabasePlayers() {
@Override protected boolean sqlUpdate(String sql, java.util.List<Object> params) {
written.set(params);
return true;
}
};
// Table setup without starting Bukkit or opening a database connection.
java.lang.reflect.Field tables = database.getClass().getSuperclass().getSuperclass().getDeclaredField("tables");
tables.setAccessible(true);
tables.set(database, java.util.Collections.singletonList("Players"));
java.util.concurrent.ExecutorService executor =
me.SuperRonanCraft.BetterRTP.references.database.SQLiteExecutor.EXECUTOR;
executor.submit(() -> {
try { release.await(5, java.util.concurrent.TimeUnit.SECONDS); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
try {
database.setData(data);
data.setRtpCount(0);
data.setGlobalCooldown(0);
manager.clear(player);
} finally {
release.countDown();
}
executor.submit(() -> {}).get(5, java.util.concurrent.TimeUnit.SECONDS);
assertEquals(java.util.Arrays.asList(player.getUniqueId().toString(), 23, 987654L), written.get());
assertNull(manager.getData(player));
}
@Test public void lookupNeverCreatesSessionAndAcceptsNull() {
PlayerDataManager manager = new PlayerDataManager();
assertNull(manager.getData((Player) null));
assertNull(manager.getData(player(UUID.randomUUID())));
}
}
+114
View File
@@ -0,0 +1,114 @@
# BetterRTP memory-retention analysis
Reviewed 2026-11-18 at commit `04309fb`; core POM version 3.6.13. Scope: BetterRTP-Core player lifecycle, cooldown persistence, RTP execution, menus, queues, scheduling, and shutdown. Addons were screened but are not covered by the conclusions below. This is source analysis plus an isolated Java reproduction, not a production heap diagnosis. No plugin behavior was changed.
All source references below are relative to `BetterRTP-Core/src/main/java/me/SuperRonanCraft/BetterRTP/`.
## Implementation status: deferred player lookups
Finding 1 has now been addressed in the working tree. The findings below describe the original reviewed commit; the other issues remain separate work.
- Sessions are created explicitly on join and for online players during enable/reload, and cleared on quit/disable. `getData(Player)` is now a nullable, non-creating lookup that rejects a different Player instance for the same UUID. External integrations using this API must handle absent sessions.
- Cooldown loads capture the session before scheduling, avoid duplicate loads, and apply results through an atomic current-session check. Old results cannot update a replacement session or repopulate the map.
- Player saves capture immutable UUID/count/timestamp values before executor submission. Per-world saves copy the cooldown timestamp before scheduling. Deferred writers do not look up or capture PlayerData/Player.
- Core placeholder, menu, damage, and effect callers handle absent session data.
- Validation: `mvn -o -q -f BetterRTP-Core/pom.xml test` passed six regression tests, including a blocked database executor released after session mutation/quit. Quit, reconnect, reload, and non-creating reads are covered. Live Paper/Folia integration has not been exercised.
## 1. High: deferred player lookups recreate cache entries after quit
Evidence: `references/player/playerdata/PlayerDataManager.java:15`, `PlayerData.java:16`, `references/player/HelperPlayer.java:13`, `player/events/Join.java:25`, `references/rtpinfo/CooldownHandler.java:130-166`.
`getData(Player)` is a creating operation: `computeIfAbsent` installs a PlayerData containing a strong, final Player reference. Neither this method nor loadPlayer checks whether that player session remains active. Quit only removes the UUID from this map.
Two concrete sequences:
1. Join schedules async loadPlayer(p); player quits and the cache is cleared; the async task starts and getData(p) creates a new entry for the departed player.
2. A cooldown change schedules savePlayer(p); player quits; the save callback calls `DatabaseHandler.getPlayers().setData(getData(player))`, recreating the cache entry.
The entry has no expiry or offline sweep. It remains until another explicit clear for that UUID or a plugin reload. A stream of different departing players can grow the map beyond the online population. Reference path: plugin -> PlayerDataManager -> map -> PlayerData -> Player. The exact retained bytes behind Player require heap inspection; this does not establish that every loaded chunk is retained by each player.
The save race also risks overwriting persisted count/global cooldown with defaults: the callback can obtain a newly created empty PlayerData instead of the state that originally triggered the save. If the player reconnects while the stale entry exists, getData(newPlayer) returns data whose final player field still refers to the previous session. UUID keys alone do not solve this.
Important distinction: when loadPlayer obtained PlayerData before quit, updating that detached object afterward does not itself reinsert it. The problematic insertion is the creating lookup after removal. ConcurrentHashMap makes map operations safe but does not make join/quit/callback ordering correct.
Validation: compiled the actual, unmodified PlayerDataManager and PlayerData sources with minimal Bukkit/annotation/menu stubs. Simulated 1,000 join -> clear -> deferred lookup sequences: 1,000 entries remained. Reconnecting with a different Player instance and the same UUID returned the old Player reference. This validates cache semantics, not real scheduler timing or production incidence. Reproduction is in `/tmp/betterrtp-retention-2sz2g7g5/Repro.java` for this workspace session.
Recommended correction: create session state explicitly on join; separate non-creating lookup from creation; invalidate the session on quit; carry a session token through callbacks. Save immutable UUID/count/timestamp snapshots captured before scheduling, without looking up PlayerData in the writer. Apply loaded results only if the original session is still current. An isOnline check alone still leaves check/remove/insert and reconnect races.
## 2. High: RTP operation map has permanent retention paths
Evidence: `player/PlayerInfo.java:19,45-59`, `player/rtp/RTP.java:82-94`, `RTPDelay.java:31-36`, `RTPPlayer.java:64-76`, `RTPTeleport.java:55-71`, and `player/events/Leave.java:9-12`.
`PlayerInfo.rtping` is a HashMap keyed by Player. RTP inserts before firing the teleport pre-event. If another plugin cancels that event, both instant and delayed paths stop without removing the entry. This is a direct persistent retention path, even without a database race. Quit does not clear it; PlayerInfo.unload and unloadAll are private and never invoked.
Additional ways to strand the entry:
- The chunk-loading continuation has no exceptional completion handler. Its surrounding catch also silently discards Throwable without cleanup.
- teleportAsync uses thenRun, so exceptional completion skips cleanup. Errors thrown by afterTeleport also skip the later removal.
- A false Boolean teleport result still runs the success path because thenRun ignores the result; this is a correctness issue separate from retention.
Ordinary completion can remove an entry; this is not a claim that every RTP leaks. The cancellation and failure paths make retention possible without a later cleanup guarantee. Player keys can retain distinct disconnected session objects across reconnects.
Recommended correction: centralize idempotent operation completion and use it for success, cancellation, exceptions, quit, reload, and disable. Scope removal to the operation/session so an old callback cannot clear a newer request. Handle both exceptional completion and unsuccessful teleport results. Use thread-safe or correctly scheduler-confined state for supported Folia execution.
## 3. High/medium: RTP keeps searching after disconnect
Evidence: `player/rtp/RTPDelay.java:72-78`, `RTPPlayer.java:38-114`, `RTPTeleport.java:40-85`, and `player/rtp/effects/RTPEffect_Potions.java:56`.
Quit does not cancel a delay or in-progress search. The delay checks rtping, which quit does not clear. Search callbacks do not verify online/session/operation state before generating locations, loading chunks, charging, adding cooldowns, or teleporting. Later cooldown and effect lookups can recreate PlayerData as in finding 1.
Ordinary failed-location retries are limited by maxAttempts, so these callbacks alone are not necessarily a permanent leak. They are avoidable post-quit work and temporary Player retention that can feed permanent caches. An unresolved chunk future can prolong retention; no application timeout exists.
A separate retry bug exists at RTPPlayer.java:46-49: when the location event is cancelled, recursive randomlyTeleport runs before attempts is incremented. Repeated cancellation can cause stack overflow instead of reaching the attempt limit. Treat this as a control-flow/resource-exhaustion bug, not proof of a growing heap cache.
Recommended correction: cancel the logical operation on quit, check its token at every async boundary and before side effects, bound its lifetime, and guarantee terminal cleanup. Do not assume cancelling a future stops underlying chunk IO. Count attempts before retrying and schedule retries without recursive stack growth.
## 4. Medium: settings menu maps retain players
Evidence: `player/PlayerInfo.java:16-17,31-36,41-66`, `references/invs/types/RTPInvCoordinates.java:18-22`, `RTPInvWorlds.java:55`, `references/invs/RTPInventories.java:22-29`.
Menu navigation writes Player keys into invWorld and invNextInv. Quit does not clear these maps. The apparent reload cleanup is ineffective: closeAll gates cleanup on playerExists, which checks the legacy invs map; its only insertion method is commented out. Offline users would be skipped by closeAll's online-player loop anyway. No InventoryCloseEvent handler performs cleanup in the core listener.
This is a source-confirmed retention path for users who navigate those settings screens. It affects fewer players than the general cooldown race, but does not require async timing.
Recommended correction: consolidate menu state into session-owned data or explicitly remove all menu references on quit and clear them on reload/disable. Close inventory cleanup must use the active menu state, not the unused legacy map.
## 5. Medium: database backlog and executor lifecycle
Evidence: `references/database/SQLiteExecutor.java:7`, `DatabasePlayers.java:49-85`, `DatabaseQueue.java:63-95`, `BetterRTP.java:78-83`.
A static single-thread executor serves player and queue work, has an unbounded pending-task queue, and is never shut down by plugin code. Writes capture PlayerData, which holds Player. Several callers block on Future.get without an application timeout while holding their own captured Player/world state. Under sustained IO slowdown, queued tasks and waiting async callers can retain an increasing population of objects. This is a conditional backlog, not proof that normal successful queries permanently leak.
After first use, the executor also leaves a worker running across plugin disable. This is a lifecycle leak risk when unloading/replacing the plugin in-process; exact classloader roots should be verified in a heap dump. It is distinct from an ordinary `/rtp reload`, which does not create a fresh static executor.
Recommended correction: own the executor in the plugin lifecycle, define a bounded pending-work policy, snapshot primitive persistence data, expose queue depth/age, and drain/shut down explicitly. Avoid blocking worker threads waiting for other workers. Shutdown must coordinate pending saves before clearing session state.
## 6. Medium/conditional: queue generation can outlive reload
Evidence: `references/rtpinfo/QueueGenerator.java:33-66,165-204`, `QueueHandler.java:48-51`.
Only the latest queueGenerator delayed task is tracked. The initial generate delay is not retained; in-flight chunk/database continuations can call queueGenerator after unload. Concurrent low-queue requests can each enter generate before generating becomes true. Reload or demand bursts can therefore leave multiple chains active and make cancellation incomplete. A request can carry WorldPlayer via RTPWorld, retaining a player through that chain.
This is a lifecycle/concurrency risk, not a demonstrated indefinitely growing in-memory location cache. DatabaseQueue queries explicitly limit results to queueMax + 1 (33). Queue contents are persisted rather than held in an unlimited core list.
Recommended correction: use a generation token and atomic single-flight admission; invalidate the generation on reload/disable and check it before each continuation schedules more work.
## Other observations and limits
- PlaceholderAPI calls creating getData before validating the request and without a null/session guard (`DepPlaceholderAPI.java:40-41`). A stale Player passed by an integration can reproduce finding 1; a null player can throw. This method itself does not issue SQL, and the core contains no active getOfflinePlayer lookup. Do not attribute automatic offline placeholder polling to this plugin without tracing the caller.
- CooldownHandler.downloading removes entries in finally. Under normal completion it is not a permanent leak, although blocked database work prolongs retention. It also allows duplicate loads.
- Most query paths explicitly close JDBC resources. SQLite.close wraps all closes in a single try, so one close failure can prevent subsequent cleanup; use independent try-with-resources. This is exception-path hardening, not evidence that every query leaks connections.
- Metrics' timer cancels when it next notices the plugin disabled, so it can retain the old plugin until that scheduled check (up to roughly 30 minutes). It is not necessarily permanent.
- Logger setup closes the prior file handler. LogUploader bounds uploaded file content. Neither supplied a stronger explanation for offline Player retention.
- No production heap, live server, or user logs were available. No full plugin integration tests were run. External libraries, BetterSync internals, and addon-specific lifecycle bugs are outside this report's validated scope.
## Fix order and validation
1. Introduce explicit session ownership/non-creating reads and snapshot-based persistence.
2. Centralize RTP completion, cancel on quit, and cover cancellation/failure/timeout branches.
3. Remove legacy menu references on quit/reload/disable.
4. Bound and close database work; invalidate queue-generation continuations on reload.
Regression scenarios should deliberately control callback ordering: quit before join-load starts; quit before save starts; reconnect before an old callback finishes; cancelled pre-event in both delay modes; exceptional chunk/teleport futures; exception during post-teleport effects; quit during delay/search; menu use then quit; reload during queue generation; database backlog then shutdown.
For production confirmation, compare retained objects after equivalent join/RTP/quit cycles and after pending work drains. Inspect strong paths from BetterRTP to PlayerDataManager.playerData, PlayerInfo.rtping/invWorld/invNextInv, executor pending tasks, and RTP callback/listener instances. Count offline Player objects in those structures, oldest operation age, database queue depth, and outstanding generation chains. A rising heap before garbage collection alone is insufficient; distinguish live retained objects from allocation churn, ordinary loaded chunks, and work that eventually drains. Expected steady state: no departed session in player/menu/operation maps and no stale callback able to recreate it.