Skip to content

Fix menu holders and update tasks leaking when a player quits while a menu opens - #325

Open
Robin-qwerty wants to merge 1 commit into
HelpChat:mainfrom
Robin-qwerty:fix/menu-holder-quit-leak
Open

Robin-qwerty wants to merge 1 commit into
HelpChat:mainfrom
Robin-qwerty:fix/menu-holder-quit-leak

Conversation

@Robin-qwerty

Copy link
Copy Markdown

Summary

If a player disconnects in the short window between running a menu command and the menu actually opening, DeluxeMenus registers a MenuHolder for the offline player anyway and starts its repeating tasks. Nothing ever closes that holder, so it stays in Menu.menuHolders and its async placeholder-update task runs every update_interval seconds until the server restarts.

This was confirmed with heap dumps on a production server (1.14.1-Release and 1.14.2-DEV). After 38 h there were 11 stuck holders, all for players who disconnected in the same second they ran /fight, each with a live CraftAsyncTask → MenuHolder$2 re-evaluating placeholders for an offline player. That is roughly one leak per ~1,900 opens.

Root cause

Opening a menu is split across threads and at least one tick:

  1. Menu.openMenu (main thread) checks requirements and starts an async build.
  2. The async build evaluates view requirements and builds the inventory, then schedules a sync step.
  3. The sync step calls openInventory, adds the holder to menuHolders and starts the refresh and update tasks, without checking whether the player is still there.

If the player quits between 1 and 3, PlayerListener.onLeave has nothing to close, because the holder isn't registered yet. Step 3 then registers it for a player who is gone:

sequenceDiagram
    autonumber
    participant P as Player
    participant M as Main thread
    participant A as Async thread
    participant S as Scheduler

    P->>M: /fight
    M->>M: openMenu(): new MenuHolder, check requirements
    M->>A: runTaskAsynchronously(build)
    P--xM: disconnects
    M->>M: PlayerQuitEvent → closeMenu()
    Note over M: holder not registered yet,<br/>nothing to close
    A->>A: build inventory + items
    A->>M: runTask(open step)
    M->>M: openInventory(offline player)
    M->>M: menuHolders.add(holder) ❌
    M->>S: startUpdatePlaceholdersTask() ❌
    loop every update_interval, until restart
        S->>A: MenuHolder$2.run() for an offline player
    end
Loading

Two smaller problems in the same lifecycle:

  • Second leak path: refreshMenu()'s sync stage restarts the update task when updateTask == null. closeMenu sets it to null, so a refresh that finishes just after the menu closed (for example on quit) starts a new update task on a closed holder. This affects menus with refresh: true.
  • Off-thread writes: refreshMenu() called Menu.closeMenu from the async thread. That writes to the non-thread-safe HashSet, and it closes whatever menu the player has open now, which may be a newer one. menuHolders is also read off the main thread by %deluxemenus_is_in_menu% and %deluxemenus_opened_menu%, for example when TAB or a scoreboard evaluates placeholders async.

Side effect found by reading the code (not observed in the report): holders are looked up by player name. If a leaked player rejoins, the stale holder counts as their open menu: clicks in their own inventory are cancelled and can run the stale menu's slot actions, and the first inventory they open is closed again by onOpen.

The fix

1. The open step only goes ahead if this open is still wanted

A new pendingOpens map (UUID → MenuHolder, concurrent) records the newest open still being built for each player.

  • openMenu puts the holder in pendingOpens once requirements pass.
  • PlayerQuitEvent removes it (Menu.cancelPendingOpen).
  • The async build skips the work if it is no longer the pending open.
  • The sync step only continues if it can remove its own entry and viewer.isConnected() is still true.

isConnected() checks this exact Player object; isOnline() would also be true if the same player had already rejoined. The return value of openInventory is now checked as well: null means the open didn't happen.

