Files
Pithos/Pithos - Planning Report v3.md
BMX 89641b2b81 Upload files to "/"
Initial report V3 commit
2026-10-01 08:50:18 +00:00

25 KiB

Pithos - Planning Report v3

1 October 2026 - BM

Summary

Pithos is a server-side NeoForge mod that writes tar.gz backups of a dedicated server on a minute-based timer, prunes old ones by rules, and can restore one with a confirmed, cancellable command. It starts on 1.21.1 for dedicated servers only; singleplayer, a UI and the 26.3 port come later.

v3 folds in the review of v2, which you approved almost entirely. The design changes where v2 could lose data or leave a server down: a global job lock, a better snapshot method, a safer output-disk check, retention that cannot orphan or cross-delete backups, a restore with two confirmations and a cancel command, and a researched restart plan. All open choices are now settled (end of the report).

What changed since v2

  • Global job lock: one job at a time (backup, prune, restore staging, restore swap, startup tar).
  • New snapshot method: only the world is paused, every file read is checked for changes, the pause has a time limit, a checksum is stored.
  • Restore: confirm to start, confirm to stop, /backup restore cancel any time before the point of no return.
  • Safety backup now comes from the moved-aside old folders after the swap, so no play time is lost between safety backup and swap.
  • Restore is resumable: a state file lets the next start finish or roll back before the world loads (v2 could leave no world folder, so a fresh world would be generated).
  • Retention rewritten (instance-scoped, sidecar mandatory, protected backups capped, space-aware).
  • Output guard rewritten: explicit /backup init for outside paths, filesystem info shown, Docker overlay warning.
  • Symlinks: a symlinked world is followed by default (v2 would have archived the link, not the world).
  • Restart plan researched (EXIT_CODE, COMMAND, NONE modes plus loop scripts).
  • Defaults corrected: stop-time backup off, keep_last 48, UTC timestamps, gzip level 3, idle-skip off.
  • Command root configurable, /pithos always registered, because other backup mods already use /backup.
  • Build order starts with risk spikes.

Decisions so far

# Topic Decision
1 Name, id, group, licence Pithos, pithos, ch.bmxlab, GPL-2.0-or-later (ship Commons Compress LICENSE and NOTICE)
2 Scope Dedicated server only first; singleplayer and a UI later
3 Snapshot Save-pause and copy-first, switchable; improved in v3
4 Timer Interval in minutes only, no cron
5 Retention Delete when ANY limit is exceeded; newest good and protected always kept
6 Includes Whole server folder by default; absolute paths allowed
7 Restore In the mod; restores everything in the archive (caveat in Platform support)
8 Permissions Op level 4, configurable
9 Archive tar.gz only, Commons Compress bundled
10 Output disk missing Skip, log, tell ops; never write to the wrong disk
11 Default excludes logs/, crash-reports/; mods/ and libraries/ stay
12 Chat messages Ops only by default
13 Restart Must work on many launch methods; default exit code 42 (researched below)
14 Global job lock New, approved
15 Restore confirmations and cancel New, approved
16 Retention fixes New, approved
17 Better snapshot method New, approved direction
18 Windows Best-effort tier 2; restore skips mods/ and libraries/ where they cannot be renamed
19 Tiered retention v0.2 as a separate mode; v0.1 keeps the current rule

Design

Global job lock

One coordinator owns one lock with the job types BACKUP, PRUNE, RESTORE_STAGING, RESTORE_READY (staged, waiting for confirmation), RESTORE_SWAP and STARTUP_TAR.

  • A conflicting command is rejected with a message like "busy: backup running since 14:30". A timer tick that finds the lock taken is skipped and logged; missed runs are never queued.
  • delete, protect and restore refuse to touch an archive a running job is reading.
  • The stop-time backup is suppressed when a restore is stopping the server.
  • The lock is in memory; only restore also writes pithos-restore.json. Config is copied when a job starts, so a reload cannot change a job midway.

Snapshot: a better way of saving the files

v2 kept saving off for the whole archive of the whole server folder, a stuck output disk could leave saving off for hours, and it assumed files cannot change during the pause. Sources on whether unloaded chunks are still written during save-off disagree, so v3 does not rely on it (spike A).

SAVE_PAUSE in v3:

  1. Take the lock, run the output guard and the space check.
  2. Write the non-world entries (mods, libraries, config) into name.tar.gz.part with no pause. Best-effort.
  3. On the server thread: note whether saving was already off (if so refuse and tell ops; Pithos never overrides an admin's manual /save-off), then do the equivalent of /save-all flush and /save-off. Log how long the flush blocked the tick.
  4. Write the world entries. Every file is read with a stability check (size, modified time and file key before and after); if they differ it is read again, up to file_retries. A file that still changes follows on_unstable_file (WARN marks the sidecar, FAIL aborts).
  5. /save-on in a finally. It also runs on server stopping, on any exception, and when max_pause_seconds is hit (backup aborted, .part deleted, ops told).
  6. Close the tar, finish the SHA-256 (computed while streaming), read the archive back once, rename, then write the sidecar atomically.

COPY_FIRST replaces steps 3 to 5: only the world files are copied to the temp folder during the pause (same stability check), saving goes back on right after, and the tar is written from the copy.

Save-pause Copy-first
Saving off for Writing the world part of the tar Only the world copy
Extra disk None About the world size in the temp folder
Best for Small and medium worlds, low-disk servers Big worlds, busy servers

The temp folder default moved to .pithos-tmp inside the server folder (fast disk, always excluded). In v2 it sat in the output folder, so with a slow HDD as target the pause ran at HDD speed. The space check covers the temp disk and the output disk separately. Copies use Files.copy with retries; another NeoForge backup mod reports this lets Windows copy locked files, which is a hint to test.

Left for later to keep v0.1 minimal: an incremental mirror (copy only changed region files during the pause, at the cost of a permanent extra copy) and pre/post hook commands for LVM, ZFS or btrfs snapshots.

tar.gz details

  • Writer: Commons Compress via jar-in-jar. It pulls in commons-io and commons-lang3, which Minecraft also ships, so test the built jar on a real server. A small PAX tar writer of our own stays a possible fallback.
  • Long paths, big files: POSIX/PAX modes. Growing files: size taken on open, exactly that many bytes copied, zero padding and a warning if it shrank.
  • Write safety: stream to .part, rename on success, delete on failure; stale .part files and temp folders are cleaned at startup.
  • Compression: default gzip_level = 3 (region files are already compressed). Level 0 to 9 is valid, so v2 was wrong that there is no 0. Measure and adjust.
  • Integrity: SHA-256 in the sidecar enables /backup verify <id>.
  • Extraction safety: reject .., absolute names and symlink entries leaving the staging folder.
  • Names: UTC timestamps (no DST repeats); the final rename never overwrites, it adds a suffix.

What goes into the archive

  • Output, temp and staging folders and Pithos state files are excluded automatically (compared by real path).
  • Symlinks: top-level include entries and direct children of the server folder may be symlinks and are followed. Deeper links are never followed, and a nested link to a directory is logged as a warning so an empty world cannot go unnoticed.
  • Absolute includes are stored under external/<n>-<basename>/ with the original path in the sidecar. Restore writes them back only if restore.external_paths = true (default false).
  • Unreadable files are skipped with a warning by default. The README suggests excludes for Dynmap/BlueMap tiles and Distant Horizons data, and warns that live SQLite or H2 files can be corrupt in a copy.

Output guard

  • .pithos marker: a small JSON with a random id and the filesystem name and type.
  • Inside the server folder (default backups/): folder and marker are created automatically; same disk as the server, no ambiguity.
  • Outside the server folder: the first backup is refused until an op runs /backup init, which prints the resolved path and filesystem and warns if it looks like a container overlay or the server's own disk. Only then is the marker written. This closes the first-run hole where an unmounted disk's empty mount folder passed.
  • Every later run requires the marker; otherwise skip, log, tell ops. Retention, list, verify and restore use the same guard.
  • Space check: last backup size times space_safety_factor plus min_free_space_mb; copy-first adds the world size on the temp disk. If the check itself fails (some network mounts), skip with a clear error.
  • pithos-status.json (excluded from backups) holds last success, last failure with reason, and next run. Ops get a notice at login after a failed backup, so failures are visible even when nobody was online.

Retention (rewritten)

  • Identity: each server generates an instance_id once (config/pithos-instance.json) and writes it into every sidecar. Retention only considers sidecars with its own id, so servers sharing an HDD never delete each other's backups and changing name_pattern cannot orphan anything.
  • The sidecar is mandatory; write_metadata_json is removed because turning it off silently disabled pruning. It holds the protected flag, size, checksum and versions.
  • Rule: delete when ANY limit is exceeded (last N, max age, max total size); the tightest wins. Always kept: the newest good backup and every protected one.
  • Pre-restore backups are protected, do not count toward keep_last, do count toward total size, and max_pre_restore (default 3, my proposal; 0 = unlimited) limits them by unprotecting the oldest.
  • Protected backups alone over the size limit: nothing protected is deleted; warn ops.
  • Order: prune after a successful backup. If the pre-backup space check fails, prune eligible backups (never below newest good plus protected) and re-check once, else skip with an error.
  • Defaults: hourly with keep_last = 24 was one day of history; it is now 48. Tiered keeping is settled for v0.2; the README says hourly backups with keep_last = 48 give about two days of history.
  • dry_run supported; unit tests in core for every rule.

Restore flow (v3)

State: pithos-restore.json and the staging folder .pithos-restore/, both excluded from backups.

  1. /backup restore <id> validates the id (letters, digits, dots, dashes; resolved path must stay in the output folder), runs the guard, takes the lock, and checks space (staged copy plus moved-aside old state, about twice the extracted size per filesystem). It prints a summary: backup date and size, what is replaced (including config/, mods/, ops.json, whitelist.json, ban lists, pithos.toml), that the server will stop, and what the restart mode will do. Then: run /backup restore confirm within confirm_timeout_seconds, or /backup restore cancel.
  2. confirm (start): extraction into .pithos-restore/ at low priority while the server runs, with the sidecar SHA-256 checked during that single read. Each staged entry is created on the same filesystem as the live entry it replaces (beside the link target if the live entry is a symlink). Progress goes to ops.
  3. Ready: ops get "staged, N players online; /backup restore confirm to stop the server and apply, or /backup restore cancel". It auto-cancels after stop_confirm_timeout_seconds. With require_confirmation = false it goes straight to the countdown.
  4. confirm (stop): countdown (warn_seconds) with player warnings; cancel still works. At zero, pithos-restore.json is written as ARMED and the server stops normally. That is the point of no return.
  5. Swap after the world is closed: each top-level entry is renamed to <name>.pithos-old and the staged one renamed in, updating the state file after each entry. If one fails, the entries already swapped are renamed back and the old state starts again.
  6. Restart per the configured mode.
  7. At the next start, before the world opens, ARMED or SWAPPING means finish or roll back deterministically, so a missing world can never produce a fresh world. DONE starts a low-priority STARTUP_TAR (after startup_delay_seconds) that writes a protected pre-restore_<date>.tar.gz from the .pithos-old entries, verifies it, then deletes them. If that fails, the old folders are kept and ops told.
  8. Leftover staging without an ARMED state is deleted at start.

cancel works in RESTORE_STAGING, RESTORE_READY and the countdown: it stops extraction, deletes staging, clears the state and releases the lock. README consequence: config, mods, ops.json, whitelist.json and ban lists return to their backed-up state, so a restore can unban players.

Restart handling (researched)

Is there a native restart? I found none in vanilla or NeoForge. Existing restart mods use three patterns: stop and rely on a start-script loop (Auto Restarter says so), run a configured command after the server stopped (Auto Restart), or launch a detached script before the JVM exits (EasyRestart, which warns that panels then lose visibility). So the answer is: stop on purpose and let whatever started the server start it again.

restore.restart_mode:

  • EXIT_CODE (default): after the swap, flush logs and exit with restore.exit_code (default 42).
  • COMMAND: run restore.restart_command detached after the swap and exit (for example an HTTP call to a panel's power API, untested).
  • NONE: stop only; the confirmation says the server stays down.

Self-relaunch is left out of v0.1: it breaks under systemd (children are in the service cgroup), Docker (server is PID 1), panels (lost visibility) and plain terminals (background processes reading the tty can be stopped).

Launch method What exit code 42 does Setup
systemd Restart=always restarts on any exit; on-failure on non-zero. RestartForceExitStatus=42 forces it whatever Restart= says, SuccessExitStatus=42 stops it counting as a failure. systemctl stop is never restarted. Add those two lines
Docker / compose always and unless-stopped restart on any exit, on-failure on non-zero, no never; only after a successful start Set a policy; mount the output folder as a volume
Pterodactyl (Wings) Crash detection restarts unexpected exits if enabled; exit 0 only counts as a crash with detect_clean_exit_as_crash; no auto restart if the last crash was under 60 s ago (default). Console says "crashed". Keep crash detection on, or use COMMAND
Loop script (Linux terminal, tmux, screen) Restarts Shipped start-loop.sh
Plain start.sh Server stops, nothing restarts it Use the loop script
Windows .bat loop Restarts Shipped start-loop.bat (untested)
Windows service wrappers Not verified Research later

At startup Pithos logs where it seems to run (systemd, Docker, Pterodactyl or none), using environment markers I believe those tools set (to verify), only to make the confirmation message more helpful, never to change behaviour.

Spike B risk: System.exit from the server thread may deadlock with vanilla's shutdown hook (my knowledge, unverified). Plan: finish all work, flush Log4j, use Runtime.halt(code), and test that the code survives each real launcher, including wrapper programs such as a Docker image's server runner.

Platform support

  • Tier 1 (designed and tested before release): Linux with systemd, Linux terminal with the loop script, Docker, Pterodactyl.
  • Tier 2 (best effort, limits documented, not a release blocker): Windows with the loop script.
  • Jar folders: mods/ and libraries/ cannot be renamed while the JVM has their jars open on Windows, and bind-mounted folders in Docker cannot be renamed either. Where the rename fails, restore applies everything else, skips those two, and logs what to restore by hand (tar xzf). On Linux the rename is tried, with all swap code loaded before it starts since Pithos's own jar lives in mods/. This partly overrides "restore everything, always" (settled).
  • Windows also has locked files and symlink privileges. TOML paths must use forward slashes or single-quoted strings, because "D:\backups" parses \b as a backspace.

Config sketch (config/pithos.toml)

[sources]
include = ["."]                      # relative or absolute; "${world}" = the active world
exclude = ["glob:**/session.lock", "glob:**/*.tmp", "glob:logs/**", "glob:crash-reports/**"]
follow_symlinks = true               # top-level entries and direct children of the server folder only
on_unreadable = "WARN"               # WARN | FAIL

[output]
directory = "backups"                # absolute paths need /backup init, e.g. "/mnt/hdd/minecraft-backups"
name_pattern = "pithos_${date}"      # UTC yyyy-MM-dd_HH-mm-ss; .tar.gz is added
gzip_level = 3                       # 0 (store) to 9 (small)
verify_after_write = true

[snapshot]
# SAVE_PAUSE: saving off only while the world part of the archive is written. No extra disk.
# COPY_FIRST: saving off only while the world is copied to temp_directory (needs about the world size free).
mode = "SAVE_PAUSE"
temp_directory = ""                  # empty = .pithos-tmp in the server folder
max_pause_seconds = 300
file_retries = 3
on_unstable_file = "WARN"            # WARN | FAIL

[schedule]
interval_minutes = 60                # 0 disables the timer; overlapping runs are skipped
catch_up_on_start = true             # based on the last success, after startup_grace_minutes
startup_grace_minutes = 10
on_server_start = false
on_server_stop = false               # can exceed a service manager's stop timeout
skip_if_no_players_since_last = false  # chunk-loaded machines change the world without players

[retention]
enabled = true
keep_last = 48
max_age_days = 14
max_total_size_mb = 50000            # delete when ANY limit is exceeded; the tightest wins
max_pre_restore = 3                  # 0 = unlimited
dry_run = false

[safety]
min_free_space_mb = 2048
space_safety_factor = 1.2

[restore]
require_confirmation = true
confirm_timeout_seconds = 120
stop_confirm_timeout_seconds = 600
warn_seconds = 30
startup_delay_seconds = 120
external_paths = false
restart_mode = "EXIT_CODE"           # EXIT_CODE | COMMAND | NONE
exit_code = 42                       # 0 if your supervisor restarts on any exit
restart_command = ""

[commands]
root = "backup"                      # /pithos is always registered too
permission_level = 4                 # checked in one class because 26.x changed permissions

[messages]
audience = "OPS"                     # NONE, OPS, ALL

Commands: /backup now | list | status | init | verify <id> | protect <id> | unprotect <id> | delete <id> | prune | restore <id> | restore confirm | restore cancel, with tab completion for ids.

Project structure and build order

One 1.21.1 project from NeoForge's template with everything Minecraft-free in core. v2 suggested two git branches; with the core boundary I now recommend a shared Gradle subproject for core (Java 21 bytecode) from the start, so a fix is applied once and 26.3 only adds a thin NeoForge module.

pithos/
|-- core/   (no net.minecraft imports)
|   FileSelector, TarBackupJob, StabilityReader, SnapshotCopier, OutputGuard,
|   BackupIndex, RetentionPolicy, JobCoordinator, RestoreStager, RestoreState, BackupScheduler
|-- neoforge-1.21.1/ (ch.bmxlab.pithos)
|   PithosMod (@Mod dist = DEDICATED_SERVER), PithosConfig, PithosCommands,
|   PermissionGate, ServerBridge (save on/off, world path, chat, stop, halt)
|-- scripts/ start-loop.sh, start-loop.bat, pithos.service.example, docker-compose.example.yml

Build order:

  1. Spikes on a dev server (A to D below); their answers can change the design.
  2. core: file selection (symlink rules), tar.gz writer with stability reads, unit tests including a growing file.
  3. core: retention and sidecar index, instance-scoped, unit tests.
  4. core: job coordinator and restore state machine, tests for every transition and crash point.
  5. NeoForge layer: config, timer, commands, save-pause, status file.
  6. Output guard and /backup init.
  7. Copy-first.
  8. Restore: staging, two confirmations, cancel, swap, resume, restart modes, startup tar.
  9. README (per-launcher sections, secrets warning, restore consequences), loop scripts, CI, release.

Test checklist

Spikes:

  • A. Save-off: with saving off, fly away so chunks unload; do region files change?
  • B. Exit mechanics: Runtime.halt(code) versus System.exit, log flush, and the code reaching systemd, Docker, Pterodactyl and the loop scripts.
  • C. Stop order: server-stopped fires after the world is saved and closed; find the earliest point before the world opens for the resume check.
  • D. Built jar on the real Thoryx modpack: jar-in-jar with Commons Compress, a vanilla client joining, and whether the "display-test" fallback from v2 is still the right mechanism.

Behaviour:

  • Symlinked world archived as real content; restore of a symlinked entry stays on the target filesystem.
  • Kill the JVM at every restore step; the next start recovers and never creates a fresh world.
  • Cancel at each point, confirm timeouts, a typo id, a path-traversal id.
  • Output disk unmounted on first run, on a later run, and in Docker without a volume.
  • Two servers sharing one output folder never delete each other's backups.
  • Disk full during backup, staging and startup tar; backup running when restore is typed.
  • max_pause_seconds with a hanging output target.
  • Windows: locked files, skipped mods/ and libraries/, path syntax. Panel disk quota with the default config.

Settled decisions

  1. Default exit code. Settled: 42 (you left the choice to me). Non-zero works with every Docker policy, systemd on-failure and Pterodactyl crash detection; set exit_code = 0 if your supervisor restarts on any exit.
  2. Windows and the jar folders. Settled: Windows is tier 2 (best effort), and restore skips mods/ and libraries/ where they cannot be renamed, with a clear message.
  3. Tiered retention. Settled: v0.2. v0.1 keeps "delete when ANY limit is exceeded"; the README notes that hourly backups with keep_last = 48 give about two days of history. Tiered will be a separate mode that keeps the newest backup of each hour, day and week.

Risks and how the design handles them

  • Inconsistent world files: world-only pause, stability-checked reads, pause limit, spikes A and D, test on the real modpack.
  • Retention deleting the wrong files: instance-scoped, mandatory sidecar, dry run, tests, never below newest good plus protected.
  • Wrong or missing output disk: /backup init, marker, filesystem info, gating of every operation.
  • Failed or interrupted restore: two confirmations, cancel, resumable state file, deterministic rollback, safety tar from the old folders.
  • Server left down after restore: restart modes, loop scripts, startup hints; NONE says so up front.
  • Support load for a public mod: per-launcher README, tier list, status file, clear messages.
  • 26.x changes (Java 25, unobfuscated names, permissions): contained in ServerBridge, PermissionGate and the command class.
  • Secrets in backups: server.properties can hold the RCON password; the README says to protect the output folder, and files use restrictive permissions where the OS allows.
  • Name and licences: I found no existing mod called Pithos, but search CurseForge and Modrinth again before publishing. Other backup mods are studied for ideas only.

Sources

As of 1 October 2026; read as search excerpts, so confirm details in code.

From my own knowledge, not looked up: Apache-2.0 versus GPL-2.0-only, tar's size-first header, the shutdown hook and System.exit interaction, which environment markers systemd, Docker and Pterodactyl set, Windows rename behaviour for open jars, and Commons Compress dependencies. 26.3 and NeoForge status from v2 still holds. Sources from the first and second reports still apply.