bensonsisi

Please create a plugin to delete useless chunks. Utilize mcaselector technology to delete chunks where players spend a short time (within 2 minutes). Supports game version 26.1.2.

Kodari AI
KodariApr 26 at 4:04 am 17,897 (v2)
ChunkCleanerMCA
A Minecraft plugin that tracks player dwell time per chunk and purges underused chunks directly from MCA region files. Chunks where players spent less than a configurable threshold (default 2 minutes) are deleted by zeroing their header entries in the .mca files — the same technique used by MCAselector. Supports per-world configuration, async deletion, loaded-chunk safety checks, and commands to scan, preview, and execute chunk cleanup.

Here’s my plan:

  • ChunkTimeTracker — tracks per-chunk dwell time using enter timestamps, persists binary data file across restarts

  • MCAChunkDeleter — directly manipulates .mca region files (zeros chunk location + timestamp header entries)

  • PlayerChunkListener — fires on PlayerMoveEvent (chunk-boundary only), join, and quit

  • ChunkCleanerCommand — /chunkclean scan|delete|info|reload with async deletion pipeline

  • ChunkCleanerPlugin — wires everything together, auto-saves on schedule

ChunkCleanerMCA
A Minecraft plugin that tracks player dwell time per chunk and purges underused chunks directly from MCA region files. Chunks where players spent less than a configurable threshold (default 2 minutes) are deleted by zeroing their header entries in the .mca files — the same technique used by MCAselector. Supports per-world configuration, async deletion, loaded-chunk safety checks, and commands to scan, preview, and execute chunk cleanup.

Here’s what was built:

ChunkTimeTracker — maintains a ConcurrentHashMap<world → Map<chunkKey → totalSeconds>>, committing accumulated seconds when a player leaves a chunk (move, teleport, quit, disable). Data is persisted as a compact binary file (chunk_times.dat) using DataOutputStream for fast load/save of millions of entries.

MCAChunkDeleter — implements the MCAselector technique directly in Java: reads the 4 KiB location table header of each .mca file, finds the 4-byte location entry for each target chunk by index = (chunkX & 31) + (chunkZ & 31) * 32, and overwrites it (and the matching timestamp entry) with zeroes using RandomAccessFile. Minecraft will treat those chunks as non-existent and regenerate them fresh on next load.

Commands:

Command
Effect
/chunkclean scan [world]
Shows how many chunks would be deleted (tracked-below-threshold + never-visited)
/chunkclean delete [world]
Async MCA deletion; skips currently-loaded chunks by default
/chunkclean info [world] [x] [z]
Shows dwell time, threshold, MCA existence, and deletion verdict
/chunkclean reload
Reloads
config.yml

The threshold, tracked worlds, auto-save interval, and async mode are all configurable in config.yml.

bensonsisi

I discovered that executing the delete chunk command resets all chunks, causing world data corruption.

Kodari AI
KodariApr 26 at 10:31 am 12,671 (v2)

Let me read the relevant files first.

I can see the root cause clearly. In handleDelete, the code collects all existing MCA chunks and marks any chunk not in aboveOrAtThreshold as a candidate — this includes every pre-generated chunk that existed before the plugin was installed (never tracked = never in dwellTimes = not in aboveOrAtThreshold = deleted). The entire pre-generated world gets wiped.

The fix: only delete chunks that have a dwell-time record and are below threshold. Never-visited chunks have no record and must be left alone. The untouchedCandidates block must be removed entirely from both handleDelete and handleScan.

Root cause: The handleDelete method was scanning all existing MCA chunks and treating any chunk not in aboveOrAtThreshold as a deletion candidate. Since pre-generated chunks that existed before the plugin was installed have no dwell-time record, they were never in aboveOrAtThreshold, so the entire pre-generated world was wiped.

Fix: Removed the untouchedCandidates block entirely. The deletion candidate list is now built solely from getChunksBelowThreshold — only chunks the plugin has explicitly tracked and found to be under the threshold are ever deleted. Pre-generated or never-visited chunks have no tracking record and are completely ignored. The same incorrect logic was cleaned up in handleScan as well.

bensonsisi

All chunks that have been explored for more than 120 seconds must be able to be cleared; in other words, chunks that met this condition before installing this plugin also meet this condition.

Kodari AI
KodariApr 26 at 10:44 am 32,138 (v2)

Minecraft already stores built-in chunk inhabit time as the InhabitedTime NBT tag (total ticks players have spent in a chunk) inside every MCA chunk’s NBT data. Reading this gives us pre-plugin history for free.

The fix requires reading Minecraft’s built-in InhabitedTime NBT tag directly from MCA chunk data. This tag is natively incremented by the server for all history, including before the plugin was installed. I’ll add a minimal NBT scanner to MCAChunkDeleter and merge both sources in the command using max(mcaSeconds, pluginSeconds) as the effective dwell time.

Now update the command to merge MCA InhabitedTime with plugin-tracked seconds:

Also need to add Map and File imports to the command:java.io.File is already imported and Map is covered by java.util.* — no change needed.

Here’s what changed:

MCAChunkDeleter — added a full minimal NBT parser (parseInhabitedTime / scanCompoundForInhabitedTime / skipNbtPayload) plus two public methods:

  • getAllInhabitedTicks(worldFolder, dimensionPath) — scans every .mca file and returns a Map<chunkKey → ticks> by reading InhabitedTime out of each chunk’s compressed NBT. Handles both 1.18+ (top-level tag) and pre-1.18 (Level compound) formats, and all three compression types (zlib / gzip / uncompressed).

  • getInhabitedTicks(...) — single-chunk variant used by /chunkclean info.

ChunkCleanerCommand — both handleScan and handleDelete now iterate over all generated MCA chunks (not just plugin-tracked ones) and compute effectiveSeconds = max(inhabitedTicks / 20, pluginTrackedSeconds). A chunk is only deleted if its effective dwell time is below the threshold from both sources, so pre-plugin explored chunks with enough InhabitedTime are automatically preserved, and chunks explored before install that are underused are now correctly included as candidates.

bensonsisi

I discovered that disk space is not freed up after deleting blocks.

Kodari AI
KodariApr 26 at 11:05 am 25,041 (v2)

The bug is in deleteChunksFromRegionFile. It zeroes out the header entries (location + timestamp tables) for deleted chunks but leaves their data sectors untouched inside the file. The file never shrinks because the orphaned sector bytes are still on disk — only the pointers to them are removed.

The fix: after zeroing headers, compact the file by rewriting it with only the surviving chunks’ sector data packed contiguously. If all chunks in a region are deleted, delete the .mca file entirely.

Now remove the no-op lambda I left in by accident:

There’s also a bug introduced: raf.close() is called manually inside a try-with-resources, then the TWR closes it again — and worse, the file deletion happens while the TWR still holds the handle open on Windows. Fix by restructuring to return a signal and delete after the TWR exits:

Three things were wrong and are now fixed:

  • Root cause: deleteChunksFromRegionFile only zeroed the 4-byte header entry for each chunk, but the actual sector data bytes that follow the 8 KiB header were never touched — the file size never changed.

  • Fix 1 — compaction: After marking chunks deleted, surviving chunks’ raw sector data is now shifted forward to fill the gaps, the header’s sector offsets are updated to match, and raf.setLength() truncates the file to the new compacted size. This reclaims space for partial-region deletions.

  • Fix 2 — full-region delete: If every chunk in a region file is being deleted, the entire .mca file is removed with mcaFile.delete(), reclaiming 100% of that file’s space. The file handle is properly closed by the try-with-resources before delete() is called (fixing the Windows handle-leak that the previous manual raf.close() inside the TWR introduced).

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
Code
10 1,163
src/main/java/com/chunkcleaner/ChunkCleanerPlugin.java
package com.chunkcleaner;

import com.chunkcleaner.command.ChunkCleanerCommand;
import com.chunkcleaner.listener.PlayerChunkListener;
import com.chunkcleaner.tracker.ChunkTimeTracker;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;

public class ChunkCleanerPlugin extends JavaPlugin {

    private ChunkTimeTracker chunkTimeTracker;
    private BukkitTask autoSaveTask;

    @Override
    public void onEnable() {
        saveDefaultConfig();

        chunkTimeTracker = new ChunkTimeTracker(this);
        chunkTimeTracker.load();

        getServer().getPluginManager().registerEvents(new PlayerChunkListener(this, chunkTimeTracker), this);

        ChunkCleanerCommand commandExecutor = new ChunkCleanerCommand(this, chunkTimeTracker);
        getCommand("chunkclean").setExecutor(commandExecutor);
        getCommand("chunkclean").setTabCompleter(commandExecutor);

        scheduleAutoSave();

        getLogger().info("ChunkCleanerMCA enabled. Threshold: "
                + getConfig().getInt("threshold-seconds", 120) + "s");
    }

    @Override
    public void onDisable() {
        if (autoSaveTask != null) {
            autoSaveTask.cancel();
        }
        // Flush all active player sessions before saving
        chunkTimeTracker.flushAllActiveSessions();
        chunkTimeTracker.save();
        getLogger().info("ChunkCleanerMCA disabled. Data saved.");
    }

    private void scheduleAutoSave() {
        int intervalSeconds = getConfig().getInt("auto-save-interval", 300);
        long intervalTicks = intervalSeconds * 20L;
        autoSaveTask = getServer().getScheduler().runTaskTimerAsynchronously(this, () -> {
            chunkTimeTracker.save();
            if (getConfig().getBoolean("verbose", false)) {
                getLogger().info("[AutoSave] Chunk dwell-time data saved.");
            }
        }, intervalTicks, intervalTicks);
    }

    public void reloadPlugin() {
        reloadConfig();
        if (autoSaveTask != null) {
            autoSaveTask.cancel();
        }
        scheduleAutoSave();
    }
}