flowchart TD
    A["Sync open step<br/>(main thread)"] --> B{"pendingOpens.remove(uuid, holder)<br/>and viewer.isConnected()?"}
    B -- "no: player quit,<br/>or a newer open replaced this one" --> X1["holder.markClosed()<br/>nothing registered, no tasks"]
    B -- yes --> C["close the previous menu, if any"]
    C --> D{"openInventory(...) != null?"}
    D -- "no: open was cancelled" --> X2["holder.markClosed()"]
    D -- yes --> E["menuHolders.add(holder)"]
    E --> F["start refresh / update tasks"]
    F --> G["fire DeluxeMenusOpenMenuEvent"]

    style X1 fill:#fde2e1,stroke:#c0392b
    style X2 fill:#fde2e1,stroke:#c0392b
    style G fill:#e3f4e1,stroke:#27ae60
Loading

Because both the quit and the open step run on the main thread, one always happens fully before the other. Either the menu is registered before the quit (and the quit closes it), or the quit removes the pending entry and the open step drops it.

2. Holders know when they are closed

MenuHolder gets a volatile boolean closed and a markClosed() that sets it and stops both tasks. closeMenu and closeMenuForShutdown use it; the shutdown path now also stops the refresh task, which it didn't before.

  • startRefreshTask() and startUpdatePlaceholdersTask() do nothing on a closed holder.
  • refreshMenu() bails out if the holder is closed, both before the async part and in its sync stage, so it can no longer restart the update task after close.
  • When a refresh finds nothing visible, it now closes the menu on the main thread, and only if this holder is still the player's open menu.

3. Safety net: repeating tasks stop themselves

Both repeating tasks start with stopIfAbandoned(this). If the holder is closed or its player is no longer connected, the task cancels itself. If the holder was never closed, it is also removed from menuHolders on the main thread (Menu.discardHolder). Even if some other path ever leaks a holder, its tasks can no longer run until restart.

4. Thread-safe menuHolders

menuHolders is now ConcurrentHashMap.newKeySet(), a drop-in for the HashSet that is safe for the existing off-thread reads.

Behavior changes

Before After
Player quits while a menu is opening Holder + tasks leak until restart Open is dropped, nothing leaks
Two openMenu() calls while the first is still building Both open one after another; a slow older build could replace the newer menu The newest open wins; the older one is dropped
InventoryOpenEvent cancelled (for example player sleeping) Holder still registered, tasks still started Not registered, no tasks
DeluxeMenusOpenMenuEvent Fired even if the open didn't happen Fired only when the inventory actually opened

Not changed: lastOpenedMenus (used by %deluxemenus_last_menu%) is still kept after quit. A periodic sweep (suggested in the report) was left out because the self-cancelling tasks already cover it.

Related

This PR and the async /dm reload PR (claude/relaxed-fermat-fjsevw) both change Menu.java, so whichever merges second will need a small conflict fix: that PR changes menuHolders to a Map<UUID, MenuHolder>, and this one makes it concurrent and adds pendingOpens. The combined version has already been built and tested locally.

🤖 Generated with Claude Code

… menu opens

Opening a menu builds the inventory async and opens it in a later tick.
That sync step never checked whether the player was still there, so a
player who quit in between got a MenuHolder registered and its repeating
update/refresh tasks started, and nothing ever cancelled them.

- Track the newest in-flight open per player (pendingOpens). Quitting
  cancels it, a newer open replaces it, and the sync step only opens if it
  is still the pending open and viewer.isConnected().
- Check openInventory's return value; don't register on a cancelled open.
- MenuHolder gets a closed flag: closed holders never start tasks, and
  refreshMenu() can no longer restart the update task after close.
- Repeating tasks cancel themselves if the holder is closed or the player
  disconnected, and drop an abandoned holder on the main thread.
- refreshMenu() now closes on the main thread, and only its own menu.
- menuHolders is a concurrent set (read off-thread by placeholders).
- DeluxeMenusOpenMenuEvent fires only when the inventory actually opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant